wandb 0.18.1__py3-none-macosx_11_0_x86_64.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (826) hide show
  1. package_readme.md +89 -0
  2. wandb/__init__.py +245 -0
  3. wandb/__init__.pyi +1084 -0
  4. wandb/__main__.py +3 -0
  5. wandb/_globals.py +19 -0
  6. wandb/agents/__init__.py +0 -0
  7. wandb/agents/pyagent.py +363 -0
  8. wandb/analytics/__init__.py +3 -0
  9. wandb/analytics/sentry.py +266 -0
  10. wandb/apis/__init__.py +48 -0
  11. wandb/apis/attrs.py +40 -0
  12. wandb/apis/importers/__init__.py +1 -0
  13. wandb/apis/importers/internals/internal.py +385 -0
  14. wandb/apis/importers/internals/protocols.py +99 -0
  15. wandb/apis/importers/internals/util.py +78 -0
  16. wandb/apis/importers/mlflow.py +254 -0
  17. wandb/apis/importers/validation.py +108 -0
  18. wandb/apis/importers/wandb.py +1603 -0
  19. wandb/apis/internal.py +229 -0
  20. wandb/apis/normalize.py +89 -0
  21. wandb/apis/paginator.py +81 -0
  22. wandb/apis/public/__init__.py +34 -0
  23. wandb/apis/public/api.py +1179 -0
  24. wandb/apis/public/artifacts.py +1086 -0
  25. wandb/apis/public/const.py +4 -0
  26. wandb/apis/public/files.py +195 -0
  27. wandb/apis/public/history.py +149 -0
  28. wandb/apis/public/jobs.py +651 -0
  29. wandb/apis/public/projects.py +154 -0
  30. wandb/apis/public/query_generator.py +166 -0
  31. wandb/apis/public/reports.py +469 -0
  32. wandb/apis/public/runs.py +903 -0
  33. wandb/apis/public/sweeps.py +240 -0
  34. wandb/apis/public/teams.py +198 -0
  35. wandb/apis/public/users.py +136 -0
  36. wandb/apis/reports/__init__.py +1 -0
  37. wandb/apis/reports/v1/__init__.py +8 -0
  38. wandb/apis/reports/v2/__init__.py +8 -0
  39. wandb/apis/workspaces/__init__.py +8 -0
  40. wandb/beta/workflows.py +288 -0
  41. wandb/bin/wandb-core +0 -0
  42. wandb/cli/__init__.py +0 -0
  43. wandb/cli/cli.py +3007 -0
  44. wandb/data_types.py +63 -0
  45. wandb/docker/__init__.py +342 -0
  46. wandb/docker/auth.py +436 -0
  47. wandb/docker/wandb-entrypoint.sh +33 -0
  48. wandb/docker/www_authenticate.py +94 -0
  49. wandb/env.py +514 -0
  50. wandb/errors/__init__.py +46 -0
  51. wandb/errors/term.py +103 -0
  52. wandb/errors/util.py +57 -0
  53. wandb/filesync/__init__.py +0 -0
  54. wandb/filesync/dir_watcher.py +403 -0
  55. wandb/filesync/stats.py +100 -0
  56. wandb/filesync/step_checksum.py +142 -0
  57. wandb/filesync/step_prepare.py +179 -0
  58. wandb/filesync/step_upload.py +290 -0
  59. wandb/filesync/upload_job.py +142 -0
  60. wandb/integration/__init__.py +0 -0
  61. wandb/integration/catboost/__init__.py +5 -0
  62. wandb/integration/catboost/catboost.py +178 -0
  63. wandb/integration/cohere/__init__.py +3 -0
  64. wandb/integration/cohere/cohere.py +21 -0
  65. wandb/integration/cohere/resolver.py +347 -0
  66. wandb/integration/diffusers/__init__.py +3 -0
  67. wandb/integration/diffusers/autologger.py +76 -0
  68. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  69. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  70. wandb/integration/diffusers/resolvers/multimodal.py +882 -0
  71. wandb/integration/diffusers/resolvers/utils.py +102 -0
  72. wandb/integration/fastai/__init__.py +249 -0
  73. wandb/integration/gym/__init__.py +105 -0
  74. wandb/integration/huggingface/__init__.py +3 -0
  75. wandb/integration/huggingface/huggingface.py +18 -0
  76. wandb/integration/huggingface/resolver.py +213 -0
  77. wandb/integration/keras/__init__.py +11 -0
  78. wandb/integration/keras/callbacks/__init__.py +5 -0
  79. wandb/integration/keras/callbacks/metrics_logger.py +136 -0
  80. wandb/integration/keras/callbacks/model_checkpoint.py +195 -0
  81. wandb/integration/keras/callbacks/tables_builder.py +226 -0
  82. wandb/integration/keras/keras.py +1091 -0
  83. wandb/integration/kfp/__init__.py +6 -0
  84. wandb/integration/kfp/helpers.py +28 -0
  85. wandb/integration/kfp/kfp_patch.py +324 -0
  86. wandb/integration/kfp/wandb_logging.py +182 -0
  87. wandb/integration/langchain/__init__.py +3 -0
  88. wandb/integration/langchain/wandb_tracer.py +48 -0
  89. wandb/integration/lightgbm/__init__.py +239 -0
  90. wandb/integration/lightning/__init__.py +0 -0
  91. wandb/integration/lightning/fabric/__init__.py +3 -0
  92. wandb/integration/lightning/fabric/logger.py +762 -0
  93. wandb/integration/magic.py +556 -0
  94. wandb/integration/metaflow/__init__.py +3 -0
  95. wandb/integration/metaflow/metaflow.py +383 -0
  96. wandb/integration/openai/__init__.py +3 -0
  97. wandb/integration/openai/fine_tuning.py +480 -0
  98. wandb/integration/openai/openai.py +22 -0
  99. wandb/integration/openai/resolver.py +240 -0
  100. wandb/integration/prodigy/__init__.py +3 -0
  101. wandb/integration/prodigy/prodigy.py +299 -0
  102. wandb/integration/sacred/__init__.py +117 -0
  103. wandb/integration/sagemaker/__init__.py +12 -0
  104. wandb/integration/sagemaker/auth.py +28 -0
  105. wandb/integration/sagemaker/config.py +49 -0
  106. wandb/integration/sagemaker/files.py +3 -0
  107. wandb/integration/sagemaker/resources.py +34 -0
  108. wandb/integration/sb3/__init__.py +3 -0
  109. wandb/integration/sb3/sb3.py +153 -0
  110. wandb/integration/sklearn/__init__.py +37 -0
  111. wandb/integration/sklearn/calculate/__init__.py +32 -0
  112. wandb/integration/sklearn/calculate/calibration_curves.py +125 -0
  113. wandb/integration/sklearn/calculate/class_proportions.py +68 -0
  114. wandb/integration/sklearn/calculate/confusion_matrix.py +93 -0
  115. wandb/integration/sklearn/calculate/decision_boundaries.py +40 -0
  116. wandb/integration/sklearn/calculate/elbow_curve.py +55 -0
  117. wandb/integration/sklearn/calculate/feature_importances.py +67 -0
  118. wandb/integration/sklearn/calculate/learning_curve.py +64 -0
  119. wandb/integration/sklearn/calculate/outlier_candidates.py +69 -0
  120. wandb/integration/sklearn/calculate/residuals.py +86 -0
  121. wandb/integration/sklearn/calculate/silhouette.py +118 -0
  122. wandb/integration/sklearn/calculate/summary_metrics.py +62 -0
  123. wandb/integration/sklearn/plot/__init__.py +35 -0
  124. wandb/integration/sklearn/plot/classifier.py +329 -0
  125. wandb/integration/sklearn/plot/clusterer.py +146 -0
  126. wandb/integration/sklearn/plot/regressor.py +121 -0
  127. wandb/integration/sklearn/plot/shared.py +91 -0
  128. wandb/integration/sklearn/utils.py +183 -0
  129. wandb/integration/tensorboard/__init__.py +10 -0
  130. wandb/integration/tensorboard/log.py +355 -0
  131. wandb/integration/tensorboard/monkeypatch.py +185 -0
  132. wandb/integration/tensorflow/__init__.py +5 -0
  133. wandb/integration/tensorflow/estimator_hook.py +54 -0
  134. wandb/integration/torch/__init__.py +0 -0
  135. wandb/integration/torch/wandb_torch.py +554 -0
  136. wandb/integration/ultralytics/__init__.py +11 -0
  137. wandb/integration/ultralytics/bbox_utils.py +208 -0
  138. wandb/integration/ultralytics/callback.py +524 -0
  139. wandb/integration/ultralytics/classification_utils.py +83 -0
  140. wandb/integration/ultralytics/mask_utils.py +202 -0
  141. wandb/integration/ultralytics/pose_utils.py +103 -0
  142. wandb/integration/xgboost/__init__.py +11 -0
  143. wandb/integration/xgboost/xgboost.py +189 -0
  144. wandb/integration/yolov8/__init__.py +0 -0
  145. wandb/integration/yolov8/yolov8.py +284 -0
  146. wandb/jupyter.py +515 -0
  147. wandb/magic.py +3 -0
  148. wandb/mpmain/__init__.py +0 -0
  149. wandb/mpmain/__main__.py +1 -0
  150. wandb/old/__init__.py +0 -0
  151. wandb/old/core.py +131 -0
  152. wandb/old/settings.py +173 -0
  153. wandb/old/summary.py +440 -0
  154. wandb/plot/__init__.py +19 -0
  155. wandb/plot/bar.py +42 -0
  156. wandb/plot/confusion_matrix.py +99 -0
  157. wandb/plot/histogram.py +36 -0
  158. wandb/plot/line.py +40 -0
  159. wandb/plot/line_series.py +88 -0
  160. wandb/plot/pr_curve.py +136 -0
  161. wandb/plot/roc_curve.py +118 -0
  162. wandb/plot/scatter.py +32 -0
  163. wandb/plot/utils.py +183 -0
  164. wandb/proto/__init__.py +0 -0
  165. wandb/proto/v3/__init__.py +0 -0
  166. wandb/proto/v3/wandb_base_pb2.py +55 -0
  167. wandb/proto/v3/wandb_internal_pb2.py +1608 -0
  168. wandb/proto/v3/wandb_server_pb2.py +208 -0
  169. wandb/proto/v3/wandb_settings_pb2.py +112 -0
  170. wandb/proto/v3/wandb_telemetry_pb2.py +106 -0
  171. wandb/proto/v4/__init__.py +0 -0
  172. wandb/proto/v4/wandb_base_pb2.py +30 -0
  173. wandb/proto/v4/wandb_internal_pb2.py +360 -0
  174. wandb/proto/v4/wandb_server_pb2.py +63 -0
  175. wandb/proto/v4/wandb_settings_pb2.py +45 -0
  176. wandb/proto/v4/wandb_telemetry_pb2.py +41 -0
  177. wandb/proto/v5/wandb_base_pb2.py +31 -0
  178. wandb/proto/v5/wandb_internal_pb2.py +361 -0
  179. wandb/proto/v5/wandb_server_pb2.py +64 -0
  180. wandb/proto/v5/wandb_settings_pb2.py +46 -0
  181. wandb/proto/v5/wandb_telemetry_pb2.py +42 -0
  182. wandb/proto/wandb_base_pb2.py +10 -0
  183. wandb/proto/wandb_deprecated.py +53 -0
  184. wandb/proto/wandb_generate_deprecated.py +34 -0
  185. wandb/proto/wandb_generate_proto.py +49 -0
  186. wandb/proto/wandb_internal_pb2.py +16 -0
  187. wandb/proto/wandb_server_pb2.py +10 -0
  188. wandb/proto/wandb_settings_pb2.py +10 -0
  189. wandb/proto/wandb_telemetry_pb2.py +10 -0
  190. wandb/py.typed +0 -0
  191. wandb/sdk/__init__.py +37 -0
  192. wandb/sdk/artifacts/__init__.py +0 -0
  193. wandb/sdk/artifacts/_validators.py +45 -0
  194. wandb/sdk/artifacts/artifact.py +2415 -0
  195. wandb/sdk/artifacts/artifact_download_logger.py +43 -0
  196. wandb/sdk/artifacts/artifact_file_cache.py +251 -0
  197. wandb/sdk/artifacts/artifact_instance_cache.py +15 -0
  198. wandb/sdk/artifacts/artifact_manifest.py +72 -0
  199. wandb/sdk/artifacts/artifact_manifest_entry.py +247 -0
  200. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  201. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +90 -0
  202. wandb/sdk/artifacts/artifact_saver.py +267 -0
  203. wandb/sdk/artifacts/artifact_state.py +11 -0
  204. wandb/sdk/artifacts/artifact_ttl.py +7 -0
  205. wandb/sdk/artifacts/exceptions.py +56 -0
  206. wandb/sdk/artifacts/staging.py +25 -0
  207. wandb/sdk/artifacts/storage_handler.py +60 -0
  208. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  209. wandb/sdk/artifacts/storage_handlers/azure_handler.py +206 -0
  210. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +226 -0
  211. wandb/sdk/artifacts/storage_handlers/http_handler.py +113 -0
  212. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +139 -0
  213. wandb/sdk/artifacts/storage_handlers/multi_handler.py +54 -0
  214. wandb/sdk/artifacts/storage_handlers/s3_handler.py +300 -0
  215. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +70 -0
  216. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +133 -0
  217. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +72 -0
  218. wandb/sdk/artifacts/storage_layout.py +6 -0
  219. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  220. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  221. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +376 -0
  222. wandb/sdk/artifacts/storage_policy.py +72 -0
  223. wandb/sdk/backend/__init__.py +0 -0
  224. wandb/sdk/backend/backend.py +240 -0
  225. wandb/sdk/data_types/__init__.py +0 -0
  226. wandb/sdk/data_types/_dtypes.py +914 -0
  227. wandb/sdk/data_types/_private.py +10 -0
  228. wandb/sdk/data_types/audio.py +165 -0
  229. wandb/sdk/data_types/base_types/__init__.py +0 -0
  230. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  231. wandb/sdk/data_types/base_types/media.py +315 -0
  232. wandb/sdk/data_types/base_types/wb_value.py +274 -0
  233. wandb/sdk/data_types/bokeh.py +70 -0
  234. wandb/sdk/data_types/graph.py +405 -0
  235. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  236. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +295 -0
  237. wandb/sdk/data_types/helper_types/classes.py +159 -0
  238. wandb/sdk/data_types/helper_types/image_mask.py +235 -0
  239. wandb/sdk/data_types/histogram.py +96 -0
  240. wandb/sdk/data_types/html.py +115 -0
  241. wandb/sdk/data_types/image.py +845 -0
  242. wandb/sdk/data_types/molecule.py +241 -0
  243. wandb/sdk/data_types/object_3d.py +474 -0
  244. wandb/sdk/data_types/plotly.py +82 -0
  245. wandb/sdk/data_types/saved_model.py +446 -0
  246. wandb/sdk/data_types/table.py +1204 -0
  247. wandb/sdk/data_types/trace_tree.py +438 -0
  248. wandb/sdk/data_types/utils.py +229 -0
  249. wandb/sdk/data_types/video.py +247 -0
  250. wandb/sdk/integration_utils/__init__.py +0 -0
  251. wandb/sdk/integration_utils/auto_logging.py +239 -0
  252. wandb/sdk/integration_utils/data_logging.py +475 -0
  253. wandb/sdk/interface/__init__.py +0 -0
  254. wandb/sdk/interface/constants.py +4 -0
  255. wandb/sdk/interface/interface.py +996 -0
  256. wandb/sdk/interface/interface_queue.py +59 -0
  257. wandb/sdk/interface/interface_relay.py +53 -0
  258. wandb/sdk/interface/interface_shared.py +549 -0
  259. wandb/sdk/interface/interface_sock.py +61 -0
  260. wandb/sdk/interface/message_future.py +27 -0
  261. wandb/sdk/interface/message_future_poll.py +50 -0
  262. wandb/sdk/interface/router.py +118 -0
  263. wandb/sdk/interface/router_queue.py +44 -0
  264. wandb/sdk/interface/router_relay.py +39 -0
  265. wandb/sdk/interface/router_sock.py +36 -0
  266. wandb/sdk/interface/summary_record.py +67 -0
  267. wandb/sdk/internal/__init__.py +0 -0
  268. wandb/sdk/internal/context.py +89 -0
  269. wandb/sdk/internal/datastore.py +297 -0
  270. wandb/sdk/internal/file_pusher.py +181 -0
  271. wandb/sdk/internal/file_stream.py +695 -0
  272. wandb/sdk/internal/flow_control.py +263 -0
  273. wandb/sdk/internal/handler.py +911 -0
  274. wandb/sdk/internal/internal.py +417 -0
  275. wandb/sdk/internal/internal_api.py +4287 -0
  276. wandb/sdk/internal/internal_util.py +100 -0
  277. wandb/sdk/internal/job_builder.py +629 -0
  278. wandb/sdk/internal/profiler.py +78 -0
  279. wandb/sdk/internal/progress.py +83 -0
  280. wandb/sdk/internal/run.py +25 -0
  281. wandb/sdk/internal/sample.py +70 -0
  282. wandb/sdk/internal/sender.py +1729 -0
  283. wandb/sdk/internal/sender_config.py +197 -0
  284. wandb/sdk/internal/settings_static.py +90 -0
  285. wandb/sdk/internal/system/__init__.py +0 -0
  286. wandb/sdk/internal/system/assets/__init__.py +27 -0
  287. wandb/sdk/internal/system/assets/aggregators.py +37 -0
  288. wandb/sdk/internal/system/assets/asset_registry.py +20 -0
  289. wandb/sdk/internal/system/assets/cpu.py +163 -0
  290. wandb/sdk/internal/system/assets/disk.py +210 -0
  291. wandb/sdk/internal/system/assets/gpu.py +416 -0
  292. wandb/sdk/internal/system/assets/gpu_amd.py +239 -0
  293. wandb/sdk/internal/system/assets/gpu_apple.py +177 -0
  294. wandb/sdk/internal/system/assets/interfaces.py +207 -0
  295. wandb/sdk/internal/system/assets/ipu.py +177 -0
  296. wandb/sdk/internal/system/assets/memory.py +166 -0
  297. wandb/sdk/internal/system/assets/network.py +125 -0
  298. wandb/sdk/internal/system/assets/open_metrics.py +299 -0
  299. wandb/sdk/internal/system/assets/tpu.py +154 -0
  300. wandb/sdk/internal/system/assets/trainium.py +399 -0
  301. wandb/sdk/internal/system/env_probe_helpers.py +13 -0
  302. wandb/sdk/internal/system/system_info.py +249 -0
  303. wandb/sdk/internal/system/system_monitor.py +229 -0
  304. wandb/sdk/internal/tb_watcher.py +518 -0
  305. wandb/sdk/internal/thread_local_settings.py +18 -0
  306. wandb/sdk/internal/update.py +113 -0
  307. wandb/sdk/internal/writer.py +206 -0
  308. wandb/sdk/launch/__init__.py +14 -0
  309. wandb/sdk/launch/_launch.py +330 -0
  310. wandb/sdk/launch/_launch_add.py +255 -0
  311. wandb/sdk/launch/_project_spec.py +566 -0
  312. wandb/sdk/launch/agent/__init__.py +5 -0
  313. wandb/sdk/launch/agent/agent.py +924 -0
  314. wandb/sdk/launch/agent/config.py +296 -0
  315. wandb/sdk/launch/agent/job_status_tracker.py +53 -0
  316. wandb/sdk/launch/agent/run_queue_item_file_saver.py +45 -0
  317. wandb/sdk/launch/builder/__init__.py +0 -0
  318. wandb/sdk/launch/builder/abstract.py +156 -0
  319. wandb/sdk/launch/builder/build.py +297 -0
  320. wandb/sdk/launch/builder/context_manager.py +235 -0
  321. wandb/sdk/launch/builder/docker_builder.py +177 -0
  322. wandb/sdk/launch/builder/kaniko_builder.py +595 -0
  323. wandb/sdk/launch/builder/noop.py +58 -0
  324. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +188 -0
  325. wandb/sdk/launch/builder/templates/dockerfile.py +92 -0
  326. wandb/sdk/launch/create_job.py +528 -0
  327. wandb/sdk/launch/environment/abstract.py +29 -0
  328. wandb/sdk/launch/environment/aws_environment.py +322 -0
  329. wandb/sdk/launch/environment/azure_environment.py +105 -0
  330. wandb/sdk/launch/environment/gcp_environment.py +335 -0
  331. wandb/sdk/launch/environment/local_environment.py +66 -0
  332. wandb/sdk/launch/errors.py +19 -0
  333. wandb/sdk/launch/git_reference.py +109 -0
  334. wandb/sdk/launch/inputs/files.py +148 -0
  335. wandb/sdk/launch/inputs/internal.py +315 -0
  336. wandb/sdk/launch/inputs/manage.py +113 -0
  337. wandb/sdk/launch/inputs/schema.py +39 -0
  338. wandb/sdk/launch/loader.py +249 -0
  339. wandb/sdk/launch/registry/abstract.py +48 -0
  340. wandb/sdk/launch/registry/anon.py +29 -0
  341. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  342. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  343. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  344. wandb/sdk/launch/registry/local_registry.py +67 -0
  345. wandb/sdk/launch/runner/__init__.py +0 -0
  346. wandb/sdk/launch/runner/abstract.py +195 -0
  347. wandb/sdk/launch/runner/kubernetes_monitor.py +474 -0
  348. wandb/sdk/launch/runner/kubernetes_runner.py +963 -0
  349. wandb/sdk/launch/runner/local_container.py +301 -0
  350. wandb/sdk/launch/runner/local_process.py +78 -0
  351. wandb/sdk/launch/runner/sagemaker_runner.py +426 -0
  352. wandb/sdk/launch/runner/vertex_runner.py +230 -0
  353. wandb/sdk/launch/sweeps/__init__.py +39 -0
  354. wandb/sdk/launch/sweeps/scheduler.py +742 -0
  355. wandb/sdk/launch/sweeps/scheduler_sweep.py +91 -0
  356. wandb/sdk/launch/sweeps/utils.py +316 -0
  357. wandb/sdk/launch/utils.py +746 -0
  358. wandb/sdk/launch/wandb_reference.py +138 -0
  359. wandb/sdk/lib/__init__.py +5 -0
  360. wandb/sdk/lib/_settings_toposort_generate.py +159 -0
  361. wandb/sdk/lib/_settings_toposort_generated.py +249 -0
  362. wandb/sdk/lib/_wburls_generate.py +25 -0
  363. wandb/sdk/lib/_wburls_generated.py +22 -0
  364. wandb/sdk/lib/apikey.py +273 -0
  365. wandb/sdk/lib/capped_dict.py +26 -0
  366. wandb/sdk/lib/config_util.py +101 -0
  367. wandb/sdk/lib/credentials.py +141 -0
  368. wandb/sdk/lib/deprecate.py +42 -0
  369. wandb/sdk/lib/disabled.py +29 -0
  370. wandb/sdk/lib/exit_hooks.py +54 -0
  371. wandb/sdk/lib/file_stream_utils.py +118 -0
  372. wandb/sdk/lib/filenames.py +64 -0
  373. wandb/sdk/lib/filesystem.py +372 -0
  374. wandb/sdk/lib/fsm.py +174 -0
  375. wandb/sdk/lib/gitlib.py +239 -0
  376. wandb/sdk/lib/gql_request.py +65 -0
  377. wandb/sdk/lib/handler_util.py +21 -0
  378. wandb/sdk/lib/hashutil.py +62 -0
  379. wandb/sdk/lib/import_hooks.py +275 -0
  380. wandb/sdk/lib/ipython.py +146 -0
  381. wandb/sdk/lib/json_util.py +80 -0
  382. wandb/sdk/lib/lazyloader.py +63 -0
  383. wandb/sdk/lib/mailbox.py +460 -0
  384. wandb/sdk/lib/module.py +69 -0
  385. wandb/sdk/lib/paths.py +106 -0
  386. wandb/sdk/lib/preinit.py +42 -0
  387. wandb/sdk/lib/printer.py +313 -0
  388. wandb/sdk/lib/proto_util.py +90 -0
  389. wandb/sdk/lib/redirect.py +845 -0
  390. wandb/sdk/lib/reporting.py +99 -0
  391. wandb/sdk/lib/retry.py +289 -0
  392. wandb/sdk/lib/run_moment.py +78 -0
  393. wandb/sdk/lib/runid.py +12 -0
  394. wandb/sdk/lib/server.py +52 -0
  395. wandb/sdk/lib/sock_client.py +291 -0
  396. wandb/sdk/lib/sparkline.py +45 -0
  397. wandb/sdk/lib/telemetry.py +100 -0
  398. wandb/sdk/lib/timed_input.py +133 -0
  399. wandb/sdk/lib/timer.py +19 -0
  400. wandb/sdk/lib/tracelog.py +255 -0
  401. wandb/sdk/lib/viz.py +123 -0
  402. wandb/sdk/lib/wburls.py +46 -0
  403. wandb/sdk/service/__init__.py +0 -0
  404. wandb/sdk/service/_startup_debug.py +22 -0
  405. wandb/sdk/service/port_file.py +53 -0
  406. wandb/sdk/service/server.py +119 -0
  407. wandb/sdk/service/server_sock.py +276 -0
  408. wandb/sdk/service/service.py +264 -0
  409. wandb/sdk/service/service_base.py +50 -0
  410. wandb/sdk/service/service_sock.py +70 -0
  411. wandb/sdk/service/streams.py +417 -0
  412. wandb/sdk/verify/__init__.py +0 -0
  413. wandb/sdk/verify/verify.py +501 -0
  414. wandb/sdk/wandb_alerts.py +12 -0
  415. wandb/sdk/wandb_config.py +322 -0
  416. wandb/sdk/wandb_helper.py +54 -0
  417. wandb/sdk/wandb_init.py +1256 -0
  418. wandb/sdk/wandb_login.py +349 -0
  419. wandb/sdk/wandb_manager.py +232 -0
  420. wandb/sdk/wandb_metric.py +110 -0
  421. wandb/sdk/wandb_require.py +97 -0
  422. wandb/sdk/wandb_require_helpers.py +44 -0
  423. wandb/sdk/wandb_run.py +4231 -0
  424. wandb/sdk/wandb_settings.py +1999 -0
  425. wandb/sdk/wandb_setup.py +400 -0
  426. wandb/sdk/wandb_summary.py +150 -0
  427. wandb/sdk/wandb_sweep.py +119 -0
  428. wandb/sdk/wandb_sync.py +75 -0
  429. wandb/sdk/wandb_watch.py +128 -0
  430. wandb/sklearn.py +35 -0
  431. wandb/sync/__init__.py +3 -0
  432. wandb/sync/sync.py +443 -0
  433. wandb/trigger.py +29 -0
  434. wandb/util.py +1949 -0
  435. wandb/vendor/__init__.py +0 -0
  436. wandb/vendor/gql-0.2.0/setup.py +40 -0
  437. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  438. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  439. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  440. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  441. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  442. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  443. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  444. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  445. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  446. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  447. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  448. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  449. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  450. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  451. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  452. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  453. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  454. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  455. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  456. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  457. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  458. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  459. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  460. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  461. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  462. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  463. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  464. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  465. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  466. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  467. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  468. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  469. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  470. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  471. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  472. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  473. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  474. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  475. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  476. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  477. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  478. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  479. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  480. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  481. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  482. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  483. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  484. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  485. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  486. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  487. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  488. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  489. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  490. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  491. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  492. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  493. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  494. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  495. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  496. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  497. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  498. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  499. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  500. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  501. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  502. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  503. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  504. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  505. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  506. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  507. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  508. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  509. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  510. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  511. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  512. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  513. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  514. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  515. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  516. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  517. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  518. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  519. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  520. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  521. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  522. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  523. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  524. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  525. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  526. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  527. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  528. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  529. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  530. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  531. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  532. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  533. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  534. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  535. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  549. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  550. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  551. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  552. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  553. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  554. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  555. wandb/vendor/promise-2.3.0/setup.py +64 -0
  556. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  557. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  558. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  559. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  560. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  561. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  562. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  563. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  564. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  565. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  566. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  567. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  568. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  569. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  570. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  571. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  572. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  573. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  574. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  575. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  576. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  577. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  578. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  579. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  580. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  581. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  582. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  583. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  584. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  585. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  586. wandb/vendor/pygments/__init__.py +90 -0
  587. wandb/vendor/pygments/cmdline.py +568 -0
  588. wandb/vendor/pygments/console.py +74 -0
  589. wandb/vendor/pygments/filter.py +74 -0
  590. wandb/vendor/pygments/filters/__init__.py +350 -0
  591. wandb/vendor/pygments/formatter.py +95 -0
  592. wandb/vendor/pygments/formatters/__init__.py +153 -0
  593. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  594. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  595. wandb/vendor/pygments/formatters/html.py +851 -0
  596. wandb/vendor/pygments/formatters/img.py +600 -0
  597. wandb/vendor/pygments/formatters/irc.py +182 -0
  598. wandb/vendor/pygments/formatters/latex.py +482 -0
  599. wandb/vendor/pygments/formatters/other.py +160 -0
  600. wandb/vendor/pygments/formatters/rtf.py +147 -0
  601. wandb/vendor/pygments/formatters/svg.py +153 -0
  602. wandb/vendor/pygments/formatters/terminal.py +136 -0
  603. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  604. wandb/vendor/pygments/lexer.py +871 -0
  605. wandb/vendor/pygments/lexers/__init__.py +329 -0
  606. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  607. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  608. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  609. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  610. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  611. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  612. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  613. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  614. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  615. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  616. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  617. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  618. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  619. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  620. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  621. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  622. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  623. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  624. wandb/vendor/pygments/lexers/agile.py +24 -0
  625. wandb/vendor/pygments/lexers/algebra.py +221 -0
  626. wandb/vendor/pygments/lexers/ambient.py +76 -0
  627. wandb/vendor/pygments/lexers/ampl.py +87 -0
  628. wandb/vendor/pygments/lexers/apl.py +101 -0
  629. wandb/vendor/pygments/lexers/archetype.py +318 -0
  630. wandb/vendor/pygments/lexers/asm.py +641 -0
  631. wandb/vendor/pygments/lexers/automation.py +374 -0
  632. wandb/vendor/pygments/lexers/basic.py +500 -0
  633. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  634. wandb/vendor/pygments/lexers/business.py +612 -0
  635. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  636. wandb/vendor/pygments/lexers/c_like.py +541 -0
  637. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  638. wandb/vendor/pygments/lexers/chapel.py +102 -0
  639. wandb/vendor/pygments/lexers/clean.py +288 -0
  640. wandb/vendor/pygments/lexers/compiled.py +34 -0
  641. wandb/vendor/pygments/lexers/configs.py +833 -0
  642. wandb/vendor/pygments/lexers/console.py +114 -0
  643. wandb/vendor/pygments/lexers/crystal.py +393 -0
  644. wandb/vendor/pygments/lexers/csound.py +366 -0
  645. wandb/vendor/pygments/lexers/css.py +689 -0
  646. wandb/vendor/pygments/lexers/d.py +251 -0
  647. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  648. wandb/vendor/pygments/lexers/data.py +555 -0
  649. wandb/vendor/pygments/lexers/diff.py +165 -0
  650. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  651. wandb/vendor/pygments/lexers/dsls.py +878 -0
  652. wandb/vendor/pygments/lexers/dylan.py +289 -0
  653. wandb/vendor/pygments/lexers/ecl.py +125 -0
  654. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  655. wandb/vendor/pygments/lexers/elm.py +121 -0
  656. wandb/vendor/pygments/lexers/erlang.py +533 -0
  657. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  658. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  659. wandb/vendor/pygments/lexers/factor.py +344 -0
  660. wandb/vendor/pygments/lexers/fantom.py +250 -0
  661. wandb/vendor/pygments/lexers/felix.py +273 -0
  662. wandb/vendor/pygments/lexers/forth.py +177 -0
  663. wandb/vendor/pygments/lexers/fortran.py +205 -0
  664. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  665. wandb/vendor/pygments/lexers/functional.py +21 -0
  666. wandb/vendor/pygments/lexers/go.py +101 -0
  667. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  668. wandb/vendor/pygments/lexers/graph.py +80 -0
  669. wandb/vendor/pygments/lexers/graphics.py +553 -0
  670. wandb/vendor/pygments/lexers/haskell.py +843 -0
  671. wandb/vendor/pygments/lexers/haxe.py +936 -0
  672. wandb/vendor/pygments/lexers/hdl.py +382 -0
  673. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  674. wandb/vendor/pygments/lexers/html.py +602 -0
  675. wandb/vendor/pygments/lexers/idl.py +270 -0
  676. wandb/vendor/pygments/lexers/igor.py +288 -0
  677. wandb/vendor/pygments/lexers/inferno.py +96 -0
  678. wandb/vendor/pygments/lexers/installers.py +322 -0
  679. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  680. wandb/vendor/pygments/lexers/iolang.py +63 -0
  681. wandb/vendor/pygments/lexers/j.py +146 -0
  682. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  683. wandb/vendor/pygments/lexers/julia.py +333 -0
  684. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  685. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  686. wandb/vendor/pygments/lexers/make.py +202 -0
  687. wandb/vendor/pygments/lexers/markup.py +595 -0
  688. wandb/vendor/pygments/lexers/math.py +21 -0
  689. wandb/vendor/pygments/lexers/matlab.py +663 -0
  690. wandb/vendor/pygments/lexers/ml.py +769 -0
  691. wandb/vendor/pygments/lexers/modeling.py +358 -0
  692. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  693. wandb/vendor/pygments/lexers/monte.py +204 -0
  694. wandb/vendor/pygments/lexers/ncl.py +894 -0
  695. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  696. wandb/vendor/pygments/lexers/nit.py +64 -0
  697. wandb/vendor/pygments/lexers/nix.py +136 -0
  698. wandb/vendor/pygments/lexers/oberon.py +105 -0
  699. wandb/vendor/pygments/lexers/objective.py +504 -0
  700. wandb/vendor/pygments/lexers/ooc.py +85 -0
  701. wandb/vendor/pygments/lexers/other.py +41 -0
  702. wandb/vendor/pygments/lexers/parasail.py +79 -0
  703. wandb/vendor/pygments/lexers/parsers.py +835 -0
  704. wandb/vendor/pygments/lexers/pascal.py +644 -0
  705. wandb/vendor/pygments/lexers/pawn.py +199 -0
  706. wandb/vendor/pygments/lexers/perl.py +620 -0
  707. wandb/vendor/pygments/lexers/php.py +267 -0
  708. wandb/vendor/pygments/lexers/praat.py +294 -0
  709. wandb/vendor/pygments/lexers/prolog.py +306 -0
  710. wandb/vendor/pygments/lexers/python.py +939 -0
  711. wandb/vendor/pygments/lexers/qvt.py +152 -0
  712. wandb/vendor/pygments/lexers/r.py +453 -0
  713. wandb/vendor/pygments/lexers/rdf.py +270 -0
  714. wandb/vendor/pygments/lexers/rebol.py +431 -0
  715. wandb/vendor/pygments/lexers/resource.py +85 -0
  716. wandb/vendor/pygments/lexers/rnc.py +67 -0
  717. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  718. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  719. wandb/vendor/pygments/lexers/ruby.py +519 -0
  720. wandb/vendor/pygments/lexers/rust.py +220 -0
  721. wandb/vendor/pygments/lexers/sas.py +228 -0
  722. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  723. wandb/vendor/pygments/lexers/shell.py +794 -0
  724. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  725. wandb/vendor/pygments/lexers/smv.py +79 -0
  726. wandb/vendor/pygments/lexers/snobol.py +83 -0
  727. wandb/vendor/pygments/lexers/special.py +103 -0
  728. wandb/vendor/pygments/lexers/sql.py +681 -0
  729. wandb/vendor/pygments/lexers/stata.py +108 -0
  730. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  731. wandb/vendor/pygments/lexers/tcl.py +145 -0
  732. wandb/vendor/pygments/lexers/templates.py +2283 -0
  733. wandb/vendor/pygments/lexers/testing.py +207 -0
  734. wandb/vendor/pygments/lexers/text.py +25 -0
  735. wandb/vendor/pygments/lexers/textedit.py +169 -0
  736. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  737. wandb/vendor/pygments/lexers/theorem.py +458 -0
  738. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  739. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  740. wandb/vendor/pygments/lexers/urbi.py +133 -0
  741. wandb/vendor/pygments/lexers/varnish.py +190 -0
  742. wandb/vendor/pygments/lexers/verification.py +111 -0
  743. wandb/vendor/pygments/lexers/web.py +24 -0
  744. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  745. wandb/vendor/pygments/lexers/whiley.py +116 -0
  746. wandb/vendor/pygments/lexers/x10.py +69 -0
  747. wandb/vendor/pygments/modeline.py +44 -0
  748. wandb/vendor/pygments/plugin.py +68 -0
  749. wandb/vendor/pygments/regexopt.py +92 -0
  750. wandb/vendor/pygments/scanner.py +105 -0
  751. wandb/vendor/pygments/sphinxext.py +158 -0
  752. wandb/vendor/pygments/style.py +155 -0
  753. wandb/vendor/pygments/styles/__init__.py +80 -0
  754. wandb/vendor/pygments/styles/abap.py +29 -0
  755. wandb/vendor/pygments/styles/algol.py +63 -0
  756. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  757. wandb/vendor/pygments/styles/arduino.py +98 -0
  758. wandb/vendor/pygments/styles/autumn.py +65 -0
  759. wandb/vendor/pygments/styles/borland.py +51 -0
  760. wandb/vendor/pygments/styles/bw.py +49 -0
  761. wandb/vendor/pygments/styles/colorful.py +81 -0
  762. wandb/vendor/pygments/styles/default.py +73 -0
  763. wandb/vendor/pygments/styles/emacs.py +72 -0
  764. wandb/vendor/pygments/styles/friendly.py +72 -0
  765. wandb/vendor/pygments/styles/fruity.py +42 -0
  766. wandb/vendor/pygments/styles/igor.py +29 -0
  767. wandb/vendor/pygments/styles/lovelace.py +97 -0
  768. wandb/vendor/pygments/styles/manni.py +75 -0
  769. wandb/vendor/pygments/styles/monokai.py +106 -0
  770. wandb/vendor/pygments/styles/murphy.py +80 -0
  771. wandb/vendor/pygments/styles/native.py +65 -0
  772. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  773. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  774. wandb/vendor/pygments/styles/pastie.py +75 -0
  775. wandb/vendor/pygments/styles/perldoc.py +69 -0
  776. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  777. wandb/vendor/pygments/styles/rrt.py +33 -0
  778. wandb/vendor/pygments/styles/sas.py +44 -0
  779. wandb/vendor/pygments/styles/stata.py +40 -0
  780. wandb/vendor/pygments/styles/tango.py +141 -0
  781. wandb/vendor/pygments/styles/trac.py +63 -0
  782. wandb/vendor/pygments/styles/vim.py +63 -0
  783. wandb/vendor/pygments/styles/vs.py +38 -0
  784. wandb/vendor/pygments/styles/xcode.py +51 -0
  785. wandb/vendor/pygments/token.py +213 -0
  786. wandb/vendor/pygments/unistring.py +217 -0
  787. wandb/vendor/pygments/util.py +388 -0
  788. wandb/vendor/pynvml/__init__.py +0 -0
  789. wandb/vendor/pynvml/pynvml.py +4779 -0
  790. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  791. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  792. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  793. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  794. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  795. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  796. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  797. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  798. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  799. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  800. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  801. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  802. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  803. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  804. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  805. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  806. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  807. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  808. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  809. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  810. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  811. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  812. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  813. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  814. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  815. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  816. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  817. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  818. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  819. wandb/wandb_agent.py +588 -0
  820. wandb/wandb_controller.py +721 -0
  821. wandb/wandb_run.py +9 -0
  822. wandb-0.18.1.dist-info/METADATA +212 -0
  823. wandb-0.18.1.dist-info/RECORD +826 -0
  824. wandb-0.18.1.dist-info/WHEEL +4 -0
  825. wandb-0.18.1.dist-info/entry_points.txt +3 -0
  826. wandb-0.18.1.dist-info/licenses/LICENSE +21 -0
wandb/cli/cli.py ADDED
@@ -0,0 +1,3007 @@
1
+ #!/usr/bin/env python
2
+
3
+ import asyncio
4
+ import configparser
5
+ import datetime
6
+ import getpass
7
+ import json
8
+ import logging
9
+ import os
10
+ import pathlib
11
+ import shlex
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import textwrap
17
+ import time
18
+ import traceback
19
+ from functools import wraps
20
+ from typing import Any, Dict, Optional
21
+
22
+ import click
23
+ import yaml
24
+ from click.exceptions import ClickException
25
+
26
+ # pycreds has a find_executable that works in windows
27
+ from dockerpycreds.utils import find_executable
28
+
29
+ import wandb
30
+ import wandb.env
31
+
32
+ # from wandb.old.core import wandb_dir
33
+ import wandb.errors
34
+ import wandb.sdk.verify.verify as wandb_verify
35
+ from wandb import Config, Error, env, util, wandb_agent, wandb_sdk
36
+ from wandb.apis import InternalApi, PublicApi
37
+ from wandb.apis.public import RunQueue
38
+ from wandb.errors import UsageError, WandbCoreNotAvailableError
39
+ from wandb.integration.magic import magic_install
40
+ from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
41
+ from wandb.sdk.launch import utils as launch_utils
42
+ from wandb.sdk.launch._launch_add import _launch_add
43
+ from wandb.sdk.launch.errors import ExecutionError, LaunchError
44
+ from wandb.sdk.launch.sweeps import utils as sweep_utils
45
+ from wandb.sdk.launch.sweeps.scheduler import Scheduler
46
+ from wandb.sdk.lib import filesystem
47
+ from wandb.sdk.lib.wburls import wburls
48
+ from wandb.sync import SyncManager, get_run_from_path, get_runs
49
+ from wandb.util import get_core_path
50
+
51
+ # Send cli logs to wandb/debug-cli.<username>.log by default and fallback to a temp dir.
52
+ _wandb_dir = wandb.old.core.wandb_dir(env.get_dir())
53
+ if not os.path.exists(_wandb_dir):
54
+ _wandb_dir = tempfile.gettempdir()
55
+
56
+ try:
57
+ _username = getpass.getuser()
58
+ except KeyError:
59
+ # getuser() could raise KeyError in restricted environments like
60
+ # chroot jails or docker containers. Return user id in these cases.
61
+ _username = str(os.getuid())
62
+
63
+ _wandb_log_path = os.path.join(_wandb_dir, f"debug-cli.{_username}.log")
64
+
65
+ logging.basicConfig(
66
+ filename=_wandb_log_path,
67
+ level=logging.INFO,
68
+ format="%(asctime)s %(levelname)s %(message)s",
69
+ datefmt="%Y-%m-%d %H:%M:%S",
70
+ )
71
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO)
72
+ logger = logging.getLogger("wandb")
73
+
74
+ # Click Contexts
75
+ CONTEXT = {"default_map": {}}
76
+ RUN_CONTEXT = {
77
+ "default_map": {},
78
+ "allow_extra_args": True,
79
+ "ignore_unknown_options": True,
80
+ }
81
+
82
+
83
+ def cli_unsupported(argument):
84
+ wandb.termerror(f"Unsupported argument `{argument}`")
85
+ sys.exit(1)
86
+
87
+
88
+ class ClickWandbException(ClickException):
89
+ def format_message(self):
90
+ # log_file = util.get_log_file_path()
91
+ log_file = ""
92
+ orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}"
93
+ if issubclass(self.orig_type, Error):
94
+ return click.style(str(self.message), fg="red")
95
+ else:
96
+ return (
97
+ f"An Exception was raised, see {log_file} for full traceback.\n"
98
+ f"{orig_type}: {self.message}"
99
+ )
100
+
101
+
102
+ def display_error(func):
103
+ """Function decorator for catching common errors and re-raising as wandb.Error."""
104
+
105
+ @wraps(func)
106
+ def wrapper(*args, **kwargs):
107
+ try:
108
+ return func(*args, **kwargs)
109
+ except wandb.Error as e:
110
+ exc_type, exc_value, exc_traceback = sys.exc_info()
111
+ lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
112
+ logger.error("".join(lines))
113
+ wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}")
114
+ click_exc = ClickWandbException(e)
115
+ click_exc.orig_type = exc_type
116
+ raise click_exc.with_traceback(sys.exc_info()[2])
117
+
118
+ return wrapper
119
+
120
+
121
+ _api = None # caching api instance allows patching from unit tests
122
+
123
+
124
+ def _get_cling_api(reset=None):
125
+ """Get a reference to the internal api with cling settings."""
126
+ # TODO: move CLI to wandb-core backend
127
+ wandb.require("legacy-service")
128
+
129
+ global _api
130
+ if reset:
131
+ _api = None
132
+ wandb_sdk.wandb_setup._setup(_reset=True)
133
+ if _api is None:
134
+ # TODO(jhr): make a settings object that is better for non runs.
135
+ # only override the necessary setting
136
+ wandb.setup(settings=dict(_cli_only_mode=True))
137
+ _api = InternalApi()
138
+ return _api
139
+
140
+
141
+ def prompt_for_project(ctx, entity):
142
+ """Ask the user for a project, creating one if necessary."""
143
+ result = ctx.invoke(projects, entity=entity, display=False)
144
+ api = _get_cling_api()
145
+ try:
146
+ if len(result) == 0:
147
+ project = click.prompt("Enter a name for your first project")
148
+ # description = editor()
149
+ project = api.upsert_project(project, entity=entity)["name"]
150
+ else:
151
+ project_names = [project["name"] for project in result] + ["Create New"]
152
+ wandb.termlog("Which project should we use?")
153
+ result = util.prompt_choices(project_names)
154
+ if result:
155
+ project = result
156
+ else:
157
+ project = "Create New"
158
+ # TODO: check with the server if the project exists
159
+ if project == "Create New":
160
+ project = click.prompt(
161
+ "Enter a name for your new project", value_proc=api.format_project
162
+ )
163
+ # description = editor()
164
+ project = api.upsert_project(project, entity=entity)["name"]
165
+
166
+ except wandb.errors.CommError as e:
167
+ raise ClickException(str(e))
168
+
169
+ return project
170
+
171
+
172
+ class RunGroup(click.Group):
173
+ @display_error
174
+ def get_command(self, ctx, cmd_name):
175
+ # TODO: check if cmd_name is a file in the current dir and not require `run`?
176
+ rv = click.Group.get_command(self, ctx, cmd_name)
177
+ if rv is not None:
178
+ return rv
179
+ return None
180
+
181
+
182
+ @click.command(cls=RunGroup, invoke_without_command=True)
183
+ @click.version_option(version=wandb.__version__)
184
+ @click.pass_context
185
+ def cli(ctx):
186
+ if ctx.invoked_subcommand is None:
187
+ click.echo(ctx.get_help())
188
+
189
+
190
+ @cli.command(context_settings=CONTEXT, help="List projects", hidden=True)
191
+ @click.option(
192
+ "--entity",
193
+ "-e",
194
+ default=None,
195
+ envvar=env.ENTITY,
196
+ help="The entity to scope the listing to.",
197
+ )
198
+ @display_error
199
+ def projects(entity, display=True):
200
+ api = _get_cling_api()
201
+ projects = api.list_projects(entity=entity)
202
+ if len(projects) == 0:
203
+ message = "No projects found for {}".format(entity)
204
+ else:
205
+ message = 'Latest projects for "{}"'.format(entity)
206
+ if display:
207
+ click.echo(click.style(message, bold=True))
208
+ for project in projects:
209
+ click.echo(
210
+ "".join(
211
+ (
212
+ click.style(project["name"], fg="blue", bold=True),
213
+ " - ",
214
+ str(project["description"] or "").split("\n")[0],
215
+ )
216
+ )
217
+ )
218
+ return projects
219
+
220
+
221
+ @cli.command(context_settings=CONTEXT, help="Login to Weights & Biases")
222
+ @click.argument("key", nargs=-1)
223
+ @click.option("--cloud", is_flag=True, help="Login to the cloud instead of local")
224
+ @click.option("--host", default=None, help="Login to a specific instance of W&B")
225
+ @click.option(
226
+ "--relogin", default=None, is_flag=True, help="Force relogin if already logged in."
227
+ )
228
+ @click.option("--anonymously", default=False, is_flag=True, help="Log in anonymously")
229
+ @click.option("--verify", default=False, is_flag=True, help="Verify login credentials")
230
+ @display_error
231
+ def login(key, host, cloud, relogin, anonymously, verify, no_offline=False):
232
+ # TODO: move CLI to wandb-core backend
233
+ wandb.require("legacy-service")
234
+
235
+ # TODO: handle no_offline
236
+ anon_mode = "must" if anonymously else "never"
237
+
238
+ wandb_sdk.wandb_login._handle_host_wandb_setting(host, cloud)
239
+ # A change in click or the test harness means key can be none...
240
+ key = key[0] if key is not None and len(key) > 0 else None
241
+ if key:
242
+ relogin = True
243
+
244
+ login_settings = dict(
245
+ _cli_only_mode=True,
246
+ _disable_viewer=relogin and not verify,
247
+ anonymous=anon_mode,
248
+ )
249
+ if host is not None:
250
+ login_settings["base_url"] = host
251
+
252
+ try:
253
+ wandb.setup(settings=login_settings)
254
+ except TypeError as e:
255
+ wandb.termerror(str(e))
256
+ sys.exit(1)
257
+
258
+ wandb.login(
259
+ relogin=relogin,
260
+ key=key,
261
+ anonymous=anon_mode,
262
+ host=host,
263
+ force=True,
264
+ verify=verify,
265
+ )
266
+
267
+
268
+ @cli.command(
269
+ context_settings=CONTEXT, help="Run a wandb service", name="service", hidden=True
270
+ )
271
+ @click.option(
272
+ "--sock-port", default=None, type=int, help="The host port to bind socket service."
273
+ )
274
+ @click.option("--port-filename", default=None, help="Save allocated port to file.")
275
+ @click.option("--address", default=None, help="The address to bind service.")
276
+ @click.option("--pid", default=None, type=int, help="The parent process id to monitor.")
277
+ @click.option("--debug", is_flag=True, help="log debug info")
278
+ @click.option("--serve-sock", is_flag=True, help="use socket mode")
279
+ @display_error
280
+ def service(
281
+ sock_port=None,
282
+ port_filename=None,
283
+ address=None,
284
+ pid=None,
285
+ debug=False,
286
+ serve_sock=False,
287
+ ):
288
+ from wandb.sdk.service.server import WandbServer
289
+
290
+ server = WandbServer(
291
+ sock_port=sock_port,
292
+ port_fname=port_filename,
293
+ address=address,
294
+ pid=pid,
295
+ debug=debug,
296
+ serve_sock=serve_sock,
297
+ )
298
+ server.serve()
299
+
300
+
301
+ @cli.command(
302
+ context_settings=CONTEXT, help="Configure a directory with Weights & Biases"
303
+ )
304
+ @click.option("--project", "-p", help="The project to use.")
305
+ @click.option("--entity", "-e", help="The entity to scope the project to.")
306
+ # TODO(jhr): Enable these with settings rework
307
+ # @click.option("--setting", "-s", help="enable an arbitrary setting.", multiple=True)
308
+ # @click.option('--show', is_flag=True, help="Show settings")
309
+ @click.option("--reset", is_flag=True, help="Reset settings")
310
+ @click.option(
311
+ "--mode",
312
+ "-m",
313
+ help=' Can be "online", "offline" or "disabled". Defaults to online.',
314
+ )
315
+ @click.pass_context
316
+ @display_error
317
+ def init(ctx, project, entity, reset, mode):
318
+ from wandb.old.core import __stage_dir__, _set_stage_dir, wandb_dir
319
+
320
+ if __stage_dir__ is None:
321
+ _set_stage_dir("wandb")
322
+
323
+ # non-interactive init
324
+ if reset or project or entity or mode:
325
+ api = InternalApi()
326
+ if reset:
327
+ api.clear_setting("entity", persist=True)
328
+ api.clear_setting("project", persist=True)
329
+ api.clear_setting("mode", persist=True)
330
+ # TODO(jhr): clear more settings?
331
+ if entity:
332
+ api.set_setting("entity", entity, persist=True)
333
+ if project:
334
+ api.set_setting("project", project, persist=True)
335
+ if mode:
336
+ api.set_setting("mode", mode, persist=True)
337
+ return
338
+
339
+ if os.path.isdir(wandb_dir()) and os.path.exists(
340
+ os.path.join(wandb_dir(), "settings")
341
+ ):
342
+ click.confirm(
343
+ click.style(
344
+ "This directory has been configured previously, should we re-configure it?",
345
+ bold=True,
346
+ ),
347
+ abort=True,
348
+ )
349
+ else:
350
+ click.echo(
351
+ click.style("Let's setup this directory for W&B!", fg="green", bold=True)
352
+ )
353
+ api = _get_cling_api()
354
+ if api.api_key is None:
355
+ ctx.invoke(login)
356
+ api = _get_cling_api(reset=True)
357
+
358
+ viewer = api.viewer()
359
+
360
+ # Viewer can be `None` in case your API information became invalid, or
361
+ # in testing if you switch hosts.
362
+ if not viewer:
363
+ click.echo(
364
+ click.style(
365
+ "Your login information seems to be invalid: can you log in again please?",
366
+ fg="red",
367
+ bold=True,
368
+ )
369
+ )
370
+ ctx.invoke(login)
371
+ api = _get_cling_api(reset=True)
372
+
373
+ # This shouldn't happen.
374
+ viewer = api.viewer()
375
+ if not viewer:
376
+ click.echo(
377
+ click.style(
378
+ "We're sorry, there was a problem logging you in. "
379
+ "Please send us a note at support@wandb.com and tell us how this happened.",
380
+ fg="red",
381
+ bold=True,
382
+ )
383
+ )
384
+ sys.exit(1)
385
+
386
+ # At this point we should be logged in successfully.
387
+ if len(viewer["teams"]["edges"]) > 1:
388
+ team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [
389
+ "Manual entry"
390
+ ]
391
+ wandb.termlog(
392
+ "Which team should we use?",
393
+ )
394
+ result = util.prompt_choices(team_names)
395
+ # result can be empty on click
396
+ if result:
397
+ entity = result
398
+ else:
399
+ entity = "Manual Entry"
400
+ if entity == "Manual Entry":
401
+ entity = click.prompt("Enter the name of the team you want to use")
402
+ else:
403
+ entity = viewer.get("entity") or click.prompt(
404
+ "What username or team should we use?"
405
+ )
406
+
407
+ # TODO: this error handling sucks and the output isn't pretty
408
+ try:
409
+ project = prompt_for_project(ctx, entity)
410
+ except ClickWandbException:
411
+ raise ClickException(f"Could not find team: {entity}")
412
+
413
+ api.set_setting("entity", entity, persist=True)
414
+ api.set_setting("project", project, persist=True)
415
+ api.set_setting("base_url", api.settings().get("base_url"), persist=True)
416
+
417
+ filesystem.mkdir_exists_ok(wandb_dir())
418
+ with open(os.path.join(wandb_dir(), ".gitignore"), "w") as file:
419
+ file.write("*\n!settings")
420
+
421
+ click.echo(
422
+ click.style("This directory is configured! Next, track a run:\n", fg="green")
423
+ + textwrap.dedent(
424
+ """\
425
+ * In your training script:
426
+ {code1}
427
+ {code2}
428
+ * then `{run}`.
429
+ """
430
+ ).format(
431
+ code1=click.style("import wandb", bold=True),
432
+ code2=click.style('wandb.init(project="{}")'.format(project), bold=True),
433
+ run=click.style("python <train.py>", bold=True),
434
+ )
435
+ )
436
+
437
+
438
+ @cli.group()
439
+ def beta():
440
+ """Beta versions of wandb CLI commands. Requires wandb-core."""
441
+ # this is the future that requires wandb-core!
442
+ import wandb.env
443
+
444
+ wandb._sentry.configure_scope(process_context="wandb_beta")
445
+
446
+ if wandb.env.is_require_legacy_service():
447
+ raise UsageError(
448
+ "wandb beta commands can only be used with wandb-core. "
449
+ f"Please make sure that `{wandb.env._REQUIRE_LEGACY_SERVICE}` is not set."
450
+ )
451
+
452
+ try:
453
+ get_core_path()
454
+ except WandbCoreNotAvailableError as e:
455
+ wandb._sentry.exception(f"using `wandb beta`. failed with {e}")
456
+ click.secho(
457
+ (e),
458
+ fg="red",
459
+ err=True,
460
+ )
461
+
462
+
463
+ @beta.command(
464
+ name="sync",
465
+ context_settings=CONTEXT,
466
+ help="Upload a training run to W&B",
467
+ )
468
+ @click.pass_context
469
+ @click.argument("wandb_dir", nargs=1, type=click.Path(exists=True))
470
+ @click.option("--id", "run_id", help="The run you want to upload to.")
471
+ @click.option("--project", "-p", help="The project you want to upload to.")
472
+ @click.option("--entity", "-e", help="The entity to scope to.")
473
+ @click.option("--skip-console", is_flag=True, default=False, help="Skip console logs")
474
+ @click.option("--append", is_flag=True, default=False, help="Append run")
475
+ @click.option(
476
+ "--include",
477
+ "-i",
478
+ help="Glob to include. Can be used multiple times.",
479
+ multiple=True,
480
+ )
481
+ @click.option(
482
+ "--exclude",
483
+ "-e",
484
+ help="Glob to exclude. Can be used multiple times.",
485
+ multiple=True,
486
+ )
487
+ @click.option(
488
+ "--mark-synced/--no-mark-synced",
489
+ is_flag=True,
490
+ default=True,
491
+ help="Mark runs as synced",
492
+ )
493
+ @click.option(
494
+ "--skip-synced/--no-skip-synced",
495
+ is_flag=True,
496
+ default=True,
497
+ help="Skip synced runs",
498
+ )
499
+ @click.option(
500
+ "--dry-run", is_flag=True, help="Perform a dry run without uploading anything."
501
+ )
502
+ @display_error
503
+ def sync_beta(
504
+ ctx,
505
+ wandb_dir=None,
506
+ run_id: Optional[str] = None,
507
+ project: Optional[str] = None,
508
+ entity: Optional[str] = None,
509
+ skip_console: bool = False,
510
+ append: bool = False,
511
+ include: Optional[str] = None,
512
+ exclude: Optional[str] = None,
513
+ skip_synced: bool = True,
514
+ mark_synced: bool = True,
515
+ dry_run: bool = False,
516
+ ):
517
+ import concurrent.futures
518
+ from multiprocessing import cpu_count
519
+
520
+ paths = set()
521
+
522
+ # TODO: test file discovery logic
523
+ # include and exclude globs are evaluated relative to the provided base_path
524
+ if include:
525
+ for pattern in include:
526
+ matching_dirs = list(pathlib.Path(wandb_dir).glob(pattern))
527
+ for d in matching_dirs:
528
+ if not d.is_dir():
529
+ continue
530
+ wandb_files = [p for p in d.glob("*.wandb") if p.is_file()]
531
+ if len(wandb_files) > 1:
532
+ print(f"Multiple wandb files found in directory {d}, skipping")
533
+ elif len(wandb_files) == 1:
534
+ paths.add(d)
535
+ else:
536
+ paths.update({p.parent for p in pathlib.Path(wandb_dir).glob("**/*.wandb")})
537
+
538
+ for pattern in exclude:
539
+ matching_dirs = list(pathlib.Path(wandb_dir).glob(pattern))
540
+ for d in matching_dirs:
541
+ if not d.is_dir():
542
+ continue
543
+ if d in paths:
544
+ paths.remove(d)
545
+
546
+ # remove paths that are already synced, if requested
547
+ if skip_synced:
548
+ synced_paths = set()
549
+ for path in paths:
550
+ wandb_synced_files = [p for p in path.glob("*.wandb.synced") if p.is_file()]
551
+ if len(wandb_synced_files) > 1:
552
+ print(
553
+ f"Multiple wandb.synced files found in directory {path}, skipping"
554
+ )
555
+ elif len(wandb_synced_files) == 1:
556
+ synced_paths.add(path)
557
+ paths -= synced_paths
558
+
559
+ if run_id and len(paths) > 1:
560
+ # TODO: handle this more gracefully
561
+ click.echo("id can only be set for a single run.", err=True)
562
+ sys.exit(1)
563
+
564
+ if not paths:
565
+ click.echo("No runs to sync.")
566
+ return
567
+
568
+ click.echo("Found runs:")
569
+ for path in paths:
570
+ click.echo(f" {path}")
571
+
572
+ if dry_run:
573
+ return
574
+
575
+ wandb.sdk.wandb_setup.setup()
576
+
577
+ # TODO: make it thread-safe in the Rust code
578
+ with concurrent.futures.ProcessPoolExecutor(
579
+ max_workers=min(len(paths), cpu_count())
580
+ ) as executor:
581
+ futures = []
582
+ for path in paths:
583
+ # we already know there is only one wandb file in the directory
584
+ wandb_file = [p for p in path.glob("*.wandb") if p.is_file()][0]
585
+ future = executor.submit(
586
+ wandb._sync,
587
+ wandb_file,
588
+ run_id=run_id,
589
+ project=project,
590
+ entity=entity,
591
+ skip_console=skip_console,
592
+ append=append,
593
+ mark_synced=mark_synced,
594
+ )
595
+ futures.append(future)
596
+
597
+ # Wait for tasks to complete
598
+ for _ in concurrent.futures.as_completed(futures):
599
+ pass
600
+
601
+
602
+ @cli.command(
603
+ context_settings=CONTEXT, help="Upload an offline training directory to W&B"
604
+ )
605
+ @click.pass_context
606
+ @click.argument("path", nargs=-1, type=click.Path(exists=True))
607
+ @click.option("--view", is_flag=True, default=False, help="View runs", hidden=True)
608
+ @click.option("--verbose", is_flag=True, default=False, help="Verbose", hidden=True)
609
+ @click.option("--id", "run_id", help="The run you want to upload to.")
610
+ @click.option("--project", "-p", help="The project you want to upload to.")
611
+ @click.option("--entity", "-e", help="The entity to scope to.")
612
+ @click.option(
613
+ "--job_type",
614
+ "job_type",
615
+ help="Specifies the type of run for grouping related runs together.",
616
+ )
617
+ @click.option(
618
+ "--sync-tensorboard/--no-sync-tensorboard",
619
+ is_flag=True,
620
+ default=None,
621
+ help="Stream tfevent files to wandb.",
622
+ )
623
+ @click.option("--include-globs", help="Comma separated list of globs to include.")
624
+ @click.option("--exclude-globs", help="Comma separated list of globs to exclude.")
625
+ @click.option(
626
+ "--include-online/--no-include-online",
627
+ is_flag=True,
628
+ default=None,
629
+ help="Include online runs",
630
+ )
631
+ @click.option(
632
+ "--include-offline/--no-include-offline",
633
+ is_flag=True,
634
+ default=None,
635
+ help="Include offline runs",
636
+ )
637
+ @click.option(
638
+ "--include-synced/--no-include-synced",
639
+ is_flag=True,
640
+ default=None,
641
+ help="Include synced runs",
642
+ )
643
+ @click.option(
644
+ "--mark-synced/--no-mark-synced",
645
+ is_flag=True,
646
+ default=True,
647
+ help="Mark runs as synced",
648
+ )
649
+ @click.option("--sync-all", is_flag=True, default=False, help="Sync all runs")
650
+ @click.option("--clean", is_flag=True, default=False, help="Delete synced runs")
651
+ @click.option(
652
+ "--clean-old-hours",
653
+ default=24,
654
+ help="Delete runs created before this many hours. To be used alongside --clean flag.",
655
+ type=int,
656
+ )
657
+ @click.option(
658
+ "--clean-force",
659
+ is_flag=True,
660
+ default=False,
661
+ help="Clean without confirmation prompt.",
662
+ )
663
+ @click.option("--ignore", hidden=True)
664
+ @click.option("--show", default=5, help="Number of runs to show")
665
+ @click.option("--append", is_flag=True, default=False, help="Append run")
666
+ @click.option("--skip-console", is_flag=True, default=False, help="Skip console logs")
667
+ @display_error
668
+ def sync(
669
+ ctx,
670
+ path=None,
671
+ view=None,
672
+ verbose=None,
673
+ run_id=None,
674
+ project=None,
675
+ entity=None,
676
+ job_type=None, # trace this back to SyncManager
677
+ sync_tensorboard=None,
678
+ include_globs=None,
679
+ exclude_globs=None,
680
+ include_online=None,
681
+ include_offline=None,
682
+ include_synced=None,
683
+ mark_synced=None,
684
+ sync_all=None,
685
+ ignore=None,
686
+ show=None,
687
+ clean=None,
688
+ clean_old_hours=24,
689
+ clean_force=None,
690
+ append=None,
691
+ skip_console=None,
692
+ ):
693
+ api = _get_cling_api()
694
+ if not api.is_authenticated:
695
+ wandb.termlog("Login to W&B to sync offline runs")
696
+ ctx.invoke(login, no_offline=True)
697
+ api = _get_cling_api(reset=True)
698
+
699
+ if ignore:
700
+ exclude_globs = ignore
701
+ if include_globs:
702
+ include_globs = include_globs.split(",")
703
+ if exclude_globs:
704
+ exclude_globs = exclude_globs.split(",")
705
+
706
+ def _summary():
707
+ all_items = get_runs(
708
+ include_online=True,
709
+ include_offline=True,
710
+ include_synced=True,
711
+ include_unsynced=True,
712
+ )
713
+ sync_items = get_runs(
714
+ include_online=include_online if include_online is not None else True,
715
+ include_offline=include_offline if include_offline is not None else True,
716
+ include_synced=include_synced if include_synced is not None else False,
717
+ include_unsynced=True,
718
+ exclude_globs=exclude_globs,
719
+ include_globs=include_globs,
720
+ )
721
+ synced = []
722
+ unsynced = []
723
+ for item in all_items:
724
+ (synced if item.synced else unsynced).append(item)
725
+ if sync_items:
726
+ wandb.termlog(f"Number of runs to be synced: {len(sync_items)}")
727
+ if show and show < len(sync_items):
728
+ wandb.termlog(f"Showing {show} runs to be synced:")
729
+ for item in sync_items[: (show or len(sync_items))]:
730
+ wandb.termlog(f" {item}")
731
+ else:
732
+ wandb.termlog("No runs to be synced.")
733
+ if synced:
734
+ clean_cmd = click.style("wandb sync --clean", fg="yellow")
735
+ wandb.termlog(
736
+ f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory."
737
+ )
738
+ if unsynced:
739
+ sync_cmd = click.style("wandb sync --sync-all", fg="yellow")
740
+ wandb.termlog(
741
+ f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory."
742
+ )
743
+
744
+ def _sync_path(_path, _sync_tensorboard):
745
+ if run_id and len(_path) > 1:
746
+ wandb.termerror("id can only be set for a single run.")
747
+ sys.exit(1)
748
+ sm = SyncManager(
749
+ project=project,
750
+ entity=entity,
751
+ run_id=run_id,
752
+ job_type=job_type,
753
+ mark_synced=mark_synced,
754
+ app_url=api.app_url,
755
+ view=view,
756
+ verbose=verbose,
757
+ sync_tensorboard=_sync_tensorboard,
758
+ log_path=_wandb_log_path,
759
+ append=append,
760
+ skip_console=skip_console,
761
+ )
762
+ for p in _path:
763
+ sm.add(p)
764
+ sm.start()
765
+ while not sm.is_done():
766
+ _ = sm.poll()
767
+
768
+ def _sync_all():
769
+ sync_items = get_runs(
770
+ include_online=include_online if include_online is not None else True,
771
+ include_offline=include_offline if include_offline is not None else True,
772
+ include_synced=include_synced if include_synced is not None else False,
773
+ include_unsynced=True,
774
+ exclude_globs=exclude_globs,
775
+ include_globs=include_globs,
776
+ )
777
+ if not sync_items:
778
+ wandb.termerror("Nothing to sync.")
779
+ else:
780
+ # When syncing run directories, default to not syncing tensorboard
781
+ sync_tb = sync_tensorboard if sync_tensorboard is not None else False
782
+ _sync_path(sync_items, sync_tb)
783
+
784
+ def _clean():
785
+ if path:
786
+ runs = list(map(get_run_from_path, path))
787
+ if not clean_force:
788
+ click.confirm(
789
+ click.style(
790
+ f"Are you sure you want to remove {len(runs)} runs?",
791
+ bold=True,
792
+ ),
793
+ abort=True,
794
+ )
795
+ for run in runs:
796
+ shutil.rmtree(run.path)
797
+ click.echo(click.style("Success!", fg="green"))
798
+ return
799
+ runs = get_runs(
800
+ include_online=include_online if include_online is not None else True,
801
+ include_offline=include_offline if include_offline is not None else True,
802
+ include_synced=include_synced if include_synced is not None else True,
803
+ include_unsynced=False,
804
+ exclude_globs=exclude_globs,
805
+ include_globs=include_globs,
806
+ )
807
+ since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours)
808
+ old_runs = [run for run in runs if run.datetime < since]
809
+ old_runs.sort(key=lambda _run: _run.datetime)
810
+ if old_runs:
811
+ click.echo(
812
+ f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours"
813
+ )
814
+ for run in old_runs:
815
+ click.echo(run.path)
816
+ if not clean_force:
817
+ click.confirm(
818
+ click.style(
819
+ f"Are you sure you want to remove {len(old_runs)} runs?",
820
+ bold=True,
821
+ ),
822
+ abort=True,
823
+ )
824
+ for run in old_runs:
825
+ shutil.rmtree(run.path)
826
+ click.echo(click.style("Success!", fg="green"))
827
+ else:
828
+ click.echo(
829
+ click.style(
830
+ f"No runs older than {clean_old_hours} hours found", fg="red"
831
+ )
832
+ )
833
+
834
+ if sync_all:
835
+ _sync_all()
836
+ elif clean:
837
+ _clean()
838
+ elif path:
839
+ # When syncing a specific path, default to syncing tensorboard
840
+ sync_tb = sync_tensorboard if sync_tensorboard is not None else True
841
+ _sync_path(path, sync_tb)
842
+ else:
843
+ _summary()
844
+
845
+
846
+ @cli.command(
847
+ context_settings=CONTEXT,
848
+ help="Initialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.",
849
+ )
850
+ @click.option(
851
+ "--project",
852
+ "-p",
853
+ default=None,
854
+ help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.""",
855
+ )
856
+ @click.option(
857
+ "--entity",
858
+ "-e",
859
+ default=None,
860
+ help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
861
+ )
862
+ @click.option("--controller", is_flag=True, default=False, help="Run local controller")
863
+ @click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
864
+ @click.option(
865
+ "--name",
866
+ default=None,
867
+ help="The name of the sweep. The sweep ID is used if no name is specified.",
868
+ )
869
+ @click.option("--program", default=None, help="Set sweep program")
870
+ @click.option("--settings", default=None, help="Set sweep settings", hidden=True)
871
+ @click.option("--update", default=None, help="Update pending sweep")
872
+ @click.option(
873
+ "--stop",
874
+ is_flag=True,
875
+ default=False,
876
+ help="Finish a sweep to stop running new runs and let currently running runs finish.",
877
+ )
878
+ @click.option(
879
+ "--cancel",
880
+ is_flag=True,
881
+ default=False,
882
+ help="Cancel a sweep to kill all running runs and stop running new runs.",
883
+ )
884
+ @click.option(
885
+ "--pause",
886
+ is_flag=True,
887
+ default=False,
888
+ help="Pause a sweep to temporarily stop running new runs.",
889
+ )
890
+ @click.option(
891
+ "--resume",
892
+ is_flag=True,
893
+ default=False,
894
+ help="Resume a sweep to continue running new runs.",
895
+ )
896
+ @click.option(
897
+ "--prior_run",
898
+ "-R",
899
+ "prior_runs",
900
+ multiple=True,
901
+ default=None,
902
+ help="ID of an existing run to add to this sweep",
903
+ )
904
+ @click.argument("config_yaml_or_sweep_id")
905
+ @click.pass_context
906
+ @display_error
907
+ def sweep(
908
+ ctx,
909
+ project,
910
+ entity,
911
+ controller,
912
+ verbose,
913
+ name,
914
+ program,
915
+ settings,
916
+ update,
917
+ stop,
918
+ cancel,
919
+ pause,
920
+ resume,
921
+ prior_runs,
922
+ config_yaml_or_sweep_id,
923
+ ):
924
+ state_args = "stop", "cancel", "pause", "resume"
925
+ lcls = locals()
926
+ is_state_change_command = sum(lcls[k] for k in state_args)
927
+ if is_state_change_command > 1:
928
+ raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.")
929
+ elif is_state_change_command == 1:
930
+ sweep_id = config_yaml_or_sweep_id
931
+ api = _get_cling_api()
932
+ if not api.is_authenticated:
933
+ wandb.termlog("Login to W&B to use the sweep feature")
934
+ ctx.invoke(login, no_offline=True)
935
+ api = _get_cling_api(reset=True)
936
+ parts = dict(entity=entity, project=project, name=sweep_id)
937
+ err = sweep_utils.parse_sweep_id(parts)
938
+ if err:
939
+ wandb.termerror(err)
940
+ return
941
+ entity = parts.get("entity") or entity
942
+ project = parts.get("project") or project
943
+ sweep_id = parts.get("name") or sweep_id
944
+ state = [s for s in state_args if lcls[s]][0]
945
+ ings = {
946
+ "stop": "Stopping",
947
+ "cancel": "Cancelling",
948
+ "pause": "Pausing",
949
+ "resume": "Resuming",
950
+ }
951
+ wandb.termlog(f"{ings[state]} sweep {entity}/{project}/{sweep_id}")
952
+ getattr(api, "{}_sweep".format(state))(sweep_id, entity=entity, project=project)
953
+ wandb.termlog("Done.")
954
+ return
955
+ else:
956
+ config_yaml = config_yaml_or_sweep_id
957
+
958
+ def _parse_settings(settings):
959
+ """Parse settings from json or comma separated assignments."""
960
+ ret = {}
961
+ # TODO(jhr): merge with magic:_parse_magic
962
+ if settings.find("=") > 0:
963
+ for item in settings.split(","):
964
+ kv = item.split("=")
965
+ if len(kv) != 2:
966
+ wandb.termwarn(
967
+ "Unable to parse sweep settings key value pair", repeat=False
968
+ )
969
+ ret.update(dict([kv]))
970
+ return ret
971
+ wandb.termwarn("Unable to parse settings parameter", repeat=False)
972
+ return ret
973
+
974
+ api = _get_cling_api()
975
+ if not api.is_authenticated:
976
+ wandb.termlog("Login to W&B to use the sweep feature")
977
+ ctx.invoke(login, no_offline=True)
978
+ api = _get_cling_api(reset=True)
979
+
980
+ sweep_obj_id = None
981
+ if update:
982
+ parts = dict(entity=entity, project=project, name=update)
983
+ err = sweep_utils.parse_sweep_id(parts)
984
+ if err:
985
+ wandb.termerror(err)
986
+ return
987
+ entity = parts.get("entity") or entity
988
+ project = parts.get("project") or project
989
+ sweep_id = parts.get("name") or update
990
+
991
+ has_project = (project or api.settings("project")) is not None
992
+ has_entity = (entity or api.settings("entity")) is not None
993
+
994
+ termerror_msg = (
995
+ "Sweep lookup requires a valid %s, and none was specified. \n"
996
+ "Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` "
997
+ "from the command line, specify the full sweep path via: \n\n"
998
+ " wandb sweep {username}/{projectname}/{sweepid}\n\n"
999
+ )
1000
+
1001
+ if not has_entity:
1002
+ wandb.termerror(termerror_msg % (("entity",) * 2))
1003
+ return
1004
+
1005
+ if not has_project:
1006
+ wandb.termerror(termerror_msg % (("project",) * 2))
1007
+ return
1008
+
1009
+ found = api.sweep(sweep_id, "{}", entity=entity, project=project)
1010
+ if not found:
1011
+ wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}")
1012
+ return
1013
+ sweep_obj_id = found["id"]
1014
+
1015
+ action = "Updating" if sweep_obj_id else "Creating"
1016
+ wandb.termlog(f"{action} sweep from: {config_yaml}")
1017
+ config = sweep_utils.load_sweep_config(config_yaml)
1018
+
1019
+ # Set or override parameters
1020
+ if name:
1021
+ config["name"] = name
1022
+ if program:
1023
+ config["program"] = program
1024
+ if settings:
1025
+ settings = _parse_settings(settings)
1026
+ if settings:
1027
+ config.setdefault("settings", {})
1028
+ config["settings"].update(settings)
1029
+ if controller:
1030
+ config.setdefault("controller", {})
1031
+ config["controller"]["type"] = "local"
1032
+
1033
+ is_local = config.get("controller", {}).get("type") == "local"
1034
+ if is_local:
1035
+ from wandb import controller as wandb_controller
1036
+
1037
+ tuner = wandb_controller()
1038
+ err = tuner._validate(config)
1039
+ if err:
1040
+ wandb.termerror(f"Error in sweep file: {err}")
1041
+ return
1042
+
1043
+ env = os.environ
1044
+ entity = (
1045
+ entity
1046
+ or env.get("WANDB_ENTITY")
1047
+ or config.get("entity")
1048
+ or api.settings("entity")
1049
+ )
1050
+ project = (
1051
+ project
1052
+ or env.get("WANDB_PROJECT")
1053
+ or config.get("project")
1054
+ or api.settings("project")
1055
+ or util.auto_project_name(config.get("program"))
1056
+ )
1057
+
1058
+ sweep_id, warnings = api.upsert_sweep(
1059
+ config,
1060
+ project=project,
1061
+ entity=entity,
1062
+ obj_id=sweep_obj_id,
1063
+ prior_runs=prior_runs,
1064
+ )
1065
+ sweep_utils.handle_sweep_config_violations(warnings)
1066
+
1067
+ # Log nicely formatted sweep information
1068
+ styled_id = click.style(sweep_id, fg="yellow")
1069
+ wandb.termlog(f"{action} sweep with ID: {styled_id}")
1070
+
1071
+ sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id)
1072
+ if sweep_url:
1073
+ styled_url = click.style(sweep_url, underline=True, fg="blue")
1074
+ wandb.termlog(f"View sweep at: {styled_url}")
1075
+
1076
+ # re-probe entity and project if it was auto-detected by upsert_sweep
1077
+ entity = entity or env.get("WANDB_ENTITY")
1078
+ project = project or env.get("WANDB_PROJECT")
1079
+
1080
+ if entity and project:
1081
+ sweep_path = f"{entity}/{project}/{sweep_id}"
1082
+ elif project:
1083
+ sweep_path = f"{project}/{sweep_id}"
1084
+ else:
1085
+ sweep_path = sweep_id
1086
+
1087
+ if sweep_path.find(" ") >= 0:
1088
+ sweep_path = f"{sweep_path!r}"
1089
+
1090
+ styled_path = click.style(f"wandb agent {sweep_path}", fg="yellow")
1091
+ wandb.termlog(f"Run sweep agent with: {styled_path}")
1092
+ if controller:
1093
+ wandb.termlog("Starting wandb controller...")
1094
+ from wandb import controller as wandb_controller
1095
+
1096
+ tuner = wandb_controller(sweep_id)
1097
+ tuner.run(verbose=verbose)
1098
+
1099
+
1100
+ @cli.command(
1101
+ context_settings=CONTEXT,
1102
+ no_args_is_help=True,
1103
+ help="Run a W&B launch sweep (Experimental).",
1104
+ )
1105
+ @click.option(
1106
+ "--queue",
1107
+ "-q",
1108
+ default=None,
1109
+ help="The name of a queue to push the sweep to",
1110
+ )
1111
+ @click.option(
1112
+ "--project",
1113
+ "-p",
1114
+ default=None,
1115
+ help="Name of the project which the agent will watch. "
1116
+ "If passed in, will override the project value passed in using a config file",
1117
+ )
1118
+ @click.option(
1119
+ "--entity",
1120
+ "-e",
1121
+ default=None,
1122
+ help="The entity to use. Defaults to current logged-in user",
1123
+ )
1124
+ @click.option(
1125
+ "--resume_id",
1126
+ "-r",
1127
+ default=None,
1128
+ help="Resume a launch sweep by passing an 8-char sweep id. Queue required",
1129
+ )
1130
+ @click.option(
1131
+ "--prior_run",
1132
+ "-R",
1133
+ "prior_runs",
1134
+ multiple=True,
1135
+ default=None,
1136
+ help="ID of an existing run to add to this sweep",
1137
+ )
1138
+ @click.argument("config", required=False, type=click.Path(exists=True))
1139
+ @click.pass_context
1140
+ @display_error
1141
+ def launch_sweep(
1142
+ ctx,
1143
+ project,
1144
+ entity,
1145
+ queue,
1146
+ config,
1147
+ resume_id,
1148
+ prior_runs,
1149
+ ):
1150
+ api = _get_cling_api()
1151
+ env = os.environ
1152
+ if not api.is_authenticated:
1153
+ wandb.termlog("Login to W&B to use the sweep feature")
1154
+ ctx.invoke(login, no_offline=True)
1155
+ api = _get_cling_api(reset=True)
1156
+
1157
+ entity = entity or env.get("WANDB_ENTITY") or api.settings("entity")
1158
+ if entity is None:
1159
+ wandb.termerror("Must specify entity when using launch")
1160
+ return
1161
+
1162
+ project = project or env.get("WANDB_PROJECT") or api.settings("project")
1163
+ if project is None:
1164
+ wandb.termerror("A project must be configured when using launch")
1165
+ return
1166
+
1167
+ # get personal username, not team name or service account, default to entity
1168
+ author = api.viewer().get("username") or entity
1169
+
1170
+ # if not sweep_config XOR resume_id
1171
+ if not (config or resume_id):
1172
+ wandb.termerror("'config' and/or 'resume_id' required")
1173
+ return
1174
+
1175
+ parsed_user_config = sweep_utils.load_launch_sweep_config(config)
1176
+ # Rip special keys out of config, store in scheduler run_config
1177
+ launch_args: Dict[str, Any] = parsed_user_config.pop("launch", {})
1178
+ scheduler_args: Dict[str, Any] = parsed_user_config.pop("scheduler", {})
1179
+ settings: Dict[str, Any] = scheduler_args.pop("settings", {})
1180
+
1181
+ scheduler_job: Optional[str] = scheduler_args.get("job")
1182
+ if scheduler_job:
1183
+ wandb.termwarn(
1184
+ "Using a scheduler job for launch sweeps is *experimental* and may change without warning"
1185
+ )
1186
+ queue: Optional[str] = queue or launch_args.get("queue")
1187
+
1188
+ sweep_config, sweep_obj_id = None, None
1189
+ if not resume_id:
1190
+ sweep_config = parsed_user_config
1191
+
1192
+ # check method
1193
+ method = sweep_config.get("method")
1194
+ if scheduler_job and not method:
1195
+ sweep_config["method"] = "custom"
1196
+ elif scheduler_job and method != "custom":
1197
+ # TODO(gst): Check if using Anaconda2
1198
+ wandb.termwarn(
1199
+ "Use 'method': 'custom' in the sweep config when using scheduler jobs, "
1200
+ "or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), "
1201
+ "set the method in the sweep config under scheduler.settings.method "
1202
+ )
1203
+ settings["method"] = method
1204
+
1205
+ if settings.get("method"):
1206
+ # assume WandbScheduler, and user is using this right
1207
+ sweep_config["method"] = settings["method"]
1208
+
1209
+ else: # Resuming an existing sweep
1210
+ found = api.sweep(resume_id, "{}", entity=entity, project=project)
1211
+ if not found:
1212
+ wandb.termerror(f"Could not find sweep {entity}/{project}/{resume_id}")
1213
+ return
1214
+
1215
+ if found.get("state") == "RUNNING":
1216
+ wandb.termerror(
1217
+ f"Cannot resume sweep {entity}/{project}/{resume_id}, it is already running"
1218
+ )
1219
+ return
1220
+
1221
+ sweep_obj_id = found["id"]
1222
+ sweep_config = yaml.safe_load(found["config"])
1223
+ wandb.termlog(f"Resuming from existing sweep {entity}/{project}/{resume_id}")
1224
+ if len(parsed_user_config.keys()) > 0:
1225
+ wandb.termwarn(
1226
+ "Sweep parameters loaded from resumed sweep, ignoring provided config"
1227
+ )
1228
+
1229
+ prev_scheduler = json.loads(found.get("scheduler") or "{}")
1230
+ run_spec = json.loads(prev_scheduler.get("run_spec", "{}"))
1231
+ if (
1232
+ scheduler_job
1233
+ and run_spec.get("job")
1234
+ and run_spec.get("job") != scheduler_job
1235
+ ):
1236
+ wandb.termerror(
1237
+ f"Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: {run_spec.get('job')}, job in config: {scheduler_job}"
1238
+ )
1239
+ return
1240
+
1241
+ prev_scheduler_args, prev_settings = sweep_utils.get_previous_args(run_spec)
1242
+ # Passed in scheduler_args and settings override previous
1243
+ scheduler_args.update(prev_scheduler_args)
1244
+ settings.update(prev_settings)
1245
+ if not queue:
1246
+ wandb.termerror(
1247
+ "Launch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config"
1248
+ )
1249
+ return
1250
+
1251
+ entrypoint = Scheduler.ENTRYPOINT if not scheduler_job else None
1252
+ args = sweep_utils.construct_scheduler_args(
1253
+ return_job=scheduler_job is not None,
1254
+ sweep_config=sweep_config,
1255
+ queue=queue,
1256
+ project=project,
1257
+ author=author,
1258
+ )
1259
+ if not args:
1260
+ return
1261
+
1262
+ # validate training job existence
1263
+ if not sweep_utils.check_job_exists(PublicApi(), sweep_config.get("job")):
1264
+ return False
1265
+
1266
+ # validate scheduler job existence, if present
1267
+ if not sweep_utils.check_job_exists(PublicApi(), scheduler_job):
1268
+ return False
1269
+
1270
+ # Set run overrides for the Scheduler
1271
+ overrides = {"run_config": {}}
1272
+ if launch_args:
1273
+ overrides["run_config"]["launch"] = launch_args
1274
+ if scheduler_args:
1275
+ overrides["run_config"]["scheduler"] = scheduler_args
1276
+ if settings:
1277
+ overrides["run_config"]["settings"] = settings
1278
+
1279
+ if scheduler_job:
1280
+ overrides["run_config"]["sweep_args"] = args
1281
+ else:
1282
+ overrides["args"] = args
1283
+
1284
+ # configure scheduler job resource
1285
+ resource = scheduler_args.get("resource")
1286
+ if resource:
1287
+ if resource == "local-process" and scheduler_job:
1288
+ wandb.termerror(
1289
+ "Scheduler jobs cannot be run with the 'local-process' resource"
1290
+ )
1291
+ return
1292
+ if resource == "local-process" and scheduler_args.get("docker_image"):
1293
+ wandb.termerror(
1294
+ "Scheduler jobs cannot be run with the 'local-process' resource and a docker image"
1295
+ )
1296
+ return
1297
+ else: # no resource set, default local-process if not scheduler job, else container
1298
+ resource = "local-process" if not scheduler_job else "local-container"
1299
+
1300
+ # Launch job spec for the Scheduler
1301
+ launch_scheduler_spec = launch_utils.construct_launch_spec(
1302
+ uri=Scheduler.PLACEHOLDER_URI,
1303
+ api=api,
1304
+ name="Scheduler.WANDB_SWEEP_ID",
1305
+ project=project,
1306
+ entity=entity,
1307
+ docker_image=scheduler_args.get("docker_image"),
1308
+ resource=resource,
1309
+ entry_point=entrypoint,
1310
+ resource_args=scheduler_args.get("resource_args", {}),
1311
+ repository=launch_args.get("registry", {}).get("url", None),
1312
+ job=scheduler_job,
1313
+ version=None,
1314
+ launch_config={"overrides": overrides},
1315
+ run_id="WANDB_SWEEP_ID", # scheduler inits run with sweep_id=run_id
1316
+ author=None, # author gets passed into scheduler override args
1317
+ )
1318
+ launch_scheduler_with_queue = json.dumps(
1319
+ {
1320
+ "queue": queue,
1321
+ "run_queue_project": launch_utils.LAUNCH_DEFAULT_PROJECT,
1322
+ "run_spec": json.dumps(launch_scheduler_spec),
1323
+ }
1324
+ )
1325
+
1326
+ sweep_id, warnings = api.upsert_sweep(
1327
+ sweep_config,
1328
+ project=project,
1329
+ entity=entity,
1330
+ obj_id=sweep_obj_id, # if resuming
1331
+ launch_scheduler=launch_scheduler_with_queue,
1332
+ state="PENDING",
1333
+ prior_runs=prior_runs,
1334
+ template_variable_values=scheduler_args.get("template_variables", None),
1335
+ )
1336
+ sweep_utils.handle_sweep_config_violations(warnings)
1337
+ # Log nicely formatted sweep information
1338
+ styled_id = click.style(sweep_id, fg="yellow")
1339
+ wandb.termlog(f"{'Resumed' if resume_id else 'Created'} sweep with ID: {styled_id}")
1340
+ sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id)
1341
+ if sweep_url:
1342
+ styled_url = click.style(sweep_url, underline=True, fg="blue")
1343
+ wandb.termlog(f"View sweep at: {styled_url}")
1344
+ wandb.termlog(f"Scheduler added to launch queue ({queue})")
1345
+
1346
+
1347
+ @cli.command(help=f"Launch or queue a W&B Job. See {wburls.get('cli_launch')}")
1348
+ @click.option(
1349
+ "--uri",
1350
+ "-u",
1351
+ metavar="(str)",
1352
+ default=None,
1353
+ help="Local path or git repo uri to launch. If provided this command will "
1354
+ "create a job from the specified uri.",
1355
+ )
1356
+ @click.option(
1357
+ "--job",
1358
+ "-j",
1359
+ metavar="(str)",
1360
+ default=None,
1361
+ help="Name of the job to launch. If passed in, launch does not require a uri.",
1362
+ )
1363
+ @click.option(
1364
+ "--entry-point",
1365
+ "-E",
1366
+ metavar="NAME",
1367
+ default=None,
1368
+ help="""Entry point within project. [default: main]. If the entry point is not found,
1369
+ attempts to run the project file with the specified name as a script,
1370
+ using 'python' to run .py files and the default shell (specified by
1371
+ environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.""",
1372
+ )
1373
+ @click.option(
1374
+ "--git-version",
1375
+ "-g",
1376
+ metavar="GIT-VERSION",
1377
+ hidden=True,
1378
+ help="Version of the project to run, as a Git commit reference for Git projects.",
1379
+ )
1380
+ @click.option(
1381
+ "--build-context",
1382
+ metavar="(str)",
1383
+ help="Path to the build context within the source code. Defaults to the "
1384
+ "root of the source code. Compatible only with -u.",
1385
+ )
1386
+ @click.option(
1387
+ "--job-name",
1388
+ "-J",
1389
+ metavar="(str)",
1390
+ default=None,
1391
+ hidden=True,
1392
+ help="Name for the job created if the -u,--uri flag is passed in.",
1393
+ )
1394
+ @click.option(
1395
+ "--name",
1396
+ envvar="WANDB_NAME",
1397
+ help="""Name of the run under which to launch the run. If not
1398
+ specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.""",
1399
+ )
1400
+ @click.option(
1401
+ "--entity",
1402
+ "-e",
1403
+ metavar="(str)",
1404
+ default=None,
1405
+ help="""Name of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder.
1406
+ If passed in, will override the entity value passed in using a config file.""",
1407
+ )
1408
+ @click.option(
1409
+ "--project",
1410
+ "-p",
1411
+ metavar="(str)",
1412
+ default=None,
1413
+ help="""Name of the target project which the new run will be sent to. Defaults to using the project name given by the source uri
1414
+ or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.""",
1415
+ )
1416
+ @click.option(
1417
+ "--resource",
1418
+ "-r",
1419
+ metavar="BACKEND",
1420
+ default=None,
1421
+ help="""Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'.
1422
+ This is now a required parameter if pushing to a queue with no resource configuration.
1423
+ If passed in, will override the resource value passed in using a config file.""",
1424
+ )
1425
+ @click.option(
1426
+ "--docker-image",
1427
+ "-d",
1428
+ default=None,
1429
+ metavar="DOCKER IMAGE",
1430
+ help="""Specific docker image you'd like to use. In the form name:tag.
1431
+ If passed in, will override the docker image value passed in using a config file.""",
1432
+ )
1433
+ @click.option(
1434
+ "--base-image",
1435
+ "-B",
1436
+ default=None,
1437
+ metavar="BASE IMAGE",
1438
+ help="""Docker image to run job code in. Incompatible with --docker-image.""",
1439
+ )
1440
+ @click.option(
1441
+ "--config",
1442
+ "-c",
1443
+ metavar="FILE",
1444
+ help="""Path to JSON file (must end in '.json') or JSON string which will be passed
1445
+ as a launch config. Dictation how the launched run will be configured.""",
1446
+ )
1447
+ @click.option(
1448
+ "--set-var",
1449
+ "-v",
1450
+ "cli_template_vars",
1451
+ default=None,
1452
+ multiple=True,
1453
+ help="""Set template variable values for queues with allow listing enabled,
1454
+ as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`""",
1455
+ )
1456
+ @click.option(
1457
+ "--queue",
1458
+ "-q",
1459
+ is_flag=False,
1460
+ flag_value="default",
1461
+ default=None,
1462
+ help="""Name of run queue to push to. If none, launches single run directly. If supplied without
1463
+ an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the
1464
+ project and entity supplied.""",
1465
+ )
1466
+ @click.option(
1467
+ "--async",
1468
+ "run_async",
1469
+ is_flag=True,
1470
+ help="""Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for
1471
+ the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be
1472
+ set on wandb launch-agent.""",
1473
+ )
1474
+ @click.option(
1475
+ "--resource-args",
1476
+ "-R",
1477
+ metavar="FILE",
1478
+ help="""Path to JSON file (must end in '.json') or JSON string which will be passed
1479
+ as resource args to the compute resource. The exact content which should be
1480
+ provided is different for each execution backend. See documentation for layout of this file.""",
1481
+ )
1482
+ @click.option(
1483
+ "--build",
1484
+ "-b",
1485
+ is_flag=True,
1486
+ hidden=True,
1487
+ help="Flag to build an associated job and push to queue as an image job.",
1488
+ )
1489
+ @click.option(
1490
+ "--repository",
1491
+ "-rg",
1492
+ is_flag=False,
1493
+ default=None,
1494
+ hidden=True,
1495
+ help="Name of a remote repository. Will be used to push a built image to.",
1496
+ )
1497
+ # TODO: this is only included for back compat. But we should remove this in the future
1498
+ @click.option(
1499
+ "--project-queue",
1500
+ "-pq",
1501
+ default=None,
1502
+ hidden=True,
1503
+ help="Name of the project containing the queue to push to. If none, defaults to entity level queues.",
1504
+ )
1505
+ @click.option(
1506
+ "--dockerfile",
1507
+ "-D",
1508
+ default=None,
1509
+ help="Path to the Dockerfile used to build the job, relative to the job's root",
1510
+ )
1511
+ @click.option(
1512
+ "--priority",
1513
+ "-P",
1514
+ default=None,
1515
+ type=click.Choice(["critical", "high", "medium", "low"]),
1516
+ help="""When --queue is passed, set the priority of the job. Launch jobs with higher priority
1517
+ are served first. The order, from highest to lowest priority, is: critical, high, medium, low""",
1518
+ )
1519
+ @display_error
1520
+ def launch(
1521
+ uri,
1522
+ job,
1523
+ entry_point,
1524
+ git_version,
1525
+ build_context,
1526
+ name,
1527
+ resource,
1528
+ entity,
1529
+ project,
1530
+ docker_image,
1531
+ base_image,
1532
+ config,
1533
+ cli_template_vars,
1534
+ queue,
1535
+ run_async,
1536
+ resource_args,
1537
+ build,
1538
+ repository,
1539
+ project_queue,
1540
+ dockerfile,
1541
+ priority,
1542
+ job_name,
1543
+ ):
1544
+ """Start a W&B run from the given URI.
1545
+
1546
+ The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a
1547
+ wandb URI the arguments used in the original run will be used by default. These
1548
+ arguments can be overridden using the args option, or specifying those arguments in
1549
+ the config's 'overrides' key, 'args' field as a list of strings.
1550
+
1551
+ Running `wandb launch [URI]` will launch the run directly. To add the run to a
1552
+ queue, run `wandb launch [URI] --queue [optional queuename]`.
1553
+ """
1554
+ logger.info(
1555
+ f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}==="
1556
+ )
1557
+ from wandb.sdk.launch._launch import _launch
1558
+ from wandb.sdk.launch.create_job import _create_job
1559
+ from wandb.sdk.launch.utils import _is_git_uri
1560
+
1561
+ api = _get_cling_api()
1562
+ wandb._sentry.configure_scope(process_context="launch_cli")
1563
+
1564
+ if run_async and queue is not None:
1565
+ raise LaunchError(
1566
+ "Cannot use both --async and --queue with wandb launch, see help for details."
1567
+ )
1568
+
1569
+ if queue and docker_image and not project:
1570
+ raise LaunchError(
1571
+ "Cannot use --queue and --docker together without a project. Please specify a project with --project or -p."
1572
+ )
1573
+
1574
+ if priority is not None and queue is None:
1575
+ raise LaunchError("--priority flag requires --queue to be set")
1576
+
1577
+ if resource_args is not None:
1578
+ resource_args = util.load_json_yaml_dict(resource_args)
1579
+ if resource_args is None:
1580
+ raise LaunchError("Invalid format for resource-args")
1581
+ else:
1582
+ resource_args = {}
1583
+
1584
+ if entry_point is not None:
1585
+ entry_point = shlex.split(entry_point)
1586
+
1587
+ if config is not None:
1588
+ config = util.load_json_yaml_dict(config)
1589
+ if config is None:
1590
+ raise LaunchError("Invalid format for config")
1591
+ else:
1592
+ config = {}
1593
+
1594
+ resource = resource or config.get("resource")
1595
+
1596
+ if build and queue is None:
1597
+ raise LaunchError("Build flag requires a queue to be set")
1598
+
1599
+ try:
1600
+ launch_utils.check_logged_in(api)
1601
+ except Exception:
1602
+ wandb.termerror(f"Error running job: {traceback.format_exc()}")
1603
+
1604
+ run_id = config.get("run_id")
1605
+
1606
+ # If URI was provided, we need to create a job from it.
1607
+ if uri:
1608
+ if entry_point is None:
1609
+ raise LaunchError(
1610
+ "Cannot provide a uri without an entry point. Please provide an "
1611
+ "entry point with --entry-point or -E."
1612
+ )
1613
+ if job is not None:
1614
+ raise LaunchError("Cannot provide both a uri and a job name.")
1615
+ job_type = (
1616
+ "git" if _is_git_uri(uri) else "code"
1617
+ ) # TODO: Add support for local URIs with git.
1618
+ if entity is None:
1619
+ entity = launch_utils.get_default_entity(api, config)
1620
+ artifact, _, _ = _create_job(
1621
+ api,
1622
+ job_type,
1623
+ uri,
1624
+ entrypoint=" ".join(entry_point),
1625
+ git_hash=git_version,
1626
+ name=job_name,
1627
+ project=project,
1628
+ base_image=base_image,
1629
+ build_context=build_context,
1630
+ dockerfile=dockerfile,
1631
+ entity=entity,
1632
+ )
1633
+ if artifact is None:
1634
+ raise LaunchError(f"Failed to create job from uri: {uri}")
1635
+ job = f"{entity}/{project}/{artifact.name}"
1636
+
1637
+ if dockerfile:
1638
+ if "overrides" in config:
1639
+ config["overrides"]["dockerfile"] = dockerfile
1640
+ else:
1641
+ config["overrides"] = {"dockerfile": dockerfile}
1642
+
1643
+ if priority is not None:
1644
+ priority_map = {
1645
+ "critical": 0,
1646
+ "high": 1,
1647
+ "medium": 2,
1648
+ "low": 3,
1649
+ }
1650
+ priority = priority_map[priority.lower()]
1651
+
1652
+ template_variables = None
1653
+ if cli_template_vars:
1654
+ if queue is None:
1655
+ raise LaunchError("'--set-var' flag requires queue to be set")
1656
+ if entity is None:
1657
+ entity = launch_utils.get_default_entity(api, config)
1658
+ public_api = PublicApi()
1659
+ runqueue = RunQueue(client=public_api.client, name=queue, entity=entity)
1660
+ template_variables = launch_utils.fetch_and_validate_template_variables(
1661
+ runqueue, cli_template_vars
1662
+ )
1663
+
1664
+ if queue is None:
1665
+ # direct launch
1666
+ try:
1667
+ run = asyncio.run(
1668
+ _launch(
1669
+ api,
1670
+ job,
1671
+ project=project,
1672
+ entity=entity,
1673
+ docker_image=docker_image,
1674
+ name=name,
1675
+ entry_point=entry_point,
1676
+ version=git_version,
1677
+ resource=resource,
1678
+ resource_args=resource_args,
1679
+ launch_config=config,
1680
+ synchronous=(not run_async),
1681
+ run_id=run_id,
1682
+ repository=repository,
1683
+ )
1684
+ )
1685
+ if asyncio.run(run.get_status()).state in [
1686
+ "failed",
1687
+ "stopped",
1688
+ "preempted",
1689
+ ]:
1690
+ wandb.termerror("Launched run exited with non-zero status")
1691
+ sys.exit(1)
1692
+ except LaunchError as e:
1693
+ logger.error("=== %s ===", e)
1694
+ wandb._sentry.exception(e)
1695
+ sys.exit(e)
1696
+ except ExecutionError as e:
1697
+ logger.error("=== %s ===", e)
1698
+ wandb._sentry.exception(e)
1699
+ sys.exit(e)
1700
+ except asyncio.CancelledError:
1701
+ sys.exit(0)
1702
+ else:
1703
+ try:
1704
+ _launch_add(
1705
+ api,
1706
+ job,
1707
+ config,
1708
+ template_variables,
1709
+ project,
1710
+ entity,
1711
+ queue,
1712
+ resource,
1713
+ entry_point,
1714
+ name,
1715
+ git_version,
1716
+ docker_image,
1717
+ project_queue,
1718
+ resource_args,
1719
+ build=build,
1720
+ run_id=run_id,
1721
+ repository=repository,
1722
+ priority=priority,
1723
+ )
1724
+
1725
+ except Exception as e:
1726
+ wandb._sentry.exception(e)
1727
+ raise e
1728
+
1729
+
1730
+ @cli.command(
1731
+ context_settings=CONTEXT,
1732
+ help="Run a W&B launch agent.",
1733
+ )
1734
+ @click.pass_context
1735
+ @click.option(
1736
+ "--queue",
1737
+ "-q",
1738
+ "queues",
1739
+ default=None,
1740
+ multiple=True,
1741
+ metavar="<queue(s)>",
1742
+ help="The name of a queue for the agent to watch. Multiple -q flags supported.",
1743
+ )
1744
+ @click.option(
1745
+ "--entity",
1746
+ "-e",
1747
+ default=None,
1748
+ help="The entity to use. Defaults to current logged-in user",
1749
+ )
1750
+ @click.option(
1751
+ "--log-file",
1752
+ "-l",
1753
+ default=None,
1754
+ help=(
1755
+ "Destination for internal agent logs. Use - for stdout. "
1756
+ "By default all agents logs will go to debug.log in your wandb/ "
1757
+ "subdirectory or WANDB_DIR if set."
1758
+ ),
1759
+ )
1760
+ @click.option(
1761
+ "--max-jobs",
1762
+ "-j",
1763
+ default=None,
1764
+ help="The maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limit",
1765
+ )
1766
+ @click.option(
1767
+ "--config", "-c", default=None, help="path to the agent config yaml to use"
1768
+ )
1769
+ @click.option(
1770
+ "--url",
1771
+ "-u",
1772
+ default=None,
1773
+ hidden=True,
1774
+ help="a wandb client registration URL, this is generated in the UI",
1775
+ )
1776
+ @click.option("--verbose", "-v", count=True, help="Display verbose output")
1777
+ @display_error
1778
+ def launch_agent(
1779
+ ctx,
1780
+ entity=None,
1781
+ queues=None,
1782
+ max_jobs=None,
1783
+ config=None,
1784
+ url=None,
1785
+ log_file=None,
1786
+ verbose=0,
1787
+ ):
1788
+ logger.info(
1789
+ f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ==="
1790
+ )
1791
+ if url is not None:
1792
+ raise LaunchError(
1793
+ "--url is not supported in this version, upgrade with: pip install -u wandb"
1794
+ )
1795
+
1796
+ import wandb.sdk.launch._launch as _launch
1797
+
1798
+ if log_file is not None:
1799
+ _launch.set_launch_logfile(log_file)
1800
+
1801
+ api = _get_cling_api()
1802
+ wandb._sentry.configure_scope(process_context="launch_agent")
1803
+ agent_config, api = _launch.resolve_agent_config(
1804
+ entity, max_jobs, queues, config, verbose
1805
+ )
1806
+
1807
+ if len(agent_config.get("queues")) == 0:
1808
+ raise LaunchError(
1809
+ "To launch an agent please specify a queue or a list of queues in the configuration file or cli."
1810
+ )
1811
+
1812
+ launch_utils.check_logged_in(api)
1813
+
1814
+ wandb.termlog("Starting launch agent ✨")
1815
+ try:
1816
+ _launch.create_and_run_agent(api, agent_config)
1817
+ except Exception as e:
1818
+ wandb._sentry.exception(e)
1819
+ raise e
1820
+
1821
+
1822
+ @cli.command(context_settings=CONTEXT, help="Run the W&B agent")
1823
+ @click.pass_context
1824
+ @click.option(
1825
+ "--project",
1826
+ "-p",
1827
+ default=None,
1828
+ help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.""",
1829
+ )
1830
+ @click.option(
1831
+ "--entity",
1832
+ "-e",
1833
+ default=None,
1834
+ help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
1835
+ )
1836
+ @click.option(
1837
+ "--count", default=None, type=int, help="The max number of runs for this agent."
1838
+ )
1839
+ @click.argument("sweep_id")
1840
+ @display_error
1841
+ def agent(ctx, project, entity, count, sweep_id):
1842
+ api = _get_cling_api()
1843
+ if not api.is_authenticated:
1844
+ wandb.termlog("Login to W&B to use the sweep agent feature")
1845
+ ctx.invoke(login, no_offline=True)
1846
+ api = _get_cling_api(reset=True)
1847
+
1848
+ wandb.termlog("Starting wandb agent 🕵️")
1849
+ wandb_agent.agent(sweep_id, entity=entity, project=project, count=count)
1850
+
1851
+ # you can send local commands like so:
1852
+ # agent_api.command({'type': 'run', 'program': 'train.py',
1853
+ # 'args': ['--max_epochs=10']})
1854
+
1855
+
1856
+ @cli.command(
1857
+ context_settings=RUN_CONTEXT, help="Run a W&B launch sweep scheduler (Experimental)"
1858
+ )
1859
+ @click.pass_context
1860
+ @click.argument("sweep_id")
1861
+ @display_error
1862
+ def scheduler(
1863
+ ctx,
1864
+ sweep_id,
1865
+ ):
1866
+ api = InternalApi()
1867
+ if not api.is_authenticated:
1868
+ wandb.termlog("Login to W&B to use the sweep scheduler feature")
1869
+ ctx.invoke(login, no_offline=True)
1870
+ api = InternalApi(reset=True)
1871
+
1872
+ wandb._sentry.configure_scope(process_context="sweep_scheduler")
1873
+ wandb.termlog("Starting a Launch Scheduler 🚀")
1874
+ from wandb.sdk.launch.sweeps import load_scheduler
1875
+
1876
+ # TODO(gst): remove this monstrosity
1877
+ # Future-proofing hack to pull any kwargs that get passed in through the CLI
1878
+ kwargs = {}
1879
+ for i, _arg in enumerate(ctx.args):
1880
+ if isinstance(_arg, str) and _arg.startswith("--"):
1881
+ # convert input kwargs from hyphens to underscores
1882
+ _key = _arg[2:].replace("-", "_")
1883
+ _args = ctx.args[i + 1]
1884
+ if str.isdigit(_args):
1885
+ _args = int(_args)
1886
+ kwargs[_key] = _args
1887
+ try:
1888
+ sweep_type = kwargs.get("sweep_type", "wandb")
1889
+ _scheduler = load_scheduler(scheduler_type=sweep_type)(
1890
+ api,
1891
+ sweep_id=sweep_id,
1892
+ **kwargs,
1893
+ )
1894
+ _scheduler.start()
1895
+ except Exception as e:
1896
+ wandb._sentry.exception(e)
1897
+ raise e
1898
+
1899
+
1900
+ @cli.group(help="Commands for managing and viewing W&B jobs")
1901
+ def job() -> None:
1902
+ pass
1903
+
1904
+
1905
+ @job.command("list", help="List jobs in a project")
1906
+ @click.option(
1907
+ "--project",
1908
+ "-p",
1909
+ envvar=env.PROJECT,
1910
+ help="The project you want to list jobs from.",
1911
+ )
1912
+ @click.option(
1913
+ "--entity",
1914
+ "-e",
1915
+ default="models",
1916
+ envvar=env.ENTITY,
1917
+ help="The entity the jobs belong to",
1918
+ )
1919
+ def _list(project, entity):
1920
+ wandb.termlog(f"Listing jobs in {entity}/{project}")
1921
+ public_api = PublicApi()
1922
+ try:
1923
+ jobs = public_api.list_jobs(entity=entity, project=project)
1924
+ except wandb.errors.CommError as e:
1925
+ wandb.termerror(f"{e}")
1926
+ return
1927
+
1928
+ if len(jobs) == 0:
1929
+ wandb.termlog("No jobs found")
1930
+ return
1931
+
1932
+ for job in jobs:
1933
+ aliases = []
1934
+ if len(job["edges"]) == 0:
1935
+ # deleted?
1936
+ continue
1937
+
1938
+ name = job["edges"][0]["node"]["artifactSequence"]["name"]
1939
+ for version in job["edges"]:
1940
+ aliases += [x["alias"] for x in version["node"]["aliases"]]
1941
+
1942
+ # only list the most recent 10 job versions
1943
+ aliases_str = ",".join(aliases[::-1])
1944
+ wandb.termlog(f"{name} -- versions ({len(aliases)}): {aliases_str}")
1945
+
1946
+
1947
+ @job.command(
1948
+ help="Describe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-version"
1949
+ )
1950
+ @click.argument("job")
1951
+ def describe(job):
1952
+ public_api = PublicApi()
1953
+ try:
1954
+ job = public_api.job(name=job)
1955
+ except wandb.errors.CommError as e:
1956
+ wandb.termerror(f"{e}")
1957
+ return
1958
+
1959
+ for key in job._job_info:
1960
+ if key.startswith("_"):
1961
+ continue
1962
+ wandb.termlog(f"{key}: {job._job_info[key]}")
1963
+
1964
+
1965
+ @job.command(
1966
+ no_args_is_help=True,
1967
+ )
1968
+ @click.option(
1969
+ "--project",
1970
+ "-p",
1971
+ envvar=env.PROJECT,
1972
+ help="The project you want to list jobs from.",
1973
+ )
1974
+ @click.option(
1975
+ "--entity",
1976
+ "-e",
1977
+ envvar=env.ENTITY,
1978
+ help="The entity the jobs belong to",
1979
+ )
1980
+ @click.option(
1981
+ "--name",
1982
+ "-n",
1983
+ help="Name for the job",
1984
+ )
1985
+ @click.option(
1986
+ "--description",
1987
+ "-d",
1988
+ help="Description for the job",
1989
+ )
1990
+ @click.option(
1991
+ "--alias",
1992
+ "-a",
1993
+ "aliases",
1994
+ help="Alias for the job",
1995
+ multiple=True,
1996
+ default=tuple(),
1997
+ )
1998
+ @click.option(
1999
+ "--entry-point",
2000
+ "-E",
2001
+ "entrypoint",
2002
+ help="Entrypoint to the script, including an executable and an entrypoint "
2003
+ "file. Required for code or repo jobs. If --build-context is provided, "
2004
+ "paths in the entrypoint command will be relative to the build context.",
2005
+ )
2006
+ @click.option(
2007
+ "--git-hash",
2008
+ "-g",
2009
+ "git_hash",
2010
+ type=str,
2011
+ help="Commit reference to use as the source for git jobs",
2012
+ )
2013
+ @click.option(
2014
+ "--runtime",
2015
+ "-r",
2016
+ type=str,
2017
+ help="Python runtime to execute the job",
2018
+ )
2019
+ @click.option(
2020
+ "--build-context",
2021
+ "-b",
2022
+ type=str,
2023
+ help="Path to the build context from the root of the job source code. If "
2024
+ "provided, this is used as the base path for the Dockerfile and entrypoint.",
2025
+ )
2026
+ @click.option(
2027
+ "--base-image",
2028
+ "-B",
2029
+ type=str,
2030
+ help="Base image to use for the job. Incompatible with image jobs.",
2031
+ )
2032
+ @click.option(
2033
+ "--dockerfile",
2034
+ "-D",
2035
+ type=str,
2036
+ help="Path to the Dockerfile for the job. If --build-context is provided, "
2037
+ "the Dockerfile path will be relative to the build context.",
2038
+ )
2039
+ @click.argument(
2040
+ "job_type",
2041
+ type=click.Choice(("git", "code", "image")),
2042
+ )
2043
+ @click.argument("path")
2044
+ def create(
2045
+ path,
2046
+ project,
2047
+ entity,
2048
+ name,
2049
+ job_type,
2050
+ description,
2051
+ aliases,
2052
+ entrypoint,
2053
+ git_hash,
2054
+ runtime,
2055
+ build_context,
2056
+ base_image,
2057
+ dockerfile,
2058
+ ):
2059
+ """Create a job from a source, without a wandb run.
2060
+
2061
+ Jobs can be of three types, git, code, or image.
2062
+
2063
+ git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable.
2064
+ code: A code path, containing a requirements.txt file.
2065
+ image: A docker image.
2066
+ """
2067
+ from wandb.sdk.launch.create_job import _create_job
2068
+
2069
+ api = _get_cling_api()
2070
+ wandb._sentry.configure_scope(process_context="job_create")
2071
+
2072
+ entity = entity or os.getenv("WANDB_ENTITY") or api.default_entity
2073
+ if not entity:
2074
+ wandb.termerror("No entity provided, use --entity or set WANDB_ENTITY")
2075
+ return
2076
+
2077
+ project = project or os.getenv("WANDB_PROJECT")
2078
+ if not project:
2079
+ wandb.termerror("No project provided, use --project or set WANDB_PROJECT")
2080
+ return
2081
+
2082
+ if entrypoint is None and job_type in ["git", "code"]:
2083
+ wandb.termwarn(
2084
+ f"No entrypoint provided for {job_type} job, defaulting to main.py"
2085
+ )
2086
+ entrypoint = "main.py"
2087
+
2088
+ if job_type == "image" and base_image:
2089
+ wandb.termerror("Cannot provide --base-image/-B for an `image` job")
2090
+ return
2091
+
2092
+ artifact, action, aliases = _create_job(
2093
+ api=api,
2094
+ path=path,
2095
+ entity=entity,
2096
+ project=project,
2097
+ name=name,
2098
+ job_type=job_type,
2099
+ description=description,
2100
+ aliases=list(aliases),
2101
+ entrypoint=entrypoint,
2102
+ git_hash=git_hash,
2103
+ runtime=runtime,
2104
+ build_context=build_context,
2105
+ base_image=base_image,
2106
+ dockerfile=dockerfile,
2107
+ )
2108
+ if not artifact:
2109
+ wandb.termerror("Job creation failed")
2110
+ return
2111
+
2112
+ artifact_path = f"{entity}/{project}/{artifact.name}"
2113
+ msg = f"{action} job: {click.style(artifact_path, fg='yellow')}"
2114
+ if len(aliases) == 1:
2115
+ alias_str = click.style(aliases[0], fg="yellow")
2116
+ msg += f", with alias: {alias_str}"
2117
+ elif len(aliases) > 1:
2118
+ alias_str = click.style(", ".join(aliases), fg="yellow")
2119
+ msg += f", with aliases: {alias_str}"
2120
+
2121
+ wandb.termlog(msg)
2122
+ web_url = util.app_url(api.settings().get("base_url"))
2123
+ url = click.style(f"{web_url}/{entity}/{project}/jobs", underline=True)
2124
+ wandb.termlog(f"View all jobs in project '{project}' here: {url}\n")
2125
+
2126
+
2127
+ @cli.command(context_settings=CONTEXT, help="Run the W&B local sweep controller")
2128
+ @click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
2129
+ @click.argument("sweep_id")
2130
+ @display_error
2131
+ def controller(verbose, sweep_id):
2132
+ click.echo("Starting wandb controller...")
2133
+ from wandb import controller as wandb_controller
2134
+
2135
+ tuner = wandb_controller(sweep_id)
2136
+ tuner.run(verbose=verbose)
2137
+
2138
+
2139
+ @cli.command(context_settings=RUN_CONTEXT, name="docker-run")
2140
+ @click.pass_context
2141
+ @click.argument("docker_run_args", nargs=-1)
2142
+ def docker_run(ctx, docker_run_args):
2143
+ """Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables.
2144
+
2145
+ This will also set the runtime to nvidia if the nvidia-docker executable is present
2146
+ on the system and --runtime wasn't set.
2147
+
2148
+ See `docker run --help` for more details.
2149
+ """
2150
+ api = InternalApi()
2151
+ args = list(docker_run_args)
2152
+ if len(args) > 0 and args[0] == "run":
2153
+ args.pop(0)
2154
+ if len([a for a in args if a.startswith("--runtime")]) == 0 and find_executable(
2155
+ "nvidia-docker"
2156
+ ):
2157
+ args = ["--runtime", "nvidia"] + args
2158
+ # TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases
2159
+ # where this won't work
2160
+ image = util.image_from_docker_args(args)
2161
+ resolved_image = None
2162
+ if image:
2163
+ resolved_image = wandb.docker.image_id(image)
2164
+ if resolved_image:
2165
+ args = ["-e", "WANDB_DOCKER={}".format(resolved_image)] + args
2166
+ else:
2167
+ wandb.termlog(
2168
+ "Couldn't detect image argument, running command without the WANDB_DOCKER env variable"
2169
+ )
2170
+ if api.api_key:
2171
+ args = ["-e", "WANDB_API_KEY={}".format(api.api_key)] + args
2172
+ else:
2173
+ wandb.termlog(
2174
+ "Not logged in, run `wandb login` from the host machine to enable result logging"
2175
+ )
2176
+ subprocess.call(["docker", "run"] + args)
2177
+
2178
+
2179
+ @cli.command(context_settings=RUN_CONTEXT)
2180
+ @click.pass_context
2181
+ @click.argument("docker_run_args", nargs=-1)
2182
+ @click.argument("docker_image", required=False)
2183
+ @click.option(
2184
+ "--nvidia/--no-nvidia",
2185
+ default=find_executable("nvidia-docker") is not None,
2186
+ help="Use the nvidia runtime, defaults to nvidia if nvidia-docker is present",
2187
+ )
2188
+ @click.option(
2189
+ "--digest", is_flag=True, default=False, help="Output the image digest and exit"
2190
+ )
2191
+ @click.option(
2192
+ "--jupyter/--no-jupyter", default=False, help="Run jupyter lab in the container"
2193
+ )
2194
+ @click.option(
2195
+ "--dir", default="/app", help="Which directory to mount the code in the container"
2196
+ )
2197
+ @click.option("--no-dir", is_flag=True, help="Don't mount the current directory")
2198
+ @click.option(
2199
+ "--shell", default="/bin/bash", help="The shell to start the container with"
2200
+ )
2201
+ @click.option("--port", default="8888", help="The host port to bind jupyter on")
2202
+ @click.option("--cmd", help="The command to run in the container")
2203
+ @click.option(
2204
+ "--no-tty", is_flag=True, default=False, help="Run the command without a tty"
2205
+ )
2206
+ @display_error
2207
+ def docker(
2208
+ ctx,
2209
+ docker_run_args,
2210
+ docker_image,
2211
+ nvidia,
2212
+ digest,
2213
+ jupyter,
2214
+ dir,
2215
+ no_dir,
2216
+ shell,
2217
+ port,
2218
+ cmd,
2219
+ no_tty,
2220
+ ):
2221
+ """Run your code in a docker container.
2222
+
2223
+ W&B docker lets you run your code in a docker image ensuring wandb is configured. It
2224
+ adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and
2225
+ mounts the current directory in /app by default. You can pass additional args which
2226
+ will be added to `docker run` before the image name is declared, we'll choose a
2227
+ default image for you if one isn't passed:
2228
+
2229
+ ```sh
2230
+ wandb docker -v /mnt/dataset:/app/data
2231
+ wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter
2232
+ wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5"
2233
+ ```
2234
+
2235
+ By default, we override the entrypoint to check for the existence of wandb and
2236
+ install it if not present. If you pass the --jupyter flag we will ensure jupyter is
2237
+ installed and start jupyter lab on port 8888. If we detect nvidia-docker on your
2238
+ system we will use the nvidia runtime. If you just want wandb to set environment
2239
+ variable to an existing docker run command, see the wandb docker-run command.
2240
+ """
2241
+ api = InternalApi()
2242
+ if not find_executable("docker"):
2243
+ raise ClickException("Docker not installed, install it from https://docker.com")
2244
+ args = list(docker_run_args)
2245
+ image = docker_image or ""
2246
+ # remove run for users used to nvidia-docker
2247
+ if len(args) > 0 and args[0] == "run":
2248
+ args.pop(0)
2249
+ if image == "" and len(args) > 0:
2250
+ image = args.pop(0)
2251
+ # If the user adds docker args without specifying an image (should be rare)
2252
+ if not util.docker_image_regex(image.split("@")[0]):
2253
+ if image:
2254
+ args = args + [image]
2255
+ image = wandb.docker.default_image(gpu=nvidia)
2256
+ subprocess.call(["docker", "pull", image])
2257
+ _, repo_name, tag = wandb.docker.parse(image)
2258
+
2259
+ resolved_image = wandb.docker.image_id(image)
2260
+ if resolved_image is None:
2261
+ raise ClickException(
2262
+ "Couldn't find image locally or in a registry, try running `docker pull {}`".format(
2263
+ image
2264
+ )
2265
+ )
2266
+ if digest:
2267
+ sys.stdout.write(resolved_image)
2268
+ exit(0)
2269
+
2270
+ existing = wandb.docker.shell(
2271
+ ["ps", "-f", "ancestor={}".format(resolved_image), "-q"]
2272
+ )
2273
+ if existing:
2274
+ if click.confirm(
2275
+ "Found running container with the same image, do you want to attach?"
2276
+ ):
2277
+ subprocess.call(["docker", "attach", existing.split("\n")[0]])
2278
+ exit(0)
2279
+ cwd = os.getcwd()
2280
+ command = [
2281
+ "docker",
2282
+ "run",
2283
+ "-e",
2284
+ "LANG=C.UTF-8",
2285
+ "-e",
2286
+ "WANDB_DOCKER={}".format(resolved_image),
2287
+ "--ipc=host",
2288
+ "-v",
2289
+ wandb.docker.entrypoint + ":/wandb-entrypoint.sh",
2290
+ "--entrypoint",
2291
+ "/wandb-entrypoint.sh",
2292
+ ]
2293
+ if nvidia:
2294
+ command.extend(["--runtime", "nvidia"])
2295
+ if not no_dir:
2296
+ # TODO: We should default to the working directory if defined
2297
+ command.extend(["-v", cwd + ":" + dir, "-w", dir])
2298
+ if api.api_key:
2299
+ command.extend(["-e", "WANDB_API_KEY={}".format(api.api_key)])
2300
+ else:
2301
+ wandb.termlog(
2302
+ "Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics"
2303
+ )
2304
+ if jupyter:
2305
+ command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"])
2306
+ no_tty = True
2307
+ cmd = "jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir {}".format(
2308
+ dir
2309
+ )
2310
+ command.extend(args)
2311
+ if no_tty:
2312
+ command.extend([image, shell, "-c", cmd])
2313
+ else:
2314
+ if cmd:
2315
+ command.extend(["-e", "WANDB_COMMAND={}".format(cmd)])
2316
+ command.extend(["-it", image, shell])
2317
+ wandb.termlog("Launching docker container \U0001f6a2")
2318
+ subprocess.call(command)
2319
+
2320
+
2321
+ @cli.command(
2322
+ context_settings=RUN_CONTEXT,
2323
+ help="Start a local W&B container (deprecated, see wandb server --help)",
2324
+ hidden=True,
2325
+ )
2326
+ @click.pass_context
2327
+ @click.option("--port", "-p", default="8080", help="The host port to bind W&B local on")
2328
+ @click.option(
2329
+ "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
2330
+ )
2331
+ @click.option(
2332
+ "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
2333
+ )
2334
+ @click.option(
2335
+ "--upgrade", is_flag=True, default=False, help="Upgrade to the most recent version"
2336
+ )
2337
+ @click.option(
2338
+ "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
2339
+ )
2340
+ @display_error
2341
+ def local(ctx, *args, **kwargs):
2342
+ wandb.termwarn("`wandb local` has been replaced with `wandb server start`.")
2343
+ ctx.invoke(start, *args, **kwargs)
2344
+
2345
+
2346
+ @cli.group(help="Commands for operating a local W&B server")
2347
+ def server():
2348
+ pass
2349
+
2350
+
2351
+ @server.command(context_settings=RUN_CONTEXT, help="Start a local W&B server")
2352
+ @click.pass_context
2353
+ @click.option(
2354
+ "--port", "-p", default="8080", help="The host port to bind W&B server on"
2355
+ )
2356
+ @click.option(
2357
+ "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
2358
+ )
2359
+ @click.option(
2360
+ "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
2361
+ )
2362
+ @click.option(
2363
+ "--upgrade",
2364
+ is_flag=True,
2365
+ default=False,
2366
+ help="Upgrade to the most recent version",
2367
+ hidden=True,
2368
+ )
2369
+ @click.option(
2370
+ "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
2371
+ )
2372
+ @display_error
2373
+ def start(ctx, port, env, daemon, upgrade, edge):
2374
+ api = InternalApi()
2375
+ if not find_executable("docker"):
2376
+ raise ClickException("Docker not installed, install it from https://docker.com")
2377
+ local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1]
2378
+ registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split(
2379
+ "wandb/local"
2380
+ )[-1]
2381
+ if local_image_sha != registry_image_sha:
2382
+ if upgrade:
2383
+ subprocess.call(["docker", "pull", "wandb/local"])
2384
+ else:
2385
+ wandb.termlog(
2386
+ "A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`"
2387
+ )
2388
+ running = subprocess.check_output(
2389
+ ["docker", "ps", "--filter", "name=wandb-local", "--format", "{{.ID}}"]
2390
+ )
2391
+ if running != b"":
2392
+ if upgrade:
2393
+ subprocess.call(["docker", "stop", "wandb-local"])
2394
+ else:
2395
+ wandb.termerror(
2396
+ "A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance"
2397
+ )
2398
+ exit(1)
2399
+ image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local"
2400
+ username = getpass.getuser()
2401
+ env_vars = ["-e", "LOCAL_USERNAME={}".format(username)]
2402
+ for e in env:
2403
+ env_vars.append("-e")
2404
+ env_vars.append(e)
2405
+ command = [
2406
+ "docker",
2407
+ "run",
2408
+ "--rm",
2409
+ "-v",
2410
+ "wandb:/vol",
2411
+ "-p",
2412
+ port + ":8080",
2413
+ "--name",
2414
+ "wandb-local",
2415
+ ] + env_vars
2416
+ host = f"http://localhost:{port}"
2417
+ api.set_setting("base_url", host, globally=True, persist=True)
2418
+ if daemon:
2419
+ command += ["-d"]
2420
+ command += [image]
2421
+
2422
+ # DEVNULL is only in py3
2423
+ try:
2424
+ from subprocess import DEVNULL
2425
+ except ImportError:
2426
+ DEVNULL = open(os.devnull, "wb") # noqa: N806
2427
+ code = subprocess.call(command, stdout=DEVNULL)
2428
+ if daemon:
2429
+ if code != 0:
2430
+ wandb.termerror(
2431
+ "Failed to launch the W&B server container, see the above error."
2432
+ )
2433
+ exit(1)
2434
+ else:
2435
+ wandb.termlog(
2436
+ "W&B server started at http://localhost:{} \U0001f680".format(port)
2437
+ )
2438
+ wandb.termlog("You can stop the server by running `wandb server stop`")
2439
+ if not api.api_key:
2440
+ # Let the server start before potentially launching a browser
2441
+ time.sleep(2)
2442
+ ctx.invoke(login, host=host)
2443
+
2444
+
2445
+ @server.command(context_settings=RUN_CONTEXT, help="Stop a local W&B server")
2446
+ def stop():
2447
+ if not find_executable("docker"):
2448
+ raise ClickException("Docker not installed, install it from https://docker.com")
2449
+ subprocess.call(["docker", "stop", "wandb-local"])
2450
+
2451
+
2452
+ @cli.group(help="Commands for interacting with artifacts")
2453
+ def artifact():
2454
+ pass
2455
+
2456
+
2457
+ @artifact.command(context_settings=CONTEXT, help="Upload an artifact to wandb")
2458
+ @click.argument("path")
2459
+ @click.option(
2460
+ "--name", "-n", help="The name of the artifact to push: project/artifact_name"
2461
+ )
2462
+ @click.option("--description", "-d", help="A description of this artifact")
2463
+ @click.option("--type", "-t", default="dataset", help="The type of the artifact")
2464
+ @click.option(
2465
+ "--alias",
2466
+ "-a",
2467
+ default=["latest"],
2468
+ multiple=True,
2469
+ help="An alias to apply to this artifact",
2470
+ )
2471
+ @click.option("--id", "run_id", help="The run you want to upload to.")
2472
+ @click.option(
2473
+ "--resume",
2474
+ is_flag=True,
2475
+ default=None,
2476
+ help="Resume the last run from your current directory.",
2477
+ )
2478
+ @click.option(
2479
+ "--skip_cache",
2480
+ is_flag=True,
2481
+ default=False,
2482
+ help="Skip caching while uploading artifact files.",
2483
+ )
2484
+ @click.option(
2485
+ "--policy",
2486
+ default="mutable",
2487
+ type=click.Choice(["mutable", "immutable"]),
2488
+ help="Set the storage policy while uploading artifact files.",
2489
+ )
2490
+ @display_error
2491
+ def put(
2492
+ path,
2493
+ name,
2494
+ description,
2495
+ type,
2496
+ alias,
2497
+ run_id,
2498
+ resume,
2499
+ skip_cache,
2500
+ policy,
2501
+ ):
2502
+ if name is None:
2503
+ name = os.path.basename(path)
2504
+ public_api = PublicApi()
2505
+ entity, project, artifact_name = public_api._parse_artifact_path(name)
2506
+ if project is None:
2507
+ project = click.prompt("Enter the name of the project you want to use")
2508
+ # TODO: settings nightmare...
2509
+ api = InternalApi()
2510
+ api.set_setting("entity", entity)
2511
+ api.set_setting("project", project)
2512
+ artifact = wandb.Artifact(name=artifact_name, type=type, description=description)
2513
+ artifact_path = f"{entity}/{project}/{artifact_name}:{alias[0]}"
2514
+ if os.path.isdir(path):
2515
+ wandb.termlog(f'Uploading directory {path} to: "{artifact_path}" ({type})')
2516
+ artifact.add_dir(path, skip_cache=skip_cache, policy=policy)
2517
+ elif os.path.isfile(path):
2518
+ wandb.termlog(f'Uploading file {path} to: "{artifact_path}" ({type})')
2519
+ artifact.add_file(path, skip_cache=skip_cache, policy=policy)
2520
+ elif "://" in path:
2521
+ wandb.termlog(
2522
+ f'Logging reference artifact from {path} to: "{artifact_path}" ({type})'
2523
+ )
2524
+ artifact.add_reference(path)
2525
+ else:
2526
+ raise ClickException("Path argument must be a file or directory")
2527
+
2528
+ with wandb.init(
2529
+ entity=entity,
2530
+ project=project,
2531
+ config={"path": path},
2532
+ job_type="cli_put",
2533
+ id=run_id,
2534
+ resume=resume,
2535
+ ) as run:
2536
+ run.log_artifact(artifact, aliases=alias)
2537
+ artifact.wait()
2538
+
2539
+ wandb.termlog(
2540
+ "Artifact uploaded, use this artifact in a run by adding:\n", prefix=False
2541
+ )
2542
+ wandb.termlog(
2543
+ f' artifact = run.use_artifact("{artifact.source_qualified_name}")\n',
2544
+ prefix=False,
2545
+ )
2546
+
2547
+
2548
+ @artifact.command(context_settings=CONTEXT, help="Download an artifact from wandb")
2549
+ @click.argument("path")
2550
+ @click.option("--root", help="The directory you want to download the artifact to")
2551
+ @click.option("--type", help="The type of artifact you are downloading")
2552
+ @display_error
2553
+ def get(path, root, type):
2554
+ public_api = PublicApi()
2555
+ entity, project, artifact_name = public_api._parse_artifact_path(path)
2556
+ if project is None:
2557
+ project = click.prompt("Enter the name of the project you want to use")
2558
+
2559
+ try:
2560
+ artifact_parts = artifact_name.split(":")
2561
+ if len(artifact_parts) > 1:
2562
+ version = artifact_parts[1]
2563
+ artifact_name = artifact_parts[0]
2564
+ else:
2565
+ version = "latest"
2566
+ full_path = f"{entity}/{project}/{artifact_name}:{version}"
2567
+ wandb.termlog(
2568
+ "Downloading {type} artifact {full_path}".format(
2569
+ type=type or "dataset", full_path=full_path
2570
+ )
2571
+ )
2572
+ artifact = public_api.artifact(full_path, type=type)
2573
+ path = artifact.download(root=root)
2574
+ wandb.termlog("Artifact downloaded to {}".format(path))
2575
+ except ValueError:
2576
+ raise ClickException("Unable to download artifact")
2577
+
2578
+
2579
+ @artifact.command(
2580
+ context_settings=CONTEXT, help="List all artifacts in a wandb project"
2581
+ )
2582
+ @click.argument("path")
2583
+ @click.option("--type", "-t", help="The type of artifacts to list")
2584
+ @display_error
2585
+ def ls(path, type):
2586
+ public_api = PublicApi()
2587
+ if type is not None:
2588
+ types = [public_api.artifact_type(type, path)]
2589
+ else:
2590
+ types = public_api.artifact_types(path)
2591
+
2592
+ for kind in types:
2593
+ for collection in kind.collections():
2594
+ versions = public_api.artifact_versions(
2595
+ kind.type,
2596
+ "/".join([kind.entity, kind.project, collection.name]),
2597
+ per_page=1,
2598
+ )
2599
+ latest = next(versions)
2600
+ print(
2601
+ "{:<15s}{:<15s}{:>15s} {:<20s}".format(
2602
+ kind.type,
2603
+ latest.updated_at,
2604
+ util.to_human_size(latest.size),
2605
+ latest.name,
2606
+ )
2607
+ )
2608
+
2609
+
2610
+ @artifact.group(help="Commands for interacting with the artifact cache")
2611
+ def cache():
2612
+ pass
2613
+
2614
+
2615
+ @cache.command(
2616
+ context_settings=CONTEXT,
2617
+ help="Clean up less frequently used files from the artifacts cache",
2618
+ )
2619
+ @click.argument("target_size")
2620
+ @click.option("--remove-temp/--no-remove-temp", default=False, help="Remove temp files")
2621
+ @display_error
2622
+ def cleanup(target_size, remove_temp):
2623
+ target_size = util.from_human_size(target_size)
2624
+ cache = get_artifact_file_cache()
2625
+ reclaimed_bytes = cache.cleanup(target_size, remove_temp)
2626
+ print(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space")
2627
+
2628
+
2629
+ @cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases")
2630
+ @click.argument("run", envvar=env.RUN_ID)
2631
+ @click.option(
2632
+ "--project", "-p", envvar=env.PROJECT, help="The project you want to download."
2633
+ )
2634
+ @click.option(
2635
+ "--entity",
2636
+ "-e",
2637
+ default="models",
2638
+ envvar=env.ENTITY,
2639
+ help="The entity to scope the listing to.",
2640
+ )
2641
+ @display_error
2642
+ def pull(run, project, entity):
2643
+ api = InternalApi()
2644
+ project, run = api.parse_slug(run, project=project)
2645
+ urls = api.download_urls(project, run=run, entity=entity)
2646
+ if len(urls) == 0:
2647
+ raise ClickException("Run has no files")
2648
+ click.echo(f"Downloading: {click.style(project, bold=True)}/{run}")
2649
+
2650
+ for name in urls:
2651
+ if api.file_current(name, urls[name]["md5"]):
2652
+ click.echo("File {} is up to date".format(name))
2653
+ else:
2654
+ length, response = api.download_file(urls[name]["url"])
2655
+ # TODO: I had to add this because some versions in CI broke click.progressbar
2656
+ sys.stdout.write("File {}\r".format(name))
2657
+ dirname = os.path.dirname(name)
2658
+ if dirname != "":
2659
+ filesystem.mkdir_exists_ok(dirname)
2660
+ with click.progressbar(
2661
+ length=length,
2662
+ label="File {}".format(name),
2663
+ fill_char=click.style("&", fg="green"),
2664
+ ) as bar:
2665
+ with open(name, "wb") as f:
2666
+ for data in response.iter_content(chunk_size=4096):
2667
+ f.write(data)
2668
+ bar.update(len(data))
2669
+
2670
+
2671
+ @cli.command(
2672
+ context_settings=CONTEXT, help="Restore code, config and docker state for a run"
2673
+ )
2674
+ @click.pass_context
2675
+ @click.argument("run", envvar=env.RUN_ID)
2676
+ @click.option("--no-git", is_flag=True, default=False, help="Don't restore git state")
2677
+ @click.option(
2678
+ "--branch/--no-branch",
2679
+ default=True,
2680
+ help="Whether to create a branch or checkout detached",
2681
+ )
2682
+ @click.option(
2683
+ "--project", "-p", envvar=env.PROJECT, help="The project you wish to upload to."
2684
+ )
2685
+ @click.option(
2686
+ "--entity", "-e", envvar=env.ENTITY, help="The entity to scope the listing to."
2687
+ )
2688
+ @display_error
2689
+ def restore(ctx, run, no_git, branch, project, entity):
2690
+ from wandb.old.core import wandb_dir
2691
+
2692
+ api = _get_cling_api()
2693
+ if ":" in run:
2694
+ if "/" in run:
2695
+ entity, rest = run.split("/", 1)
2696
+ else:
2697
+ rest = run
2698
+ project, run = rest.split(":", 1)
2699
+ elif run.count("/") > 1:
2700
+ entity, run = run.split("/", 1)
2701
+
2702
+ project, run = api.parse_slug(run, project=project)
2703
+ commit, json_config, patch_content, metadata = api.run_config(
2704
+ project, run=run, entity=entity
2705
+ )
2706
+ repo = metadata.get("git", {}).get("repo")
2707
+ image = metadata.get("docker")
2708
+ restore_message = """`wandb restore` needs to be run from the same git repository as the original run.
2709
+ Run `git clone {}` and restore from there or pass the --no-git flag.""".format(repo)
2710
+ if no_git:
2711
+ commit = None
2712
+ elif not api.git.enabled:
2713
+ if repo:
2714
+ raise ClickException(restore_message)
2715
+ elif image:
2716
+ wandb.termlog(
2717
+ "Original run has no git history. Just restoring config and docker"
2718
+ )
2719
+
2720
+ if commit and api.git.enabled:
2721
+ wandb.termlog(f"Fetching origin and finding commit: {commit}")
2722
+ subprocess.check_call(["git", "fetch", "--all"])
2723
+ try:
2724
+ api.git.repo.commit(commit)
2725
+ except ValueError:
2726
+ wandb.termlog(f"Couldn't find original commit: {commit}")
2727
+ commit = None
2728
+ files = api.download_urls(project, run=run, entity=entity)
2729
+ for filename in files:
2730
+ if filename.startswith("upstream_diff_") and filename.endswith(
2731
+ ".patch"
2732
+ ):
2733
+ commit = filename[len("upstream_diff_") : -len(".patch")]
2734
+ try:
2735
+ api.git.repo.commit(commit)
2736
+ except ValueError:
2737
+ commit = None
2738
+ else:
2739
+ break
2740
+
2741
+ if commit:
2742
+ wandb.termlog(f"Falling back to upstream commit: {commit}")
2743
+ patch_path, _ = api.download_write_file(files[filename])
2744
+ else:
2745
+ raise ClickException(restore_message)
2746
+ else:
2747
+ if patch_content:
2748
+ patch_path = os.path.join(wandb_dir(), "diff.patch")
2749
+ with open(patch_path, "w") as f:
2750
+ f.write(patch_content)
2751
+ else:
2752
+ patch_path = None
2753
+
2754
+ branch_name = "wandb/{}".format(run)
2755
+ if branch and branch_name not in api.git.repo.branches:
2756
+ api.git.repo.git.checkout(commit, b=branch_name)
2757
+ wandb.termlog(
2758
+ "Created branch {}".format(click.style(branch_name, bold=True))
2759
+ )
2760
+ elif branch:
2761
+ wandb.termlog(
2762
+ "Using existing branch, run `git branch -D {}` from master for a clean checkout".format(
2763
+ branch_name
2764
+ )
2765
+ )
2766
+ api.git.repo.git.checkout(branch_name)
2767
+ else:
2768
+ wandb.termlog("Checking out {} in detached mode".format(commit))
2769
+ api.git.repo.git.checkout(commit)
2770
+
2771
+ if patch_path:
2772
+ # we apply the patch from the repository root so git doesn't exclude
2773
+ # things outside the current directory
2774
+ root = api.git.root
2775
+ patch_rel_path = os.path.relpath(patch_path, start=root)
2776
+ # --reject is necessary or else this fails any time a binary file
2777
+ # occurs in the diff
2778
+ exit_code = subprocess.call(
2779
+ ["git", "apply", "--reject", patch_rel_path], cwd=root
2780
+ )
2781
+ if exit_code == 0:
2782
+ wandb.termlog("Applied patch")
2783
+ else:
2784
+ wandb.termerror(
2785
+ "Failed to apply patch, try un-staging any un-committed changes"
2786
+ )
2787
+
2788
+ filesystem.mkdir_exists_ok(wandb_dir())
2789
+ config_path = os.path.join(wandb_dir(), "config.yaml")
2790
+ config = Config()
2791
+ for k, v in json_config.items():
2792
+ if k not in ("_wandb", "wandb_version"):
2793
+ config[k] = v
2794
+ s = b"wandb_version: 1"
2795
+ s += b"\n\n" + yaml.dump(
2796
+ config._as_dict(),
2797
+ Dumper=yaml.SafeDumper,
2798
+ default_flow_style=False,
2799
+ allow_unicode=True,
2800
+ encoding="utf-8",
2801
+ )
2802
+ s = s.decode("utf-8")
2803
+ with open(config_path, "w") as f:
2804
+ f.write(s)
2805
+
2806
+ wandb.termlog("Restored config variables to {}".format(config_path))
2807
+ if image:
2808
+ if not metadata["program"].startswith("<") and metadata.get("args") is not None:
2809
+ # TODO: we may not want to default to python here.
2810
+ runner = util.find_runner(metadata["program"]) or ["python"]
2811
+ command = runner + [metadata["program"]] + metadata["args"]
2812
+ cmd = " ".join(command)
2813
+ else:
2814
+ wandb.termlog("Couldn't find original command, just restoring environment")
2815
+ cmd = None
2816
+ wandb.termlog("Docker image found, attempting to start")
2817
+ ctx.invoke(docker, docker_run_args=[image], cmd=cmd)
2818
+
2819
+ return commit, json_config, patch_content, repo, metadata
2820
+
2821
+
2822
+ @cli.command(context_settings=CONTEXT, help="Run any script with wandb", hidden=True)
2823
+ @click.pass_context
2824
+ @click.argument("program")
2825
+ @click.argument("args", nargs=-1)
2826
+ @display_error
2827
+ def magic(ctx, program, args):
2828
+ def magic_run(cmd, globals, locals):
2829
+ try:
2830
+ exec(cmd, globals, locals)
2831
+ finally:
2832
+ pass
2833
+
2834
+ sys.argv[:] = args
2835
+ sys.argv.insert(0, program)
2836
+ sys.path.insert(0, os.path.dirname(program))
2837
+ try:
2838
+ with open(program, "rb") as fp:
2839
+ code = compile(fp.read(), program, "exec")
2840
+ except OSError:
2841
+ click.echo(
2842
+ click.style("Could not launch program: {}".format(program), fg="red")
2843
+ )
2844
+ sys.exit(1)
2845
+ globs = {
2846
+ "__file__": program,
2847
+ "__name__": "__main__",
2848
+ "__package__": None,
2849
+ "wandb_magic_install": magic_install,
2850
+ }
2851
+ prep = """
2852
+ import __main__
2853
+ __main__.__file__ = "{}"
2854
+ wandb_magic_install()
2855
+ """.format(program)
2856
+ magic_run(prep, globs, None)
2857
+ magic_run(code, globs, None)
2858
+
2859
+
2860
+ @cli.command("online", help="Enable W&B sync")
2861
+ @display_error
2862
+ def online():
2863
+ api = InternalApi()
2864
+ try:
2865
+ api.clear_setting("disabled", persist=True)
2866
+ api.clear_setting("mode", persist=True)
2867
+ except configparser.Error:
2868
+ pass
2869
+ click.echo(
2870
+ "W&B online. Running your script from this directory will now sync to the cloud."
2871
+ )
2872
+
2873
+
2874
+ @cli.command("offline", help="Disable W&B sync")
2875
+ @display_error
2876
+ def offline():
2877
+ api = InternalApi()
2878
+ try:
2879
+ api.set_setting("disabled", "true", persist=True)
2880
+ api.set_setting("mode", "offline", persist=True)
2881
+ click.echo(
2882
+ "W&B offline. Running your script from this directory will only write metadata locally. Use wandb disabled to completely turn off W&B."
2883
+ )
2884
+ except configparser.Error:
2885
+ click.echo(
2886
+ "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=offline"
2887
+ )
2888
+
2889
+
2890
+ @cli.command("on", hidden=True)
2891
+ @click.pass_context
2892
+ @display_error
2893
+ def on(ctx):
2894
+ ctx.invoke(online)
2895
+
2896
+
2897
+ @cli.command("off", hidden=True)
2898
+ @click.pass_context
2899
+ @display_error
2900
+ def off(ctx):
2901
+ ctx.invoke(offline)
2902
+
2903
+
2904
+ @cli.command("status", help="Show configuration settings")
2905
+ @click.option(
2906
+ "--settings/--no-settings", help="Show the current settings", default=True
2907
+ )
2908
+ def status(settings):
2909
+ api = _get_cling_api()
2910
+ if settings:
2911
+ click.echo(click.style("Current Settings", bold=True))
2912
+ settings = api.settings()
2913
+ click.echo(
2914
+ json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": "))
2915
+ )
2916
+
2917
+
2918
+ @cli.command("disabled", help="Disable W&B.")
2919
+ @click.option(
2920
+ "--service",
2921
+ is_flag=True,
2922
+ show_default=True,
2923
+ default=True,
2924
+ help="Disable W&B service",
2925
+ )
2926
+ def disabled(service):
2927
+ api = InternalApi()
2928
+ try:
2929
+ api.set_setting("mode", "disabled", persist=True)
2930
+ click.echo("W&B disabled.")
2931
+ except configparser.Error:
2932
+ click.echo(
2933
+ "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=disabled"
2934
+ )
2935
+
2936
+
2937
+ @cli.command("enabled", help="Enable W&B.")
2938
+ @click.option(
2939
+ "--service",
2940
+ is_flag=True,
2941
+ show_default=True,
2942
+ default=True,
2943
+ help="Enable W&B service",
2944
+ )
2945
+ def enabled(service):
2946
+ api = InternalApi()
2947
+ try:
2948
+ api.set_setting("mode", "online", persist=True)
2949
+ click.echo("W&B enabled.")
2950
+ except configparser.Error:
2951
+ click.echo(
2952
+ "Unable to write config, copy and paste the following in your terminal to turn on W&B:\nexport WANDB_MODE=online"
2953
+ )
2954
+
2955
+
2956
+ @cli.command(context_settings=CONTEXT, help="Verify your local instance")
2957
+ @click.option("--host", default=None, help="Test a specific instance of W&B")
2958
+ def verify(host):
2959
+ # TODO: (kdg) Build this all into a WandbVerify object, and clean this up.
2960
+ os.environ["WANDB_SILENT"] = "true"
2961
+ os.environ["WANDB_PROJECT"] = "verify"
2962
+ api = _get_cling_api()
2963
+ reinit = False
2964
+ if host is None:
2965
+ host = api.settings("base_url")
2966
+ print(f"Default host selected: {host}")
2967
+ # if the given host does not match the default host, re-run init
2968
+ elif host != api.settings("base_url"):
2969
+ reinit = True
2970
+
2971
+ tmp_dir = tempfile.mkdtemp()
2972
+ print(
2973
+ "Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb"))
2974
+ )
2975
+ os.chdir(tmp_dir)
2976
+ os.environ["WANDB_BASE_URL"] = host
2977
+ wandb.login(host=host)
2978
+ if reinit:
2979
+ api = _get_cling_api(reset=True)
2980
+ if not wandb_verify.check_host(host):
2981
+ sys.exit(1)
2982
+ if not wandb_verify.check_logged_in(api, host):
2983
+ sys.exit(1)
2984
+ url_success, url = wandb_verify.check_graphql_put(api, host)
2985
+ large_post_success = wandb_verify.check_large_post()
2986
+ wandb_verify.check_secure_requests(
2987
+ api.settings("base_url"),
2988
+ "Checking requests to base url",
2989
+ "Connections are not made over https. SSL required for secure communications.",
2990
+ )
2991
+ if url:
2992
+ wandb_verify.check_secure_requests(
2993
+ url,
2994
+ "Checking requests made over signed URLs",
2995
+ "Signed URL requests not made over https. SSL is required for secure communications.",
2996
+ )
2997
+ wandb_verify.check_cors_configuration(url, host)
2998
+ wandb_verify.check_wandb_version(api)
2999
+ check_run_success = wandb_verify.check_run(api)
3000
+ check_artifacts_success = wandb_verify.check_artifacts()
3001
+ if not (
3002
+ check_artifacts_success
3003
+ and check_run_success
3004
+ and large_post_success
3005
+ and url_success
3006
+ ):
3007
+ sys.exit(1)