Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

cli.py 20 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
  1. # -*- coding: utf-8 -*-
  2. import click, sys
  3. import copy
  4. from wandb import Api, Error, Sync, Config, __version__, __stage_dir__
  5. import random, time, os, re, netrc, logging, json, glob, io, stat, subprocess
  6. from functools import wraps
  7. from click.utils import LazyFile
  8. from click.exceptions import BadParameter, ClickException
  9. import inquirer
  10. import sys, traceback
  11. from wandb import util
  12. logger = logging.getLogger(__name__)
  13. def write_netrc(host, entity, key):
  14. """Add our host and key to .netrc"""
  15. try:
  16. normalized_host = host.split("/")[-1].split(":")[0]
  17. print("Appending to netrc %s" % os.path.expanduser('~/.netrc'))
  18. with open(os.path.expanduser('~/.netrc'), 'a') as f:
  19. f.write("""machine {host}
  20. login {entity}
  21. password {key}
  22. """.format(host=normalized_host, entity=entity, key=key))
  23. os.chmod(os.path.expanduser('~/.netrc'), stat.S_IRUSR | stat.S_IWUSR)
  24. except IOError as e:
  25. click.secho("Unable to read ~/.netrc", fg="red")
  26. return None
  27. def display_error(func):
  28. """Function decorator for catching common errors and re-raising as wandb.Error"""
  29. @wraps(func)
  30. def wrapper(*args, **kwargs):
  31. try:
  32. return func(*args, **kwargs)
  33. except Error as e:
  34. exc_type, exc_value, exc_traceback = sys.exc_info()
  35. lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  36. logger.error('\n'.join(lines))
  37. raise ClickException(e)
  38. return wrapper
  39. def editor(content='', marker='# Enter a description, markdown is allowed!\n'):
  40. message = click.edit(content + '\n\n' + marker)
  41. if message is not None:
  42. return message.split(marker, 1)[0].rstrip('\n')
  43. api = Api()
  44. # Some commands take project/entity etc. as arguments. We provide default
  45. # values for those arguments from the current project configuration, as
  46. # returned by api.settings()
  47. CONTEXT=dict(default_map=api.settings())
  48. class RunGroup(click.Group):
  49. @display_error
  50. def get_command(self, ctx, cmd_name):
  51. #TODO: check if cmd_name is a file in the current dir and not require `run`?
  52. rv = click.Group.get_command(self, ctx, cmd_name)
  53. if rv is not None:
  54. return rv
  55. return None
  56. @click.command(cls=RunGroup)
  57. @click.version_option(version=__version__)
  58. @click.pass_context
  59. def cli(ctx):
  60. """Weights & Biases
  61. If the first argument is a file in the current directory run it.
  62. wandb train.py --arg=1
  63. """
  64. pass
  65. @cli.command(context_settings=CONTEXT, help="List projects")
  66. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  67. @display_error
  68. def projects(entity, display=True):
  69. projects = api.list_projects(entity=entity)
  70. if len(projects) == 0:
  71. message = "No projects found for %s" % entity
  72. else:
  73. message = 'Latest projects for "%s"' % entity
  74. if display:
  75. click.echo(click.style(message, bold=True))
  76. for project in projects:
  77. click.echo("".join(
  78. (click.style(project['name'], fg="blue", bold=True),
  79. " - ",
  80. str(project['description']).split("\n")[0])
  81. ))
  82. return projects
  83. @cli.command(context_settings=CONTEXT, help="List runs in a project")
  84. @click.option("--project", "-p", prompt=True, envvar='WANDB_PROJECT', help="The project you wish to list runs from.")
  85. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  86. @display_error
  87. def runs(project, entity):
  88. click.echo(click.style('Latest runs for project "%s"' % project, bold=True))
  89. runs = api.list_runs(project, entity=entity)
  90. for run in runs:
  91. click.echo("".join(
  92. (click.style(run['name'], fg="blue", bold=True),
  93. " - ",
  94. (run['description'] or "").split("\n")[0])
  95. ))
  96. @cli.command(context_settings=CONTEXT, help="List local & remote file status")
  97. @click.argument("run", envvar='WANDB_RUN')
  98. @click.option("--settings/--no-settings", help="Show the current settings", default=False)
  99. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  100. @display_error
  101. def status(run, settings, project):
  102. if settings:
  103. click.echo(click.style("Current Settings", bold=True) + " (%s)" % api.settings_file)
  104. settings = api.settings()
  105. click.echo(json.dumps(
  106. settings,
  107. sort_keys=True,
  108. indent=2,
  109. separators=(',', ': ')
  110. ))
  111. click.echo(click.style("Logged in?", bold=True) + " %s\n" % bool(api.api_key))
  112. project, run = api.parse_slug(run, project=project)
  113. existing = set() #TODO: populate this set with the current files in the run dir
  114. remote = api.download_urls(project, run)
  115. not_synced = set()
  116. remote_names = set([name for name in remote])
  117. for file in existing:
  118. meta = remote.get(file)
  119. if meta and not api.file_current(file, meta['md5']):
  120. not_synced.add(file)
  121. elif not meta:
  122. not_synced.add(file)
  123. #TODO: remove items that exists and have the md5
  124. only_remote = remote_names.difference(existing)
  125. up_to_date = existing.difference(only_remote).difference(not_synced)
  126. click.echo('File status for '+ click.style('"%s/%s" ' % (project, run), bold=True))
  127. if len(not_synced) > 0:
  128. click.echo(click.style('Push needed: ', bold=True) + click.style(", ".join(not_synced), fg="red"))
  129. if len(only_remote) > 0:
  130. click.echo(click.style('Pull needed: ', bold=True) + click.style(", ".join(only_remote), fg="red"))
  131. if len(up_to_date) > 0:
  132. click.echo(click.style('Up to date: ', bold=True) + click.style(", ".join(up_to_date), fg="green"))
  133. @cli.command(context_settings=CONTEXT, help="Store notes for a future training run")
  134. @display_error
  135. def describe():
  136. path = __stage_dir__+'description.md'
  137. existing = (os.path.exists(path) and open(path).read()) or ''
  138. description = editor(existing)
  139. if description:
  140. with open(path, 'w') as file:
  141. file.write(description)
  142. click.echo("Notes stored for next training run\nCalling wandb.sync() in your training script will persist them.")
  143. @cli.command(context_settings=CONTEXT, help="Restore code and config state for a run")
  144. @click.argument("run", envvar='WANDB_RUN')
  145. @click.option("--branch/--no-branch", default=True, help="Whether to create a branch or checkout detached")
  146. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  147. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  148. @display_error
  149. def restore(run, branch, project, entity):
  150. project, run = api.parse_slug(run, project=project)
  151. commit, json_config, patch = api.run_config(project, run=run, entity=entity)
  152. if commit:
  153. branch_name = "wandb/%s" % run
  154. if branch and branch_name not in api.git.repo.branches:
  155. api.git.repo.git.checkout(commit, b=branch_name)
  156. click.echo("Created branch %s" % click.style(branch_name, bold=True))
  157. elif branch:
  158. click.secho("Using existing branch, run `git branch -D %s` from master for a clean checkout" % branch_name, fg="red")
  159. api.git.repo.git.checkout(branch_name)
  160. else:
  161. click.secho("Checking out %s in detached mode" % commit)
  162. api.git.repo.git.checkout(commit)
  163. if patch:
  164. with open(__stage_dir__+"diff.patch", "w") as f:
  165. f.write(patch)
  166. api.git.repo.git.execute(['git', 'apply', __stage_dir__+'diff.patch'])
  167. click.echo("Applied patch")
  168. config = Config()
  169. config.load_json(json_config)
  170. config.persist()
  171. click.echo("Restored config variables")
  172. @cli.command(context_settings=CONTEXT, help="Push files to Weights & Biases")
  173. @click.argument("run", envvar='WANDB_RUN')
  174. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  175. @click.option("--description", "-m", help="A description to associate with this upload.")
  176. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  177. @click.option("--force/--no-force", "-f", default=False, help="Whether to force git tag creation.")
  178. @click.argument("files", type=click.File('rb'), nargs=-1)
  179. @click.pass_context
  180. @display_error
  181. def push(ctx, run, project, description, entity, force, files):
  182. #TODO: do we support the case of a run with the same name as a file?
  183. if os.path.exists(run):
  184. raise BadParameter("Run id is required if files are specified.")
  185. project, run = api.parse_slug(run, project=project)
  186. click.echo("Updating run: {project}/{run}".format(
  187. project=click.style(project, bold=True), run=run))
  188. candidates = []
  189. if len(files) == 0:
  190. #TODO: do we want to do this?
  191. patterns = ("*.h5", "*.hdf5", "*.json", "*.meta", "*checkpoint*")
  192. for pattern in patterns:
  193. candidates.extend(glob.glob(pattern))
  194. if len(candidates) == 0:
  195. raise BadParameter("Couldn't auto-detect files, specify manually or use `wandb.add`", param_hint="FILES")
  196. choices = inquirer.prompt([inquirer.Checkbox('files', message="Which files do you want to push? (left and right arrows to select)",
  197. choices=[c for c in candidates])])
  198. files = [LazyFile(choice, 'rb') for choice in choices['files']]
  199. #TODO: Deal with files in a sub directory
  200. api.push(project, files=[f.name for f in files], run=run,
  201. description=description, entity=entity, force=force, progress=sys.stdout)
  202. @cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases")
  203. @click.argument("run", envvar='WANDB_RUN')
  204. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you want to download.")
  205. @click.option("--kind", "-k", default="all", type=click.Choice(['all', 'model', 'weights', 'other']))
  206. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  207. @display_error
  208. def pull(project, run, kind, entity):
  209. project, run = api.parse_slug(run, project=project)
  210. urls = api.download_urls(project, run=run, entity=entity)
  211. if len(urls) == 0:
  212. raise ClickException("Run has no files")
  213. click.echo("Downloading: {project}/{run}".format(
  214. project=click.style(project, bold=True), run=run
  215. ))
  216. for name in urls:
  217. if api.file_current(name, urls[name]['md5']):
  218. click.echo("File %s is up to date" % name)
  219. else:
  220. length, response = api.download_file(urls[name]['url'])
  221. with click.progressbar(length=length, label='File %s' % name,
  222. fill_char=click.style('&', fg='green')) as bar:
  223. with open(name, "wb") as f:
  224. for data in response.iter_content(chunk_size=4096):
  225. f.write(data)
  226. bar.update(len(data))
  227. @cli.command(context_settings=CONTEXT, help="Login to Weights & Biases")
  228. @display_error
  229. def login():
  230. # Import in here for performance reasons
  231. import webbrowser
  232. #TODO: use Oauth and a local webserver: https://community.auth0.com/questions/6501/authenticating-an-installed-cli-with-oidc-and-a-th
  233. url = "https://app.wandb.ai/profile"
  234. #TODO: google cloud SDK check_browser.py
  235. launched = webbrowser.open_new_tab(url)
  236. if launched:
  237. click.echo('Opening [{0}] in a new tab in your default browser.'.format(url))
  238. else:
  239. click.echo("You can find your API keys here: {0}".format(url))
  240. key = click.prompt("{warning} Paste an API key from your profile".format(
  241. warning=click.style("Not authenticated!", fg="red")),
  242. value_proc=lambda x: x.strip())
  243. host = api.settings()['base_url']
  244. if key:
  245. #TODO: get the username here...
  246. #username = api.viewer().get('entity', 'models')
  247. write_netrc(host, "user", key)
  248. @cli.command(context_settings=CONTEXT, help="Configure a directory with Weights & Biases")
  249. @click.pass_context
  250. @display_error
  251. def init(ctx):
  252. # TODO: This is commented out because we always automatically create this dir in __init__.py
  253. # however this isn't ideal, we'll litter the filesystem with wandb directories.
  254. #if(os.path.exists(__stage_dir__)):
  255. # click.confirm(click.style("This directory is already configured, should we overwrite it?", fg="red"), abort=True)
  256. click.echo(click.style("Let's setup this directory for W&B!", fg="green", bold=True))
  257. global api
  258. if api.api_key is None:
  259. ctx.invoke(login)
  260. api = Api()
  261. entity = click.prompt("What username or org should we use?", default=api.viewer().get('entity', 'models'))
  262. #TODO: handle the case of a missing entity
  263. result = ctx.invoke(projects, entity=entity, display=False)
  264. if len(result) == 0:
  265. project = click.prompt("Enter a name for your first project")
  266. description = editor()
  267. api.upsert_project(project, entity=entity, description=description)
  268. else:
  269. project_names = [project["name"] for project in result]
  270. question = inquirer.List('project', message="Which project should we use?", choices=project_names + ["Create New"])
  271. project = inquirer.prompt([question])['project']
  272. #TODO: check with the server if the project exists
  273. if project == "Create New":
  274. project = click.prompt("Enter a name for your new project")
  275. description = editor()
  276. api.upsert_project(project, entity=entity, description=description)
  277. else:
  278. ids = [res['id'] for res in result if res['name'] == project]
  279. if len(ids) > 0:
  280. api.upsert_project(project, id=ids[0], entity=entity)
  281. ctx.invoke(config_init, False)
  282. with open(os.path.join(__stage_dir__, 'settings'), "w") as file:
  283. file.write("[default]\nentity: {entity}\nproject: {project}\n".format(entity=entity, project=project))
  284. with open(os.path.join(__stage_dir__, '.gitignore'), "w") as file:
  285. file.write("*\n!config")
  286. click.echo(click.style("This directory is configured! Try these next:\n", fg="green")+
  287. """
  288. * Track runs by calling sync in your training script `{flags}`.
  289. * Run `{push}` to manually add a file.
  290. * `{config}` to add or change configuration defaults.
  291. * Pull popular models into your project with: `{pull}`.
  292. """.format(
  293. push=click.style("wandb push run_id weights.h5", bold=True),
  294. flags=click.style("import wandb; run = wandb.sync(config=tf.__FLAGS__)", bold=True),
  295. config=click.style("wandb config set batch_size=10", bold=True),
  296. pull=click.style("wandb pull models/inception-v4", bold=True)
  297. ))
  298. RUN_CONTEXT = copy.copy(CONTEXT)
  299. RUN_CONTEXT['allow_extra_args'] = True
  300. RUN_CONTEXT['ignore_unknown_options'] = True
  301. @cli.command(context_settings=RUN_CONTEXT, help="Launch a job")
  302. @click.pass_context
  303. @click.argument('program')
  304. @click.argument('args', nargs=-1)
  305. @click.option('--run_dir', default='.',
  306. help='Files in this directory will be saved to wandb. (default: \'.\'')
  307. @click.option('--glob', default='*', multiple=True,
  308. help='New files in <run_dir> that match will be saved to wandb. (default: \'*\')')
  309. @display_error
  310. def run(ctx, program, args, run_dir, glob):
  311. sync = Sync(api, dir=run_dir)
  312. # This saves our stdout, which will be the popened process's stdout as well.
  313. sync.watch(files=glob)
  314. env = copy.copy(os.environ)
  315. env['WANDB_CLI_LAUNCHED'] = '1'
  316. env['WANDB_RUN_ID'] = sync.run_id
  317. env['WANDB_RUN_DIR'] = sync.run.dir
  318. proc = util.SafeSubprocess([program] + list(args), env=env)
  319. proc.run()
  320. while True:
  321. time.sleep(1)
  322. exitcode, stdout, stderr = proc.poll()
  323. for so in stdout:
  324. sys.stdout.write(so)
  325. for se in stderr:
  326. sys.stderr.write(se)
  327. if exitcode is not None:
  328. print('wandb: job (%s) Process exited with code: %s' % (program, exitcode))
  329. break
  330. @cli.group()
  331. @click.pass_context
  332. @display_error
  333. def config(ctx):
  334. """Manage this projects configuration.
  335. Examples:
  336. wandb config set param=2 --description="Some tunning parameter"
  337. wandb config del param
  338. wandb config show
  339. """
  340. pass
  341. @config.command("init", help="Initialize a directory with wandb configuration")
  342. @display_error
  343. def config_init(prompt=True):
  344. config_path = os.path.join(os.getcwd(), __stage_dir__)
  345. config = Config()
  346. if os.path.isdir(config_path):
  347. if prompt:
  348. click.confirm(click.style("This directory is already initialized, should we overwrite it?", fg="red"), abort=True)
  349. else:
  350. os.mkdir(config_path)
  351. config.epochs_desc = "Number epochs to train over"
  352. config.epochs = 32
  353. config.persist()
  354. if prompt:
  355. click.echo("""Configuration initialized, use `wandb config set` to set parameters. Then in your training script:
  356. import wandb
  357. conf = wandb.sync()
  358. conf.batch_size
  359. """)
  360. @config.command(help="Show the current config")
  361. @click.option("--format", help="The format to dump the config as", default="python", type=click.Choice(['python', 'yaml', 'json']))
  362. @display_error
  363. def show(format, changed=[], diff=False):
  364. if len(changed) == 0 and diff:
  365. click.secho("No parameters were changed", fg="red")
  366. elif diff:
  367. click.echo("%i parameters changed: " % len(changed))
  368. config = Config()
  369. if len(vars(config)) == 0:
  370. click.secho("No configuration found in this directory, run `wandb config init`", fg="red")
  371. if format == "yaml":
  372. click.echo("%s" % config)
  373. elif format == "json":
  374. click.echo(json.dumps(vars(config)))
  375. elif format == "python":
  376. res = ""
  377. for key in set(config.keys + changed):
  378. if config.desc(key):
  379. res += "# %s\n" % config.desc(key)
  380. style = None
  381. if key in changed:
  382. style = "green" if config.get(key) else "red"
  383. res += click.style("%s=%r\n" % (key, config.get(key)), bold=True if style is None else False, fg=style)
  384. click.echo(res)
  385. @config.command("import", help="Import configuration parameters")
  386. @click.option("--format", "-f", help="The format to parse the imported params", default="python", type=click.Choice(["python"]))
  387. @click.pass_context
  388. @display_error
  389. def import_config(ctx, format):
  390. data = editor("# Paste python comments and variable definitions above")
  391. desc = None
  392. config = Config()
  393. imported = []
  394. if data:
  395. for line in data.split("\n"):
  396. if line.strip().startswith("#"):
  397. desc = line.strip(" #")
  398. elif "=" in line:
  399. try:
  400. key, value = [str(part.strip()) for part in line.split("=")]
  401. if len(value) == 0:
  402. continue
  403. config[key] = value
  404. imported.append(key)
  405. if desc:
  406. config[key+"_desc"] = desc
  407. desc = None
  408. except ValueError:
  409. logging.error("Invalid line: %s" % line)
  410. else:
  411. logging.warn("Skipping line %s", line)
  412. config.persist()
  413. ctx.invoke(show, changed=imported, diff=True)
  414. @config.command("set", help="Set config variables with key=value pairs")
  415. @click.argument("key_values", nargs=-1)
  416. @click.option("--description", "-d", help="A description for the config value if specifying one pair")
  417. @click.pass_context
  418. @display_error
  419. def config_set(ctx, key_values, description=None):
  420. config = Config()
  421. if len(key_values) == 0:
  422. raise ClickException("Must specify at least 1 key value pair i.e. `wandb config set epochs=11`")
  423. if len(key_values) > 1 and description:
  424. raise ClickException("Description can only be specified with 1 key value pair.")
  425. changed = []
  426. for pair in key_values:
  427. try:
  428. key, value = pair.split("=")
  429. except ValueError:
  430. key = pair
  431. value = None
  432. if value:
  433. changed.append(key)
  434. config[str(key)] = value
  435. if description:
  436. config[str(key)+"_desc"] = description
  437. config.persist()
  438. ctx.invoke(show, changed=changed, diff=True)
  439. @config.command("del", help="Delete config variables")
  440. @click.argument("keys", nargs=-1)
  441. @click.pass_context
  442. @display_error
  443. def delete(ctx, keys):
  444. config = Config()
  445. if len(keys) == 0:
  446. raise ClickException("Must specify at least 1 key i.e. `wandb config rm epochs`")
  447. changed = []
  448. for key in keys:
  449. del config[str(key)]
  450. changed.append(key)
  451. config.persist()
  452. ctx.invoke(show, changed=changed, diff=True)
  453. if __name__ == "__main__":
  454. cli()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...