wandb 0.21.2__py3-none-macosx_12_0_x86_64.whl

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