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
  1. # -*- coding: utf-8 -*-
  2. import click, sys
  3. from wandb import Api, Error, Sync, Config, __version__
  4. import random, time, os, re, netrc, logging, json, glob, io, stat
  5. from functools import wraps
  6. from click.utils import LazyFile
  7. from click.exceptions import BadParameter, ClickException
  8. import inquirer
  9. logging.basicConfig(filename='/tmp/wandb.log', level=logging.INFO)
  10. def normalize(host):
  11. return host.split("/")[-1].split(":")[0]
  12. def logged_in(host, retry=True):
  13. """Check if our host is in .netrc"""
  14. try:
  15. conf = netrc.netrc()
  16. return conf.hosts[normalize(host)]
  17. except netrc.NetrcParseError as e:
  18. #chmod 0600 which is a common mistake, we could do this in `write_netrc`...
  19. os.chmod(os.path.expanduser('~/.netrc'), stat.S_IRUSR | stat.S_IWUSR)
  20. if retry:
  21. return logged_in(host, retry=False)
  22. else:
  23. click.secho("Unable to read ~/.netrc: "+e.message, fg="red")
  24. return None
  25. except IOError as e:
  26. click.secho("Unable to read ~/.netrc", fg="red")
  27. return None
  28. def write_netrc(host, entity, key):
  29. """Add our host and key to .netrc"""
  30. print("Appending to netrc %s" % os.path.expanduser('~/.netrc'))
  31. with open(os.path.expanduser('~/.netrc'), 'a') as f:
  32. f.write("""machine {host}
  33. login {entity}
  34. password {key}
  35. """.format(host=normalize(host), entity=entity, key=key))
  36. def display_error(func):
  37. """Function decorator for catching common errors and re-raising as wandb.Error"""
  38. @wraps(func)
  39. def wrapper(*args, **kwargs):
  40. try:
  41. return func(*args, **kwargs)
  42. except Error as e:
  43. raise ClickException(e)
  44. return wrapper
  45. def editor(marker='# Enter a description, markdown is allowed!\n'):
  46. message = click.edit('\n\n' + marker)
  47. if message is not None:
  48. return message.split(marker, 1)[0].rstrip('\n')
  49. api = Api()
  50. #TODO: Is this the best way to do this?
  51. CONTEXT=dict(default_map=api.config())
  52. class BucketGroup(click.Group):
  53. @display_error
  54. def get_command(self, ctx, cmd_name):
  55. rv = click.Group.get_command(self, ctx, cmd_name)
  56. if rv is not None:
  57. return rv
  58. try:
  59. project, bucket = api.parse_slug(cmd_name)
  60. except Error:
  61. return None
  62. sync = Sync(api, project=project, bucket=bucket)
  63. if sync.source_proc:
  64. files = sys.argv[2:]
  65. sync.watch(files)
  66. return click.Command("sync", context_settings={'allow_extra_args': True})
  67. else:
  68. return None
  69. @click.command(cls=BucketGroup)
  70. @click.version_option(version=__version__)
  71. @click.pass_context
  72. def cli(ctx):
  73. """Weights & Biases
  74. If no command is specified and input is piped, the source command and it's
  75. output will be saved to the bucket and the files uploaded when modified.
  76. ./train.sh arg1 arg2 | wandb imagenet/v2 model.json weights.h5
  77. """
  78. pass
  79. @cli.command(context_settings=CONTEXT, help="List projects")
  80. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  81. @display_error
  82. def projects(entity):
  83. projects = api.list_projects(entity=entity)
  84. if len(projects) == 0:
  85. message = "No projects found for %s" % entity
  86. else:
  87. message = 'Latest projects for "%s"' % entity
  88. click.echo(click.style(message, bold=True))
  89. for project in projects:
  90. click.echo("".join(
  91. (click.style(project['name'], fg="blue", bold=True),
  92. " - ",
  93. str(project['description']).split("\n")[0])
  94. ))
  95. return projects
  96. @cli.command(context_settings=CONTEXT, help="List buckets in a project")
  97. @click.argument("project", envvar='WANDB_PROJECT')
  98. @click.option("--project", "-p", prompt=True, envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  99. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  100. @display_error
  101. def buckets(project, entity):
  102. click.echo(click.style('Latest buckets for project "%s"' % project, bold=True))
  103. buckets = api.list_buckets(project, entity=entity)
  104. for bucket in buckets:
  105. click.echo("".join(
  106. (click.style(bucket['name'], fg="blue", bold=True),
  107. " - ",
  108. (bucket['description'] or "").split("\n")[0])
  109. ))
  110. @cli.command(context_settings=CONTEXT, help="List staged & remote files")
  111. @click.argument("bucket", envvar='WANDB_BUCKET')
  112. @click.option("--config/--no-config", help="Show the current configuration", default=False)
  113. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  114. @display_error
  115. def status(bucket, config, project):
  116. if config:
  117. click.echo(click.style("Current Configuration", bold=True) + " (%s)" % api.config_file)
  118. config = api.config()
  119. click.echo(json.dumps(
  120. config,
  121. sort_keys=True,
  122. indent=2,
  123. separators=(',', ': ')
  124. ))
  125. click.echo(click.style("Logged in?", bold=True) + " %s\n" % bool(logged_in(config['base_url'])))
  126. project, bucket = api.parse_slug(bucket, project=project)
  127. parser = api.config_parser
  128. parser.read(".wandb/config")
  129. if parser.has_option("default", "files"):
  130. existing = set(parser.get("default", "files").split(","))
  131. else:
  132. existing = set()
  133. remote = api.download_urls(project, bucket)
  134. not_synced = set()
  135. remote_names = set([name for name in remote])
  136. for file in existing:
  137. meta = remote.get(file)
  138. if meta and not api.file_current(file, meta['md5']):
  139. not_synced.add(file)
  140. elif not meta:
  141. not_synced.add(file)
  142. #TODO: remove items that exists and have the md5
  143. only_remote = remote_names.difference(existing)
  144. up_to_date = existing.difference(only_remote).difference(not_synced)
  145. click.echo('File status for '+ click.style('"%s/%s" ' % (project, bucket), bold=True))
  146. if len(not_synced) > 0:
  147. click.echo(click.style('Push needed: ', bold=True) + click.style(", ".join(not_synced), fg="red"))
  148. if len(only_remote) > 0:
  149. click.echo(click.style('Pull needed: ', bold=True) + click.style(", ".join(only_remote), fg="red"))
  150. if len(up_to_date) > 0:
  151. click.echo(click.style('Up to date: ', bold=True) + click.style(", ".join(up_to_date), fg="green"))
  152. if len(existing) == 0:
  153. click.echo(click.style("No files configured, add files with `wandb add filename`", fg="red"))
  154. @cli.command(context_settings=CONTEXT, help="Add staged files")
  155. @click.argument("files", type=click.File('rb'), nargs=-1)
  156. @click.option("--project", "-p", prompt=True, envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  157. @display_error
  158. def add(files, project):
  159. parser = api.config_parser
  160. parser.read(".wandb/config")
  161. if not parser.has_section("default"):
  162. raise ClickException("Directory not configured, run `wandb init` before adding files.")
  163. if parser.has_option("default", "files"):
  164. existing = parser.get("default", "files").split(",")
  165. else:
  166. existing = []
  167. stagedFiles = set(existing + [file.name for file in files])
  168. parser.set("default", "files", ",".join(stagedFiles))
  169. with open('.wandb/config', 'w') as configfile:
  170. parser.write(configfile)
  171. click.echo(click.style('Staged files for "%s": ' % project, bold=True) + ", ".join(stagedFiles))
  172. @cli.command(context_settings=CONTEXT, help="Remove staged files")
  173. @click.argument("files", nargs=-1)
  174. @click.option("--project", "-p", prompt=True, envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  175. @display_error
  176. def rm(files, project):
  177. parser = api.config_parser
  178. parser.read(".wandb/config")
  179. if parser.has_option("default", "files"):
  180. existing = parser.get("default", "files").split(",")
  181. else:
  182. existing = []
  183. for file in files:
  184. if file not in existing:
  185. raise ClickException("%s is not staged" % file)
  186. existing.remove(file)
  187. parser.set("default", "files", ",".join(existing))
  188. with open('.wandb/config', 'w') as configfile:
  189. parser.write(configfile)
  190. click.echo(click.style('Staged files for "%s": ' % project, bold=True) + ", ".join(existing))
  191. @cli.command(context_settings=CONTEXT, help="Push files to Weights & Biases")
  192. @click.argument("bucket", envvar='WANDB_BUCKET')
  193. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you wish to upload to.")
  194. @click.option("--description", "-m", help="A description to associate with this upload.")
  195. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  196. @click.option("--force/--no-force", "-f", default=False, help="Whether to force git tag creation.")
  197. @click.argument("files", type=click.File('rb'), nargs=-1)
  198. @click.pass_context
  199. @display_error
  200. def push(ctx, bucket, project, description, entity, force, files):
  201. #TODO: do we support the case of a bucket with the same name as a file?
  202. if os.path.exists(bucket):
  203. raise BadParameter("Bucket is required if files are specified.")
  204. project, bucket = api.parse_slug(bucket, project=project)
  205. click.echo("Uploading project: {project}/{bucket}".format(
  206. project=click.style(project, bold=True), bucket=bucket))
  207. if description is None:
  208. description = editor()
  209. candidates = []
  210. if len(files) == 0:
  211. if api.config().get("files"):
  212. fileNames = api.config()['files'].split(",")
  213. files = [LazyFile(fileName, 'rb') for fileName in fileNames]
  214. else:
  215. patterns = ("*.h5", "*.hdf5", "*.json", "*.meta", "*checkpoint*")
  216. for pattern in patterns:
  217. candidates.extend(glob.glob(pattern))
  218. if len(candidates) == 0:
  219. raise BadParameter("Couldn't auto-detect files, specify manually or use `wandb.add`", param_hint="FILES")
  220. choices = inquirer.prompt([inquirer.Checkbox('files', message="Which files do you want to push? (left and right arrows to select)",
  221. choices=[c for c in candidates])])
  222. files = [LazyFile(choice, 'rb') for choice in choices['files']]
  223. if len(files) > 5:
  224. raise BadParameter("A maximum of 5 files can be in a single bucket.", param_hint="FILES")
  225. #TODO: Deal with files in a sub directory
  226. urls = api.upload_urls(project, files=[f.name for f in files], bucket=bucket, description=description, entity=entity)
  227. api.tag_and_push(bucket, description, force)
  228. if api.latest_config:
  229. api.update_bucket(urls["bucket_id"], description=description, entity=entity, config=api.latest_config)
  230. for file in files:
  231. length = os.fstat(file.fileno()).st_size
  232. with click.progressbar(length=length, label='Uploading file: %s' % (file.name),
  233. fill_char=click.style('&', fg='green')) as bar:
  234. api.upload_file( urls[file.name]['url'], file, lambda bites: bar.update(bites) )
  235. @cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases")
  236. @click.argument("bucket", envvar='WANDB_BUCKET')
  237. @click.option("--project", "-p", envvar='WANDB_PROJECT', help="The project you want to download.")
  238. @click.option("--kind", "-k", default="all", type=click.Choice(['all', 'model', 'weights', 'other']))
  239. @click.option("--entity", "-e", default="models", envvar='WANDB_ENTITY', help="The entity to scope the listing to.")
  240. @display_error
  241. def pull(project, bucket, kind, entity):
  242. project, bucket = api.parse_slug(bucket, project=project)
  243. urls = api.download_urls(project, bucket=bucket, entity=entity)
  244. if len(urls) == 0:
  245. raise ClickException("Bucket is empty")
  246. click.echo("Downloading: {project}/{bucket}".format(
  247. project=click.style(project, bold=True), bucket=bucket
  248. ))
  249. for name in urls:
  250. if api.file_current(name, urls[name]['md5']):
  251. click.echo("File %s is up to date" % name)
  252. else:
  253. length, response = api.download_file(urls[name]['url'])
  254. with click.progressbar(length=length, label='File %s' % name,
  255. fill_char=click.style('&', fg='green')) as bar:
  256. with open(name, "wb") as f:
  257. for data in response.iter_content(chunk_size=4096):
  258. f.write(data)
  259. bar.update(len(data))
  260. @cli.command(context_settings=CONTEXT, help="Login to Weights & Biases")
  261. @display_error
  262. def login():
  263. #TODO: xdg-open dumps a bunch of output on Ubuntu if theirs no browser
  264. code = 1 #click.launch("https://app.wandb.ai/profile")
  265. if code != 0:
  266. click.echo("You can find your API keys here: https://app.wandb.ai/profile")
  267. key = click.prompt("{warning} Paste an API key from your profile".format(
  268. warning=click.style("Not authenticated!", fg="red")), default="")
  269. host = api.config()['base_url']
  270. if key:
  271. write_netrc(host, "user", key)
  272. @cli.command(context_settings=CONTEXT, help="Configure a directory with Weights & Biases")
  273. @click.pass_context
  274. @display_error
  275. def init(ctx):
  276. if(os.path.exists(".wandb")):
  277. click.confirm(click.style("This directory is already configured, should we overwrite it?", fg="red"), abort=True)
  278. click.echo(click.style("Let's setup this directory for W&B!", fg="green", bold=True))
  279. if logged_in(api.config('base_url')) is None:
  280. ctx.invoke(login)
  281. entity = click.prompt("What username or org should we use?", default=api.viewer().get('entity', 'models'))
  282. #TODO: handle the case of a missing entity
  283. result = ctx.invoke(projects, entity=entity)
  284. if len(result) == 0:
  285. project = click.prompt("Enter a name for your first project")
  286. description = editor()
  287. api.create_project(project, entity=entity, description=description)
  288. else:
  289. project_names = [project["name"] for project in result]
  290. question = inquirer.List('project', message="Which project should we use?", choices=project_names + ["Create New"])
  291. project = inquirer.prompt([question])['project']
  292. #TODO: check with the server if the project exists
  293. if project == "Create New":
  294. project = click.prompt("Enter a name for your new project")
  295. description = editor()
  296. api.create_project(project, entity=entity, description=description)
  297. ctx.invoke(config_init, False)
  298. with open(".wandb/config", "w") as file:
  299. file.write("[default]\nentity: {entity}\nproject: {project}".format(entity=entity, project=project))
  300. click.echo(click.style("This directory is configured! Try these next:\n", fg="green")+
  301. """
  302. * Run `{push}` to add your first file.
  303. * Pipe your training script output to push changed files and your logs: `{sync}`.
  304. * `{config}` let's you import existing configuration and manage it with wandb.
  305. * Pull popular models into your project with: `{pull}`.
  306. """.format(
  307. push=click.style("wandb push weights.h5", bold=True),
  308. sync=click.style("my_training.py | wandb", bold=True),
  309. config=click.style("wandb config import", bold=True),
  310. pull=click.style("wandb pull zoo/inception_v4", bold=True)
  311. ))
  312. @cli.group()
  313. @click.pass_context
  314. @display_error
  315. def config(ctx):
  316. """Manage this projects configuration.
  317. Examples:
  318. wandb config set param=2 --description="Some tunning parameter"
  319. wandb config del param
  320. wandb config show
  321. """
  322. pass
  323. @config.command("init", help="Initialize a directory with wandb configuration")
  324. @display_error
  325. def config_init(prompt=True):
  326. config_path = os.getcwd()+"/.wandb"
  327. config = Config()
  328. if os.path.isdir(config_path):
  329. if prompt:
  330. click.confirm(click.style("This directory is already initialized, should we overwrite it?", fg="red"), abort=True)
  331. else:
  332. #TODO: Temp to deal with migration
  333. tmp_path = config_path.replace(".wandb", ".wandb.tmp")
  334. if os.path.isfile(config_path):
  335. os.rename(config_path, tmp_path)
  336. os.mkdir(config_path)
  337. if os.path.isfile(tmp_path):
  338. os.rename(tmp_path, tmp_path.replace(".wandb.tmp", ".wandb/config"))
  339. config.batch_size_desc = "Number of training examples in a mini-batch"
  340. config.batch_size = 32
  341. config.persist()
  342. if prompt:
  343. click.echo("""Configuration initialized, use `wandb config set` to set parameters. Then in your training script:
  344. import wandb
  345. conf = wandb.Config()
  346. conf.batch_size
  347. """)
  348. @config.command(help="Show the current config")
  349. @click.option("--format", help="The format to dump the config as", default="python", type=click.Choice(['python', 'yaml', 'json']))
  350. @display_error
  351. def show(format, changed=[], diff=False):
  352. if len(changed) == 0 and diff:
  353. click.secho("No parameters were changed", fg="red")
  354. elif diff:
  355. click.echo("%i parameters changed: " % len(changed))
  356. config = Config()
  357. if len(vars(config)) == 0:
  358. click.secho("No configuration found in this directory, run `wandb config init`", fg="red")
  359. if format == "yaml":
  360. click.echo("%s" % config)
  361. elif format == "json":
  362. click.echo(json.dumps(vars(config)))
  363. elif format == "python":
  364. res = ""
  365. for key in set(config.keys + changed):
  366. if config.desc(key):
  367. res += "# %s\n" % config.desc(key)
  368. style = None
  369. if key in changed:
  370. style = "green" if config.get(key) else "red"
  371. res += click.style("%s=%r\n" % (key, config.get(key)), bold=True if style is None else False, fg=style)
  372. click.echo(res)
  373. @config.command("import", help="Import configuration parameters")
  374. @click.option("--format", "-f", help="The format to parse the imported params", default="python", type=click.Choice(["python"]))
  375. @click.pass_context
  376. @display_error
  377. def import_config(ctx, format):
  378. data = editor("# Paste python comments and variable definitions above")
  379. desc = None
  380. config = Config()
  381. imported = []
  382. if data:
  383. for line in data.split("\n"):
  384. if line.strip().startswith("#"):
  385. desc = line.strip(" #")
  386. elif "=" in line:
  387. try:
  388. key, value = [str(part.strip()) for part in line.split("=")]
  389. if len(value) == 0:
  390. continue
  391. config[key] = value
  392. imported.append(key)
  393. if desc:
  394. config[key+"_desc"] = desc
  395. desc = None
  396. except ValueError:
  397. logging.error("Invalid line: %s" % line)
  398. else:
  399. logging.warn("Skipping line %s", line)
  400. config.persist()
  401. ctx.invoke(show, changed=imported, diff=True)
  402. @config.command("set", help="Set config variables with key=value pairs")
  403. @click.argument("key_values", nargs=-1)
  404. @click.option("--description", "-d", help="A description for the config value if specifying one pair")
  405. @click.pass_context
  406. @display_error
  407. def config_set(ctx, key_values, description=None):
  408. config = Config()
  409. if len(key_values) == 0:
  410. raise ClickException("Must specify at least 1 key value pair i.e. `wandb config set epochs=11`")
  411. if len(key_values) > 1 and description:
  412. raise ClickException("Description can only be specified with 1 key value pair.")
  413. changed = []
  414. for pair in key_values:
  415. try:
  416. key, value = pair.split("=")
  417. except ValueError:
  418. key = pair
  419. value = None
  420. if value:
  421. changed.append(key)
  422. config[str(key)] = value
  423. if description:
  424. config[str(key)+"_desc"] = description
  425. config.persist()
  426. ctx.invoke(show, changed=changed, diff=True)
  427. @config.command("del", help="Delete config variables")
  428. @click.argument("keys", nargs=-1)
  429. @click.pass_context
  430. @display_error
  431. def delete(ctx, keys):
  432. config = Config()
  433. if len(keys) == 0:
  434. raise ClickException("Must specify at least 1 key i.e. `wandb config rm epochs`")
  435. changed = []
  436. for key in keys:
  437. del config[str(key)]
  438. changed.append(key)
  439. config.persist()
  440. ctx.invoke(show, changed=changed, diff=True)
  441. if __name__ == "__main__":
  442. cli()
Tip!

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

Comments

Loading...