wandb 0.17.0rc1__py3-none-macosx_11_0_arm64.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (842) hide show
  1. package_readme.md +95 -0
  2. wandb/__init__.py +253 -0
  3. wandb/__main__.py +3 -0
  4. wandb/_globals.py +19 -0
  5. wandb/agents/__init__.py +0 -0
  6. wandb/agents/pyagent.py +364 -0
  7. wandb/analytics/__init__.py +3 -0
  8. wandb/analytics/sentry.py +266 -0
  9. wandb/apis/__init__.py +48 -0
  10. wandb/apis/attrs.py +40 -0
  11. wandb/apis/importers/__init__.py +1 -0
  12. wandb/apis/importers/internals/internal.py +386 -0
  13. wandb/apis/importers/internals/protocols.py +99 -0
  14. wandb/apis/importers/internals/util.py +78 -0
  15. wandb/apis/importers/mlflow.py +254 -0
  16. wandb/apis/importers/validation.py +108 -0
  17. wandb/apis/importers/wandb.py +1598 -0
  18. wandb/apis/internal.py +228 -0
  19. wandb/apis/normalize.py +89 -0
  20. wandb/apis/paginator.py +81 -0
  21. wandb/apis/public/__init__.py +34 -0
  22. wandb/apis/public/api.py +1045 -0
  23. wandb/apis/public/artifacts.py +851 -0
  24. wandb/apis/public/const.py +4 -0
  25. wandb/apis/public/files.py +195 -0
  26. wandb/apis/public/history.py +149 -0
  27. wandb/apis/public/jobs.py +634 -0
  28. wandb/apis/public/projects.py +162 -0
  29. wandb/apis/public/query_generator.py +166 -0
  30. wandb/apis/public/reports.py +469 -0
  31. wandb/apis/public/runs.py +803 -0
  32. wandb/apis/public/sweeps.py +240 -0
  33. wandb/apis/public/teams.py +198 -0
  34. wandb/apis/public/users.py +136 -0
  35. wandb/apis/reports/__init__.py +7 -0
  36. wandb/apis/reports/v1/__init__.py +30 -0
  37. wandb/apis/reports/v1/_blocks.py +1406 -0
  38. wandb/apis/reports/v1/_helpers.py +70 -0
  39. wandb/apis/reports/v1/_panels.py +1282 -0
  40. wandb/apis/reports/v1/_templates.py +478 -0
  41. wandb/apis/reports/v1/blocks.py +27 -0
  42. wandb/apis/reports/v1/helpers.py +2 -0
  43. wandb/apis/reports/v1/mutations.py +66 -0
  44. wandb/apis/reports/v1/panels.py +17 -0
  45. wandb/apis/reports/v1/report.py +268 -0
  46. wandb/apis/reports/v1/runset.py +144 -0
  47. wandb/apis/reports/v1/templates.py +7 -0
  48. wandb/apis/reports/v1/util.py +406 -0
  49. wandb/apis/reports/v1/validators.py +131 -0
  50. wandb/apis/reports/v2/__init__.py +20 -0
  51. wandb/apis/reports/v2/blocks.py +25 -0
  52. wandb/apis/reports/v2/expr_parsing.py +257 -0
  53. wandb/apis/reports/v2/gql.py +68 -0
  54. wandb/apis/reports/v2/interface.py +1911 -0
  55. wandb/apis/reports/v2/internal.py +867 -0
  56. wandb/apis/reports/v2/metrics.py +6 -0
  57. wandb/apis/reports/v2/panels.py +15 -0
  58. wandb/beta/workflows.py +283 -0
  59. wandb/bin/apple_gpu_stats +0 -0
  60. wandb/bin/wandb-core +0 -0
  61. wandb/catboost/__init__.py +9 -0
  62. wandb/cli/__init__.py +0 -0
  63. wandb/cli/cli.py +2890 -0
  64. wandb/data_types.py +2068 -0
  65. wandb/docker/__init__.py +342 -0
  66. wandb/docker/auth.py +436 -0
  67. wandb/docker/wandb-entrypoint.sh +33 -0
  68. wandb/docker/www_authenticate.py +94 -0
  69. wandb/env.py +496 -0
  70. wandb/errors/__init__.py +46 -0
  71. wandb/errors/term.py +95 -0
  72. wandb/errors/util.py +57 -0
  73. wandb/fastai/__init__.py +9 -0
  74. wandb/filesync/__init__.py +0 -0
  75. wandb/filesync/dir_watcher.py +403 -0
  76. wandb/filesync/stats.py +100 -0
  77. wandb/filesync/step_checksum.py +145 -0
  78. wandb/filesync/step_prepare.py +199 -0
  79. wandb/filesync/step_upload.py +392 -0
  80. wandb/filesync/upload_job.py +218 -0
  81. wandb/integration/__init__.py +0 -0
  82. wandb/integration/catboost/__init__.py +5 -0
  83. wandb/integration/catboost/catboost.py +178 -0
  84. wandb/integration/cohere/__init__.py +3 -0
  85. wandb/integration/cohere/cohere.py +21 -0
  86. wandb/integration/cohere/resolver.py +347 -0
  87. wandb/integration/diffusers/__init__.py +3 -0
  88. wandb/integration/diffusers/autologger.py +76 -0
  89. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  90. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  91. wandb/integration/diffusers/resolvers/multimodal.py +882 -0
  92. wandb/integration/diffusers/resolvers/utils.py +102 -0
  93. wandb/integration/fastai/__init__.py +249 -0
  94. wandb/integration/gym/__init__.py +85 -0
  95. wandb/integration/huggingface/__init__.py +3 -0
  96. wandb/integration/huggingface/huggingface.py +18 -0
  97. wandb/integration/huggingface/resolver.py +213 -0
  98. wandb/integration/keras/__init__.py +14 -0
  99. wandb/integration/keras/callbacks/__init__.py +5 -0
  100. wandb/integration/keras/callbacks/metrics_logger.py +130 -0
  101. wandb/integration/keras/callbacks/model_checkpoint.py +200 -0
  102. wandb/integration/keras/callbacks/tables_builder.py +226 -0
  103. wandb/integration/keras/keras.py +1080 -0
  104. wandb/integration/kfp/__init__.py +6 -0
  105. wandb/integration/kfp/helpers.py +28 -0
  106. wandb/integration/kfp/kfp_patch.py +324 -0
  107. wandb/integration/kfp/wandb_logging.py +182 -0
  108. wandb/integration/langchain/__init__.py +3 -0
  109. wandb/integration/langchain/wandb_tracer.py +48 -0
  110. wandb/integration/lightgbm/__init__.py +239 -0
  111. wandb/integration/lightning/__init__.py +0 -0
  112. wandb/integration/lightning/fabric/__init__.py +3 -0
  113. wandb/integration/lightning/fabric/logger.py +762 -0
  114. wandb/integration/magic.py +556 -0
  115. wandb/integration/metaflow/__init__.py +3 -0
  116. wandb/integration/metaflow/metaflow.py +383 -0
  117. wandb/integration/openai/__init__.py +3 -0
  118. wandb/integration/openai/fine_tuning.py +454 -0
  119. wandb/integration/openai/openai.py +22 -0
  120. wandb/integration/openai/resolver.py +240 -0
  121. wandb/integration/prodigy/__init__.py +3 -0
  122. wandb/integration/prodigy/prodigy.py +299 -0
  123. wandb/integration/sacred/__init__.py +117 -0
  124. wandb/integration/sagemaker/__init__.py +12 -0
  125. wandb/integration/sagemaker/auth.py +28 -0
  126. wandb/integration/sagemaker/config.py +49 -0
  127. wandb/integration/sagemaker/files.py +3 -0
  128. wandb/integration/sagemaker/resources.py +34 -0
  129. wandb/integration/sb3/__init__.py +3 -0
  130. wandb/integration/sb3/sb3.py +153 -0
  131. wandb/integration/tensorboard/__init__.py +10 -0
  132. wandb/integration/tensorboard/log.py +358 -0
  133. wandb/integration/tensorboard/monkeypatch.py +185 -0
  134. wandb/integration/tensorflow/__init__.py +5 -0
  135. wandb/integration/tensorflow/estimator_hook.py +54 -0
  136. wandb/integration/torch/__init__.py +0 -0
  137. wandb/integration/ultralytics/__init__.py +11 -0
  138. wandb/integration/ultralytics/bbox_utils.py +208 -0
  139. wandb/integration/ultralytics/callback.py +524 -0
  140. wandb/integration/ultralytics/classification_utils.py +83 -0
  141. wandb/integration/ultralytics/mask_utils.py +202 -0
  142. wandb/integration/ultralytics/pose_utils.py +104 -0
  143. wandb/integration/xgboost/__init__.py +11 -0
  144. wandb/integration/xgboost/xgboost.py +189 -0
  145. wandb/integration/yolov8/__init__.py +0 -0
  146. wandb/integration/yolov8/yolov8.py +284 -0
  147. wandb/jupyter.py +501 -0
  148. wandb/keras/__init__.py +19 -0
  149. wandb/lightgbm/__init__.py +9 -0
  150. wandb/magic.py +3 -0
  151. wandb/mpmain/__init__.py +0 -0
  152. wandb/mpmain/__main__.py +1 -0
  153. wandb/old/__init__.py +0 -0
  154. wandb/old/core.py +131 -0
  155. wandb/old/settings.py +173 -0
  156. wandb/old/summary.py +435 -0
  157. wandb/plot/__init__.py +19 -0
  158. wandb/plot/bar.py +42 -0
  159. wandb/plot/confusion_matrix.py +99 -0
  160. wandb/plot/histogram.py +36 -0
  161. wandb/plot/line.py +40 -0
  162. wandb/plot/line_series.py +88 -0
  163. wandb/plot/pr_curve.py +135 -0
  164. wandb/plot/roc_curve.py +117 -0
  165. wandb/plot/scatter.py +32 -0
  166. wandb/plots/__init__.py +6 -0
  167. wandb/plots/explain_text.py +36 -0
  168. wandb/plots/heatmap.py +81 -0
  169. wandb/plots/named_entity.py +43 -0
  170. wandb/plots/part_of_speech.py +50 -0
  171. wandb/plots/plot_definitions.py +768 -0
  172. wandb/plots/precision_recall.py +121 -0
  173. wandb/plots/roc.py +103 -0
  174. wandb/plots/utils.py +195 -0
  175. wandb/proto/__init__.py +0 -0
  176. wandb/proto/v3/__init__.py +0 -0
  177. wandb/proto/v3/wandb_base_pb2.py +54 -0
  178. wandb/proto/v3/wandb_internal_pb2.py +1586 -0
  179. wandb/proto/v3/wandb_server_pb2.py +207 -0
  180. wandb/proto/v3/wandb_settings_pb2.py +111 -0
  181. wandb/proto/v3/wandb_telemetry_pb2.py +105 -0
  182. wandb/proto/v4/__init__.py +0 -0
  183. wandb/proto/v4/wandb_base_pb2.py +29 -0
  184. wandb/proto/v4/wandb_internal_pb2.py +354 -0
  185. wandb/proto/v4/wandb_server_pb2.py +62 -0
  186. wandb/proto/v4/wandb_settings_pb2.py +44 -0
  187. wandb/proto/v4/wandb_telemetry_pb2.py +40 -0
  188. wandb/proto/wandb_base_pb2.py +8 -0
  189. wandb/proto/wandb_deprecated.py +37 -0
  190. wandb/proto/wandb_internal_codegen.py +83 -0
  191. wandb/proto/wandb_internal_pb2.py +8 -0
  192. wandb/proto/wandb_server_pb2.py +8 -0
  193. wandb/proto/wandb_settings_pb2.py +8 -0
  194. wandb/proto/wandb_telemetry_pb2.py +8 -0
  195. wandb/py.typed +0 -0
  196. wandb/sacred/__init__.py +3 -0
  197. wandb/sdk/__init__.py +37 -0
  198. wandb/sdk/artifacts/__init__.py +0 -0
  199. wandb/sdk/artifacts/artifact.py +2317 -0
  200. wandb/sdk/artifacts/artifact_download_logger.py +43 -0
  201. wandb/sdk/artifacts/artifact_file_cache.py +229 -0
  202. wandb/sdk/artifacts/artifact_instance_cache.py +15 -0
  203. wandb/sdk/artifacts/artifact_manifest.py +72 -0
  204. wandb/sdk/artifacts/artifact_manifest_entry.py +205 -0
  205. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  206. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +90 -0
  207. wandb/sdk/artifacts/artifact_saver.py +270 -0
  208. wandb/sdk/artifacts/artifact_state.py +11 -0
  209. wandb/sdk/artifacts/artifact_ttl.py +7 -0
  210. wandb/sdk/artifacts/exceptions.py +56 -0
  211. wandb/sdk/artifacts/staging.py +25 -0
  212. wandb/sdk/artifacts/storage_handler.py +60 -0
  213. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  214. wandb/sdk/artifacts/storage_handlers/azure_handler.py +194 -0
  215. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +195 -0
  216. wandb/sdk/artifacts/storage_handlers/http_handler.py +113 -0
  217. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +135 -0
  218. wandb/sdk/artifacts/storage_handlers/multi_handler.py +54 -0
  219. wandb/sdk/artifacts/storage_handlers/s3_handler.py +300 -0
  220. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +68 -0
  221. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +133 -0
  222. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +72 -0
  223. wandb/sdk/artifacts/storage_layout.py +6 -0
  224. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  225. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  226. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +411 -0
  227. wandb/sdk/artifacts/storage_policy.py +83 -0
  228. wandb/sdk/backend/__init__.py +0 -0
  229. wandb/sdk/backend/backend.py +240 -0
  230. wandb/sdk/data_types/__init__.py +0 -0
  231. wandb/sdk/data_types/_dtypes.py +911 -0
  232. wandb/sdk/data_types/_private.py +10 -0
  233. wandb/sdk/data_types/base_types/__init__.py +0 -0
  234. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  235. wandb/sdk/data_types/base_types/media.py +313 -0
  236. wandb/sdk/data_types/base_types/wb_value.py +274 -0
  237. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  238. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +293 -0
  239. wandb/sdk/data_types/helper_types/classes.py +159 -0
  240. wandb/sdk/data_types/helper_types/image_mask.py +233 -0
  241. wandb/sdk/data_types/histogram.py +96 -0
  242. wandb/sdk/data_types/html.py +115 -0
  243. wandb/sdk/data_types/image.py +687 -0
  244. wandb/sdk/data_types/molecule.py +241 -0
  245. wandb/sdk/data_types/object_3d.py +363 -0
  246. wandb/sdk/data_types/plotly.py +82 -0
  247. wandb/sdk/data_types/saved_model.py +444 -0
  248. wandb/sdk/data_types/trace_tree.py +438 -0
  249. wandb/sdk/data_types/utils.py +180 -0
  250. wandb/sdk/data_types/video.py +245 -0
  251. wandb/sdk/integration_utils/__init__.py +0 -0
  252. wandb/sdk/integration_utils/auto_logging.py +239 -0
  253. wandb/sdk/integration_utils/data_logging.py +475 -0
  254. wandb/sdk/interface/__init__.py +0 -0
  255. wandb/sdk/interface/constants.py +4 -0
  256. wandb/sdk/interface/interface.py +949 -0
  257. wandb/sdk/interface/interface_queue.py +59 -0
  258. wandb/sdk/interface/interface_relay.py +53 -0
  259. wandb/sdk/interface/interface_shared.py +550 -0
  260. wandb/sdk/interface/interface_sock.py +61 -0
  261. wandb/sdk/interface/message_future.py +27 -0
  262. wandb/sdk/interface/message_future_poll.py +50 -0
  263. wandb/sdk/interface/router.py +118 -0
  264. wandb/sdk/interface/router_queue.py +44 -0
  265. wandb/sdk/interface/router_relay.py +39 -0
  266. wandb/sdk/interface/router_sock.py +36 -0
  267. wandb/sdk/interface/summary_record.py +67 -0
  268. wandb/sdk/internal/__init__.py +0 -0
  269. wandb/sdk/internal/context.py +89 -0
  270. wandb/sdk/internal/datastore.py +297 -0
  271. wandb/sdk/internal/file_pusher.py +184 -0
  272. wandb/sdk/internal/file_stream.py +708 -0
  273. wandb/sdk/internal/flow_control.py +263 -0
  274. wandb/sdk/internal/handler.py +909 -0
  275. wandb/sdk/internal/internal.py +417 -0
  276. wandb/sdk/internal/internal_api.py +4202 -0
  277. wandb/sdk/internal/internal_util.py +100 -0
  278. wandb/sdk/internal/job_builder.py +554 -0
  279. wandb/sdk/internal/profiler.py +78 -0
  280. wandb/sdk/internal/progress.py +111 -0
  281. wandb/sdk/internal/run.py +25 -0
  282. wandb/sdk/internal/sample.py +70 -0
  283. wandb/sdk/internal/sender.py +1642 -0
  284. wandb/sdk/internal/sender_config.py +197 -0
  285. wandb/sdk/internal/settings_static.py +83 -0
  286. wandb/sdk/internal/system/__init__.py +0 -0
  287. wandb/sdk/internal/system/assets/__init__.py +27 -0
  288. wandb/sdk/internal/system/assets/aggregators.py +37 -0
  289. wandb/sdk/internal/system/assets/asset_registry.py +20 -0
  290. wandb/sdk/internal/system/assets/cpu.py +163 -0
  291. wandb/sdk/internal/system/assets/disk.py +210 -0
  292. wandb/sdk/internal/system/assets/gpu.py +414 -0
  293. wandb/sdk/internal/system/assets/gpu_amd.py +230 -0
  294. wandb/sdk/internal/system/assets/gpu_apple.py +177 -0
  295. wandb/sdk/internal/system/assets/interfaces.py +207 -0
  296. wandb/sdk/internal/system/assets/ipu.py +177 -0
  297. wandb/sdk/internal/system/assets/memory.py +166 -0
  298. wandb/sdk/internal/system/assets/network.py +125 -0
  299. wandb/sdk/internal/system/assets/open_metrics.py +299 -0
  300. wandb/sdk/internal/system/assets/tpu.py +154 -0
  301. wandb/sdk/internal/system/assets/trainium.py +398 -0
  302. wandb/sdk/internal/system/env_probe_helpers.py +13 -0
  303. wandb/sdk/internal/system/system_info.py +247 -0
  304. wandb/sdk/internal/system/system_monitor.py +229 -0
  305. wandb/sdk/internal/tb_watcher.py +518 -0
  306. wandb/sdk/internal/thread_local_settings.py +18 -0
  307. wandb/sdk/internal/update.py +113 -0
  308. wandb/sdk/internal/writer.py +206 -0
  309. wandb/sdk/launch/__init__.py +6 -0
  310. wandb/sdk/launch/_launch.py +348 -0
  311. wandb/sdk/launch/_launch_add.py +257 -0
  312. wandb/sdk/launch/_project_spec.py +578 -0
  313. wandb/sdk/launch/agent/__init__.py +5 -0
  314. wandb/sdk/launch/agent/agent.py +878 -0
  315. wandb/sdk/launch/agent/config.py +299 -0
  316. wandb/sdk/launch/agent/job_status_tracker.py +53 -0
  317. wandb/sdk/launch/agent/run_queue_item_file_saver.py +47 -0
  318. wandb/sdk/launch/builder/__init__.py +0 -0
  319. wandb/sdk/launch/builder/abstract.py +89 -0
  320. wandb/sdk/launch/builder/build.py +706 -0
  321. wandb/sdk/launch/builder/docker_builder.py +193 -0
  322. wandb/sdk/launch/builder/kaniko_builder.py +579 -0
  323. wandb/sdk/launch/builder/noop.py +58 -0
  324. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +187 -0
  325. wandb/sdk/launch/create_job.py +520 -0
  326. wandb/sdk/launch/environment/abstract.py +29 -0
  327. wandb/sdk/launch/environment/aws_environment.py +297 -0
  328. wandb/sdk/launch/environment/azure_environment.py +105 -0
  329. wandb/sdk/launch/environment/gcp_environment.py +335 -0
  330. wandb/sdk/launch/environment/local_environment.py +66 -0
  331. wandb/sdk/launch/errors.py +19 -0
  332. wandb/sdk/launch/git_reference.py +109 -0
  333. wandb/sdk/launch/loader.py +249 -0
  334. wandb/sdk/launch/registry/abstract.py +48 -0
  335. wandb/sdk/launch/registry/anon.py +29 -0
  336. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  337. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  338. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  339. wandb/sdk/launch/registry/local_registry.py +67 -0
  340. wandb/sdk/launch/runner/__init__.py +0 -0
  341. wandb/sdk/launch/runner/abstract.py +195 -0
  342. wandb/sdk/launch/runner/kubernetes_monitor.py +441 -0
  343. wandb/sdk/launch/runner/kubernetes_runner.py +893 -0
  344. wandb/sdk/launch/runner/local_container.py +299 -0
  345. wandb/sdk/launch/runner/local_process.py +99 -0
  346. wandb/sdk/launch/runner/sagemaker_runner.py +422 -0
  347. wandb/sdk/launch/runner/vertex_runner.py +229 -0
  348. wandb/sdk/launch/sweeps/__init__.py +39 -0
  349. wandb/sdk/launch/sweeps/scheduler.py +738 -0
  350. wandb/sdk/launch/sweeps/scheduler_sweep.py +91 -0
  351. wandb/sdk/launch/sweeps/utils.py +316 -0
  352. wandb/sdk/launch/utils.py +866 -0
  353. wandb/sdk/launch/wandb_reference.py +138 -0
  354. wandb/sdk/lib/__init__.py +5 -0
  355. wandb/sdk/lib/_settings_toposort_generate.py +159 -0
  356. wandb/sdk/lib/_settings_toposort_generated.py +244 -0
  357. wandb/sdk/lib/_wburls_generate.py +25 -0
  358. wandb/sdk/lib/_wburls_generated.py +22 -0
  359. wandb/sdk/lib/apikey.py +258 -0
  360. wandb/sdk/lib/capped_dict.py +26 -0
  361. wandb/sdk/lib/config_util.py +101 -0
  362. wandb/sdk/lib/console.py +39 -0
  363. wandb/sdk/lib/deprecate.py +42 -0
  364. wandb/sdk/lib/disabled.py +190 -0
  365. wandb/sdk/lib/exit_hooks.py +54 -0
  366. wandb/sdk/lib/file_stream_utils.py +118 -0
  367. wandb/sdk/lib/filenames.py +64 -0
  368. wandb/sdk/lib/filesystem.py +372 -0
  369. wandb/sdk/lib/fsm.py +174 -0
  370. wandb/sdk/lib/gitlib.py +239 -0
  371. wandb/sdk/lib/gql_request.py +65 -0
  372. wandb/sdk/lib/handler_util.py +21 -0
  373. wandb/sdk/lib/hashutil.py +62 -0
  374. wandb/sdk/lib/import_hooks.py +275 -0
  375. wandb/sdk/lib/ipython.py +146 -0
  376. wandb/sdk/lib/json_util.py +80 -0
  377. wandb/sdk/lib/lazyloader.py +63 -0
  378. wandb/sdk/lib/mailbox.py +460 -0
  379. wandb/sdk/lib/module.py +69 -0
  380. wandb/sdk/lib/paths.py +106 -0
  381. wandb/sdk/lib/preinit.py +42 -0
  382. wandb/sdk/lib/printer.py +313 -0
  383. wandb/sdk/lib/proto_util.py +69 -0
  384. wandb/sdk/lib/redirect.py +840 -0
  385. wandb/sdk/lib/reporting.py +99 -0
  386. wandb/sdk/lib/retry.py +289 -0
  387. wandb/sdk/lib/run_moment.py +78 -0
  388. wandb/sdk/lib/runid.py +12 -0
  389. wandb/sdk/lib/server.py +52 -0
  390. wandb/sdk/lib/sock_client.py +291 -0
  391. wandb/sdk/lib/sparkline.py +45 -0
  392. wandb/sdk/lib/telemetry.py +100 -0
  393. wandb/sdk/lib/timed_input.py +133 -0
  394. wandb/sdk/lib/timer.py +19 -0
  395. wandb/sdk/lib/tracelog.py +255 -0
  396. wandb/sdk/lib/wburls.py +46 -0
  397. wandb/sdk/service/__init__.py +0 -0
  398. wandb/sdk/service/_startup_debug.py +22 -0
  399. wandb/sdk/service/port_file.py +53 -0
  400. wandb/sdk/service/server.py +119 -0
  401. wandb/sdk/service/server_sock.py +276 -0
  402. wandb/sdk/service/service.py +266 -0
  403. wandb/sdk/service/service_base.py +50 -0
  404. wandb/sdk/service/service_sock.py +70 -0
  405. wandb/sdk/service/streams.py +426 -0
  406. wandb/sdk/verify/__init__.py +0 -0
  407. wandb/sdk/verify/verify.py +501 -0
  408. wandb/sdk/wandb_alerts.py +12 -0
  409. wandb/sdk/wandb_config.py +319 -0
  410. wandb/sdk/wandb_helper.py +54 -0
  411. wandb/sdk/wandb_init.py +1220 -0
  412. wandb/sdk/wandb_login.py +339 -0
  413. wandb/sdk/wandb_manager.py +222 -0
  414. wandb/sdk/wandb_metric.py +110 -0
  415. wandb/sdk/wandb_require.py +92 -0
  416. wandb/sdk/wandb_require_helpers.py +44 -0
  417. wandb/sdk/wandb_run.py +4191 -0
  418. wandb/sdk/wandb_settings.py +1973 -0
  419. wandb/sdk/wandb_setup.py +335 -0
  420. wandb/sdk/wandb_summary.py +150 -0
  421. wandb/sdk/wandb_sweep.py +114 -0
  422. wandb/sdk/wandb_sync.py +75 -0
  423. wandb/sdk/wandb_watch.py +128 -0
  424. wandb/sklearn/__init__.py +37 -0
  425. wandb/sklearn/calculate/__init__.py +32 -0
  426. wandb/sklearn/calculate/calibration_curves.py +125 -0
  427. wandb/sklearn/calculate/class_proportions.py +68 -0
  428. wandb/sklearn/calculate/confusion_matrix.py +92 -0
  429. wandb/sklearn/calculate/decision_boundaries.py +40 -0
  430. wandb/sklearn/calculate/elbow_curve.py +55 -0
  431. wandb/sklearn/calculate/feature_importances.py +67 -0
  432. wandb/sklearn/calculate/learning_curve.py +64 -0
  433. wandb/sklearn/calculate/outlier_candidates.py +69 -0
  434. wandb/sklearn/calculate/residuals.py +86 -0
  435. wandb/sklearn/calculate/silhouette.py +118 -0
  436. wandb/sklearn/calculate/summary_metrics.py +62 -0
  437. wandb/sklearn/plot/__init__.py +35 -0
  438. wandb/sklearn/plot/classifier.py +331 -0
  439. wandb/sklearn/plot/clusterer.py +142 -0
  440. wandb/sklearn/plot/regressor.py +121 -0
  441. wandb/sklearn/plot/shared.py +91 -0
  442. wandb/sklearn/utils.py +183 -0
  443. wandb/sync/__init__.py +3 -0
  444. wandb/sync/sync.py +443 -0
  445. wandb/testing/relay.py +859 -0
  446. wandb/trigger.py +29 -0
  447. wandb/util.py +1925 -0
  448. wandb/vendor/__init__.py +0 -0
  449. wandb/vendor/gql-0.2.0/setup.py +40 -0
  450. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  451. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  452. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  453. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  454. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  455. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  456. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  457. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  458. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  459. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  460. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  461. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  462. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  463. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  464. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  465. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  466. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  467. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  468. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  469. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  470. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  471. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  472. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  473. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  474. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  475. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  476. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  477. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  478. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  479. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  480. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  481. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  482. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  483. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  484. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  485. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  486. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  487. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  488. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  489. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  490. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  491. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  492. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  493. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  494. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  495. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  496. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  497. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  498. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  499. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  500. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  501. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  502. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  503. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  504. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  505. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  506. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  507. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  508. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  509. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  510. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  511. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  512. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  513. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  514. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  515. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  516. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  517. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  518. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  519. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  520. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  521. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  522. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  523. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  524. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  525. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  526. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  527. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  528. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  529. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  530. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  531. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  532. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  533. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  534. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  535. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  549. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  550. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  551. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  552. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  553. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  554. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  555. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  556. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  557. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  558. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  559. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  560. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  561. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  562. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  563. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  564. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  565. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  566. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  567. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  568. wandb/vendor/promise-2.3.0/setup.py +64 -0
  569. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  570. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  571. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  572. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  573. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  574. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  575. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  576. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  577. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  578. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  579. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  580. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  581. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  582. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  583. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  584. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  585. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  586. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  587. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  588. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  589. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  590. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  591. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  592. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  593. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  594. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  595. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  596. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  597. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  598. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  599. wandb/vendor/pygments/__init__.py +90 -0
  600. wandb/vendor/pygments/cmdline.py +568 -0
  601. wandb/vendor/pygments/console.py +74 -0
  602. wandb/vendor/pygments/filter.py +74 -0
  603. wandb/vendor/pygments/filters/__init__.py +350 -0
  604. wandb/vendor/pygments/formatter.py +95 -0
  605. wandb/vendor/pygments/formatters/__init__.py +153 -0
  606. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  607. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  608. wandb/vendor/pygments/formatters/html.py +851 -0
  609. wandb/vendor/pygments/formatters/img.py +600 -0
  610. wandb/vendor/pygments/formatters/irc.py +182 -0
  611. wandb/vendor/pygments/formatters/latex.py +482 -0
  612. wandb/vendor/pygments/formatters/other.py +160 -0
  613. wandb/vendor/pygments/formatters/rtf.py +147 -0
  614. wandb/vendor/pygments/formatters/svg.py +153 -0
  615. wandb/vendor/pygments/formatters/terminal.py +136 -0
  616. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  617. wandb/vendor/pygments/lexer.py +871 -0
  618. wandb/vendor/pygments/lexers/__init__.py +329 -0
  619. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  620. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  621. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  622. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  623. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  624. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  625. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  626. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  627. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  628. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  629. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  630. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  631. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  632. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  633. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  634. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  635. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  636. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  637. wandb/vendor/pygments/lexers/agile.py +24 -0
  638. wandb/vendor/pygments/lexers/algebra.py +221 -0
  639. wandb/vendor/pygments/lexers/ambient.py +76 -0
  640. wandb/vendor/pygments/lexers/ampl.py +87 -0
  641. wandb/vendor/pygments/lexers/apl.py +101 -0
  642. wandb/vendor/pygments/lexers/archetype.py +318 -0
  643. wandb/vendor/pygments/lexers/asm.py +641 -0
  644. wandb/vendor/pygments/lexers/automation.py +374 -0
  645. wandb/vendor/pygments/lexers/basic.py +500 -0
  646. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  647. wandb/vendor/pygments/lexers/business.py +612 -0
  648. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  649. wandb/vendor/pygments/lexers/c_like.py +541 -0
  650. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  651. wandb/vendor/pygments/lexers/chapel.py +102 -0
  652. wandb/vendor/pygments/lexers/clean.py +288 -0
  653. wandb/vendor/pygments/lexers/compiled.py +34 -0
  654. wandb/vendor/pygments/lexers/configs.py +833 -0
  655. wandb/vendor/pygments/lexers/console.py +114 -0
  656. wandb/vendor/pygments/lexers/crystal.py +393 -0
  657. wandb/vendor/pygments/lexers/csound.py +366 -0
  658. wandb/vendor/pygments/lexers/css.py +689 -0
  659. wandb/vendor/pygments/lexers/d.py +251 -0
  660. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  661. wandb/vendor/pygments/lexers/data.py +555 -0
  662. wandb/vendor/pygments/lexers/diff.py +165 -0
  663. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  664. wandb/vendor/pygments/lexers/dsls.py +878 -0
  665. wandb/vendor/pygments/lexers/dylan.py +289 -0
  666. wandb/vendor/pygments/lexers/ecl.py +125 -0
  667. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  668. wandb/vendor/pygments/lexers/elm.py +121 -0
  669. wandb/vendor/pygments/lexers/erlang.py +533 -0
  670. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  671. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  672. wandb/vendor/pygments/lexers/factor.py +344 -0
  673. wandb/vendor/pygments/lexers/fantom.py +250 -0
  674. wandb/vendor/pygments/lexers/felix.py +273 -0
  675. wandb/vendor/pygments/lexers/forth.py +177 -0
  676. wandb/vendor/pygments/lexers/fortran.py +205 -0
  677. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  678. wandb/vendor/pygments/lexers/functional.py +21 -0
  679. wandb/vendor/pygments/lexers/go.py +101 -0
  680. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  681. wandb/vendor/pygments/lexers/graph.py +80 -0
  682. wandb/vendor/pygments/lexers/graphics.py +553 -0
  683. wandb/vendor/pygments/lexers/haskell.py +843 -0
  684. wandb/vendor/pygments/lexers/haxe.py +936 -0
  685. wandb/vendor/pygments/lexers/hdl.py +382 -0
  686. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  687. wandb/vendor/pygments/lexers/html.py +602 -0
  688. wandb/vendor/pygments/lexers/idl.py +270 -0
  689. wandb/vendor/pygments/lexers/igor.py +288 -0
  690. wandb/vendor/pygments/lexers/inferno.py +96 -0
  691. wandb/vendor/pygments/lexers/installers.py +322 -0
  692. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  693. wandb/vendor/pygments/lexers/iolang.py +63 -0
  694. wandb/vendor/pygments/lexers/j.py +146 -0
  695. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  696. wandb/vendor/pygments/lexers/julia.py +333 -0
  697. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  698. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  699. wandb/vendor/pygments/lexers/make.py +202 -0
  700. wandb/vendor/pygments/lexers/markup.py +595 -0
  701. wandb/vendor/pygments/lexers/math.py +21 -0
  702. wandb/vendor/pygments/lexers/matlab.py +663 -0
  703. wandb/vendor/pygments/lexers/ml.py +769 -0
  704. wandb/vendor/pygments/lexers/modeling.py +358 -0
  705. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  706. wandb/vendor/pygments/lexers/monte.py +204 -0
  707. wandb/vendor/pygments/lexers/ncl.py +894 -0
  708. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  709. wandb/vendor/pygments/lexers/nit.py +64 -0
  710. wandb/vendor/pygments/lexers/nix.py +136 -0
  711. wandb/vendor/pygments/lexers/oberon.py +105 -0
  712. wandb/vendor/pygments/lexers/objective.py +504 -0
  713. wandb/vendor/pygments/lexers/ooc.py +85 -0
  714. wandb/vendor/pygments/lexers/other.py +41 -0
  715. wandb/vendor/pygments/lexers/parasail.py +79 -0
  716. wandb/vendor/pygments/lexers/parsers.py +835 -0
  717. wandb/vendor/pygments/lexers/pascal.py +644 -0
  718. wandb/vendor/pygments/lexers/pawn.py +199 -0
  719. wandb/vendor/pygments/lexers/perl.py +620 -0
  720. wandb/vendor/pygments/lexers/php.py +267 -0
  721. wandb/vendor/pygments/lexers/praat.py +294 -0
  722. wandb/vendor/pygments/lexers/prolog.py +306 -0
  723. wandb/vendor/pygments/lexers/python.py +939 -0
  724. wandb/vendor/pygments/lexers/qvt.py +152 -0
  725. wandb/vendor/pygments/lexers/r.py +453 -0
  726. wandb/vendor/pygments/lexers/rdf.py +270 -0
  727. wandb/vendor/pygments/lexers/rebol.py +431 -0
  728. wandb/vendor/pygments/lexers/resource.py +85 -0
  729. wandb/vendor/pygments/lexers/rnc.py +67 -0
  730. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  731. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  732. wandb/vendor/pygments/lexers/ruby.py +519 -0
  733. wandb/vendor/pygments/lexers/rust.py +220 -0
  734. wandb/vendor/pygments/lexers/sas.py +228 -0
  735. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  736. wandb/vendor/pygments/lexers/shell.py +794 -0
  737. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  738. wandb/vendor/pygments/lexers/smv.py +79 -0
  739. wandb/vendor/pygments/lexers/snobol.py +83 -0
  740. wandb/vendor/pygments/lexers/special.py +103 -0
  741. wandb/vendor/pygments/lexers/sql.py +681 -0
  742. wandb/vendor/pygments/lexers/stata.py +108 -0
  743. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  744. wandb/vendor/pygments/lexers/tcl.py +145 -0
  745. wandb/vendor/pygments/lexers/templates.py +2283 -0
  746. wandb/vendor/pygments/lexers/testing.py +207 -0
  747. wandb/vendor/pygments/lexers/text.py +25 -0
  748. wandb/vendor/pygments/lexers/textedit.py +169 -0
  749. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  750. wandb/vendor/pygments/lexers/theorem.py +458 -0
  751. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  752. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  753. wandb/vendor/pygments/lexers/urbi.py +133 -0
  754. wandb/vendor/pygments/lexers/varnish.py +190 -0
  755. wandb/vendor/pygments/lexers/verification.py +111 -0
  756. wandb/vendor/pygments/lexers/web.py +24 -0
  757. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  758. wandb/vendor/pygments/lexers/whiley.py +116 -0
  759. wandb/vendor/pygments/lexers/x10.py +69 -0
  760. wandb/vendor/pygments/modeline.py +44 -0
  761. wandb/vendor/pygments/plugin.py +68 -0
  762. wandb/vendor/pygments/regexopt.py +92 -0
  763. wandb/vendor/pygments/scanner.py +105 -0
  764. wandb/vendor/pygments/sphinxext.py +158 -0
  765. wandb/vendor/pygments/style.py +155 -0
  766. wandb/vendor/pygments/styles/__init__.py +80 -0
  767. wandb/vendor/pygments/styles/abap.py +29 -0
  768. wandb/vendor/pygments/styles/algol.py +63 -0
  769. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  770. wandb/vendor/pygments/styles/arduino.py +98 -0
  771. wandb/vendor/pygments/styles/autumn.py +65 -0
  772. wandb/vendor/pygments/styles/borland.py +51 -0
  773. wandb/vendor/pygments/styles/bw.py +49 -0
  774. wandb/vendor/pygments/styles/colorful.py +81 -0
  775. wandb/vendor/pygments/styles/default.py +73 -0
  776. wandb/vendor/pygments/styles/emacs.py +72 -0
  777. wandb/vendor/pygments/styles/friendly.py +72 -0
  778. wandb/vendor/pygments/styles/fruity.py +42 -0
  779. wandb/vendor/pygments/styles/igor.py +29 -0
  780. wandb/vendor/pygments/styles/lovelace.py +97 -0
  781. wandb/vendor/pygments/styles/manni.py +75 -0
  782. wandb/vendor/pygments/styles/monokai.py +106 -0
  783. wandb/vendor/pygments/styles/murphy.py +80 -0
  784. wandb/vendor/pygments/styles/native.py +65 -0
  785. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  786. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  787. wandb/vendor/pygments/styles/pastie.py +75 -0
  788. wandb/vendor/pygments/styles/perldoc.py +69 -0
  789. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  790. wandb/vendor/pygments/styles/rrt.py +33 -0
  791. wandb/vendor/pygments/styles/sas.py +44 -0
  792. wandb/vendor/pygments/styles/stata.py +40 -0
  793. wandb/vendor/pygments/styles/tango.py +141 -0
  794. wandb/vendor/pygments/styles/trac.py +63 -0
  795. wandb/vendor/pygments/styles/vim.py +63 -0
  796. wandb/vendor/pygments/styles/vs.py +38 -0
  797. wandb/vendor/pygments/styles/xcode.py +51 -0
  798. wandb/vendor/pygments/token.py +213 -0
  799. wandb/vendor/pygments/unistring.py +217 -0
  800. wandb/vendor/pygments/util.py +388 -0
  801. wandb/vendor/pynvml/__init__.py +0 -0
  802. wandb/vendor/pynvml/pynvml.py +4779 -0
  803. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  804. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  805. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  806. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  807. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  808. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  809. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  810. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  811. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  812. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  813. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  814. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  815. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  816. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  817. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  818. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  819. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  820. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  821. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  822. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  823. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  824. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  825. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  826. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  827. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  828. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  829. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  830. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  831. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  832. wandb/viz.py +123 -0
  833. wandb/wandb_agent.py +586 -0
  834. wandb/wandb_controller.py +720 -0
  835. wandb/wandb_run.py +9 -0
  836. wandb/wandb_torch.py +550 -0
  837. wandb/xgboost/__init__.py +9 -0
  838. wandb-0.17.0rc1.dist-info/METADATA +219 -0
  839. wandb-0.17.0rc1.dist-info/RECORD +842 -0
  840. wandb-0.17.0rc1.dist-info/WHEEL +4 -0
  841. wandb-0.17.0rc1.dist-info/entry_points.txt +3 -0
  842. wandb-0.17.0rc1.dist-info/licenses/LICENSE +21 -0
wandb/sdk/wandb_run.py ADDED
@@ -0,0 +1,4191 @@
1
+ import _thread as thread
2
+ import atexit
3
+ import functools
4
+ import glob
5
+ import json
6
+ import logging
7
+ import numbers
8
+ import os
9
+ import pathlib
10
+ import re
11
+ import sys
12
+ import threading
13
+ import time
14
+ import traceback
15
+ import warnings
16
+ from collections.abc import Mapping
17
+ from dataclasses import dataclass, field
18
+ from datetime import datetime, timedelta, timezone
19
+ from enum import IntEnum
20
+ from types import TracebackType
21
+ from typing import (
22
+ TYPE_CHECKING,
23
+ Any,
24
+ Callable,
25
+ Dict,
26
+ List,
27
+ NamedTuple,
28
+ Optional,
29
+ Sequence,
30
+ TextIO,
31
+ Tuple,
32
+ Type,
33
+ Union,
34
+ )
35
+
36
+ import requests
37
+
38
+ import wandb
39
+ import wandb.env
40
+ from wandb import errors, trigger
41
+ from wandb._globals import _datatypes_set_callback
42
+ from wandb.apis import internal, public
43
+ from wandb.apis.internal import Api
44
+ from wandb.apis.public import Api as PublicApi
45
+ from wandb.proto.wandb_internal_pb2 import (
46
+ MetricRecord,
47
+ PollExitResponse,
48
+ Result,
49
+ RunRecord,
50
+ ServerInfoResponse,
51
+ )
52
+ from wandb.sdk.artifacts.artifact import Artifact
53
+ from wandb.sdk.internal import job_builder
54
+ from wandb.sdk.lib.import_hooks import (
55
+ register_post_import_hook,
56
+ unregister_post_import_hook,
57
+ )
58
+ from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath
59
+ from wandb.util import (
60
+ _is_artifact_object,
61
+ _is_artifact_string,
62
+ _is_artifact_version_weave_dict,
63
+ _is_py_or_dockerfile,
64
+ _resolve_aliases,
65
+ add_import_hook,
66
+ parse_artifact_string,
67
+ )
68
+ from wandb.viz import CustomChart, Visualize, custom_chart
69
+
70
+ from . import wandb_config, wandb_metric, wandb_summary
71
+ from .data_types._dtypes import TypeRegistry
72
+ from .interface.interface import GlobStr, InterfaceBase
73
+ from .interface.summary_record import SummaryRecord
74
+ from .lib import (
75
+ config_util,
76
+ deprecate,
77
+ filenames,
78
+ filesystem,
79
+ ipython,
80
+ module,
81
+ proto_util,
82
+ redirect,
83
+ telemetry,
84
+ )
85
+ from .lib.exit_hooks import ExitHooks
86
+ from .lib.gitlib import GitRepo
87
+ from .lib.mailbox import MailboxError, MailboxHandle, MailboxProbe, MailboxProgress
88
+ from .lib.printer import get_printer
89
+ from .lib.proto_util import message_to_dict
90
+ from .lib.reporting import Reporter
91
+ from .lib.wburls import wburls
92
+ from .wandb_settings import Settings
93
+ from .wandb_setup import _WandbSetup
94
+
95
+ if TYPE_CHECKING:
96
+ if sys.version_info >= (3, 8):
97
+ from typing import TypedDict
98
+ else:
99
+ from typing_extensions import TypedDict
100
+
101
+ import wandb.apis.public
102
+ import wandb.sdk.backend.backend
103
+ import wandb.sdk.interface.interface_queue
104
+ from wandb.proto.wandb_internal_pb2 import (
105
+ CheckVersionResponse,
106
+ GetSummaryResponse,
107
+ InternalMessagesResponse,
108
+ SampledHistoryResponse,
109
+ )
110
+
111
+ from .interface.interface import FilesDict, PolicyName
112
+ from .lib.printer import PrinterJupyter, PrinterTerm
113
+ from .wandb_alerts import AlertLevel
114
+
115
+ class GitSourceDict(TypedDict):
116
+ remote: str
117
+ commit: str
118
+ entrypoint: List[str]
119
+ args: Sequence[str]
120
+
121
+ class ArtifactSourceDict(TypedDict):
122
+ artifact: str
123
+ entrypoint: List[str]
124
+ args: Sequence[str]
125
+
126
+ class ImageSourceDict(TypedDict):
127
+ image: str
128
+ args: Sequence[str]
129
+
130
+ class JobSourceDict(TypedDict, total=False):
131
+ _version: str
132
+ source_type: str
133
+ source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict]
134
+ input_types: Dict[str, Any]
135
+ output_types: Dict[str, Any]
136
+ runtime: Optional[str]
137
+
138
+
139
+ logger = logging.getLogger("wandb")
140
+ EXIT_TIMEOUT = 60
141
+ RE_LABEL = re.compile(r"[a-zA-Z0-9_-]+$")
142
+
143
+
144
+ class TeardownStage(IntEnum):
145
+ EARLY = 1
146
+ LATE = 2
147
+
148
+
149
+ class TeardownHook(NamedTuple):
150
+ call: Callable[[], None]
151
+ stage: TeardownStage
152
+
153
+
154
+ class RunStatusChecker:
155
+ """Periodically polls the background process for relevant updates.
156
+
157
+ - check if the user has requested a stop.
158
+ - check the network status.
159
+ - check the run sync status.
160
+ """
161
+
162
+ _stop_status_lock: threading.Lock
163
+ _stop_status_handle: Optional[MailboxHandle]
164
+ _network_status_lock: threading.Lock
165
+ _network_status_handle: Optional[MailboxHandle]
166
+ _internal_messages_lock: threading.Lock
167
+ _internal_messages_handle: Optional[MailboxHandle]
168
+
169
+ def __init__(
170
+ self,
171
+ interface: InterfaceBase,
172
+ stop_polling_interval: int = 15,
173
+ retry_polling_interval: int = 5,
174
+ ) -> None:
175
+ self._interface = interface
176
+ self._stop_polling_interval = stop_polling_interval
177
+ self._retry_polling_interval = retry_polling_interval
178
+
179
+ self._join_event = threading.Event()
180
+
181
+ self._stop_status_lock = threading.Lock()
182
+ self._stop_status_handle = None
183
+ self._stop_thread = threading.Thread(
184
+ target=self.check_stop_status,
185
+ name="ChkStopThr",
186
+ daemon=True,
187
+ )
188
+
189
+ self._network_status_lock = threading.Lock()
190
+ self._network_status_handle = None
191
+ self._network_status_thread = threading.Thread(
192
+ target=self.check_network_status,
193
+ name="NetStatThr",
194
+ daemon=True,
195
+ )
196
+
197
+ self._internal_messages_lock = threading.Lock()
198
+ self._internal_messages_handle = None
199
+ self._internal_messages_thread = threading.Thread(
200
+ target=self.check_internal_messages,
201
+ name="IntMsgThr",
202
+ daemon=True,
203
+ )
204
+
205
+ def start(self) -> None:
206
+ self._stop_thread.start()
207
+ self._network_status_thread.start()
208
+ self._internal_messages_thread.start()
209
+
210
+ def _loop_check_status(
211
+ self,
212
+ *,
213
+ lock: threading.Lock,
214
+ set_handle: Any,
215
+ timeout: int,
216
+ request: Any,
217
+ process: Any,
218
+ ) -> None:
219
+ local_handle: Optional[MailboxHandle] = None
220
+ join_requested = False
221
+ while not join_requested:
222
+ time_probe = time.monotonic()
223
+ if not local_handle:
224
+ local_handle = request()
225
+ assert local_handle
226
+
227
+ with lock:
228
+ if self._join_event.is_set():
229
+ return
230
+ set_handle(local_handle)
231
+ try:
232
+ result = local_handle.wait(timeout=timeout)
233
+ except MailboxError:
234
+ # background threads are oportunistically getting results
235
+ # from the internal process but the internal process could
236
+ # be shutdown at any time. In this case assume that the
237
+ # thread should exit silently. This is possible
238
+ # because we do not have an atexit handler for the user
239
+ # process which quiesces active threads.
240
+ break
241
+ with lock:
242
+ set_handle(None)
243
+
244
+ if result:
245
+ process(result)
246
+ # if request finished, clear the handle to send on the next interval
247
+ local_handle = None
248
+
249
+ time_elapsed = time.monotonic() - time_probe
250
+ wait_time = max(self._stop_polling_interval - time_elapsed, 0)
251
+ join_requested = self._join_event.wait(timeout=wait_time)
252
+
253
+ def check_network_status(self) -> None:
254
+ def _process_network_status(result: Result) -> None:
255
+ network_status = result.response.network_status_response
256
+ for hr in network_status.network_responses:
257
+ if (
258
+ hr.http_status_code == 200 or hr.http_status_code == 0
259
+ ): # we use 0 for non-http errors (eg wandb errors)
260
+ wandb.termlog(f"{hr.http_response_text}")
261
+ else:
262
+ wandb.termlog(
263
+ "{} encountered ({}), retrying request".format(
264
+ hr.http_status_code, hr.http_response_text.rstrip()
265
+ )
266
+ )
267
+
268
+ self._loop_check_status(
269
+ lock=self._network_status_lock,
270
+ set_handle=lambda x: setattr(self, "_network_status_handle", x),
271
+ timeout=self._retry_polling_interval,
272
+ request=self._interface.deliver_network_status,
273
+ process=_process_network_status,
274
+ )
275
+
276
+ def check_stop_status(self) -> None:
277
+ def _process_stop_status(result: Result) -> None:
278
+ stop_status = result.response.stop_status_response
279
+ if stop_status.run_should_stop:
280
+ # TODO(frz): This check is required
281
+ # until WB-3606 is resolved on server side.
282
+ if not wandb.agents.pyagent.is_running():
283
+ thread.interrupt_main()
284
+ return
285
+
286
+ self._loop_check_status(
287
+ lock=self._stop_status_lock,
288
+ set_handle=lambda x: setattr(self, "_stop_status_handle", x),
289
+ timeout=self._stop_polling_interval,
290
+ request=self._interface.deliver_stop_status,
291
+ process=_process_stop_status,
292
+ )
293
+
294
+ def check_internal_messages(self) -> None:
295
+ def _process_internal_messages(result: Result) -> None:
296
+ internal_messages = result.response.internal_messages_response
297
+ for msg in internal_messages.messages.warning:
298
+ wandb.termwarn(msg)
299
+
300
+ self._loop_check_status(
301
+ lock=self._internal_messages_lock,
302
+ set_handle=lambda x: setattr(self, "_internal_messages_handle", x),
303
+ timeout=1,
304
+ request=self._interface.deliver_internal_messages,
305
+ process=_process_internal_messages,
306
+ )
307
+
308
+ def stop(self) -> None:
309
+ self._join_event.set()
310
+ with self._stop_status_lock:
311
+ if self._stop_status_handle:
312
+ self._stop_status_handle.abandon()
313
+ with self._network_status_lock:
314
+ if self._network_status_handle:
315
+ self._network_status_handle.abandon()
316
+ with self._internal_messages_lock:
317
+ if self._internal_messages_handle:
318
+ self._internal_messages_handle.abandon()
319
+
320
+ def join(self) -> None:
321
+ self.stop()
322
+ self._stop_thread.join()
323
+ self._network_status_thread.join()
324
+ self._internal_messages_thread.join()
325
+
326
+
327
+ class _run_decorator: # noqa: N801
328
+ _is_attaching: str = ""
329
+
330
+ class Dummy: ...
331
+
332
+ @classmethod
333
+ def _attach(cls, func: Callable) -> Callable:
334
+ @functools.wraps(func)
335
+ def wrapper(self: Type["Run"], *args: Any, **kwargs: Any) -> Any:
336
+ # * `_attach_id` is only assigned in service hence for all non-service cases
337
+ # it will be a passthrough.
338
+ # * `_attach_pid` is only assigned in _init (using _attach_pid guarantees single attach):
339
+ # - for non-fork case the object is shared through pickling so will be None.
340
+ # - for fork case the new process share mem space hence the value would be of parent process.
341
+ if (
342
+ getattr(self, "_attach_id", None)
343
+ and getattr(self, "_attach_pid", None) != os.getpid()
344
+ ):
345
+ if cls._is_attaching:
346
+ message = (
347
+ f"Trying to attach `{func.__name__}` "
348
+ f"while in the middle of attaching `{cls._is_attaching}`"
349
+ )
350
+ raise RuntimeError(message)
351
+ cls._is_attaching = func.__name__
352
+ try:
353
+ wandb._attach(run=self) # type: ignore
354
+ except Exception as e:
355
+ # In case the attach fails we will raise the exception that caused the issue.
356
+ # This exception should be caught and fail the execution of the program.
357
+ cls._is_attaching = ""
358
+ raise e
359
+ cls._is_attaching = ""
360
+ return func(self, *args, **kwargs)
361
+
362
+ return wrapper
363
+
364
+ @classmethod
365
+ def _noop_on_finish(cls, message: str = "", only_warn: bool = False) -> Callable:
366
+ def decorator_fn(func: Callable) -> Callable:
367
+ @functools.wraps(func)
368
+ def wrapper_fn(self: Type["Run"], *args: Any, **kwargs: Any) -> Any:
369
+ if not getattr(self, "_is_finished", False):
370
+ return func(self, *args, **kwargs)
371
+
372
+ default_message = (
373
+ f"Run ({self.id}) is finished. The call to `{func.__name__}` will be ignored. "
374
+ f"Please make sure that you are using an active run."
375
+ )
376
+ resolved_message = message or default_message
377
+ if only_warn:
378
+ warnings.warn(resolved_message, UserWarning, stacklevel=2)
379
+ else:
380
+ raise errors.UsageError(resolved_message)
381
+
382
+ return wrapper_fn
383
+
384
+ return decorator_fn
385
+
386
+ @classmethod
387
+ def _noop(cls, func: Callable) -> Callable:
388
+ @functools.wraps(func)
389
+ def wrapper(self: Type["Run"], *args: Any, **kwargs: Any) -> Any:
390
+ # `_attach_id` is only assigned in service hence for all service cases
391
+ # it will be a passthrough. We don't pickle non-service so again a way
392
+ # to see that we are in non-service case
393
+ if getattr(self, "_attach_id", None) is None:
394
+ # `_init_pid` is only assigned in __init__ (this will be constant check for mp):
395
+ # - for non-fork case the object is shared through pickling,
396
+ # and we don't pickle non-service so will be None
397
+ # - for fork case the new process share mem space hence the value would be of parent process.
398
+ _init_pid = getattr(self, "_init_pid", None)
399
+ if _init_pid != os.getpid():
400
+ message = "`{}` ignored (called from pid={}, `init` called from pid={}). See: {}".format(
401
+ func.__name__,
402
+ os.getpid(),
403
+ _init_pid,
404
+ wburls.get("multiprocess"),
405
+ )
406
+ # - if this process was pickled in non-service case,
407
+ # we ignore the attributes (since pickle is not supported)
408
+ # - for fork case will use the settings of the parent process
409
+ # - only point of inconsistent behavior from forked and non-forked cases
410
+ settings = getattr(self, "_settings", None)
411
+ if settings and settings["strict"]:
412
+ wandb.termerror(message, repeat=False)
413
+ raise errors.UnsupportedError(
414
+ f"`{func.__name__}` does not support multiprocessing"
415
+ )
416
+ wandb.termwarn(message, repeat=False)
417
+ return cls.Dummy()
418
+
419
+ return func(self, *args, **kwargs)
420
+
421
+ return wrapper
422
+
423
+
424
+ @dataclass
425
+ class RunStatus:
426
+ sync_items_total: int = field(default=0)
427
+ sync_items_pending: int = field(default=0)
428
+ sync_time: Optional[datetime] = field(default=None)
429
+
430
+
431
+ class Run:
432
+ """A unit of computation logged by wandb. Typically, this is an ML experiment.
433
+
434
+ Create a run with `wandb.init()`:
435
+ <!--yeadoc-test:run-object-basic-->
436
+ ```python
437
+ import wandb
438
+
439
+ run = wandb.init()
440
+ ```
441
+
442
+ There is only ever at most one active `wandb.Run` in any process,
443
+ and it is accessible as `wandb.run`:
444
+ <!--yeadoc-test:global-run-object-->
445
+ ```python
446
+ import wandb
447
+
448
+ assert wandb.run is None
449
+
450
+ wandb.init()
451
+
452
+ assert wandb.run is not None
453
+ ```
454
+ anything you log with `wandb.log` will be sent to that run.
455
+
456
+ If you want to start more runs in the same script or notebook, you'll need to
457
+ finish the run that is in-flight. Runs can be finished with `wandb.finish` or
458
+ by using them in a `with` block:
459
+ <!--yeadoc-test:run-context-manager-->
460
+ ```python
461
+ import wandb
462
+
463
+ wandb.init()
464
+ wandb.finish()
465
+
466
+ assert wandb.run is None
467
+
468
+ with wandb.init() as run:
469
+ pass # log data here
470
+
471
+ assert wandb.run is None
472
+ ```
473
+
474
+ See the documentation for `wandb.init` for more on creating runs, or check out
475
+ [our guide to `wandb.init`](https://docs.wandb.ai/guides/track/launch).
476
+
477
+ In distributed training, you can either create a single run in the rank 0 process
478
+ and then log information only from that process, or you can create a run in each process,
479
+ logging from each separately, and group the results together with the `group` argument
480
+ to `wandb.init`. For more details on distributed training with W&B, check out
481
+ [our guide](https://docs.wandb.ai/guides/track/log/distributed-training).
482
+
483
+ Currently, there is a parallel `Run` object in the `wandb.Api`. Eventually these
484
+ two objects will be merged.
485
+
486
+ Attributes:
487
+ summary: (Summary) Single values set for each `wandb.log()` key. By
488
+ default, summary is set to the last value logged. You can manually
489
+ set summary to the best value, like max accuracy, instead of the
490
+ final value.
491
+ """
492
+
493
+ _telemetry_obj: telemetry.TelemetryRecord
494
+ _telemetry_obj_active: bool
495
+ _telemetry_obj_dirty: bool
496
+ _telemetry_obj_flushed: bytes
497
+
498
+ _teardown_hooks: List[TeardownHook]
499
+ _tags: Optional[Tuple[Any, ...]]
500
+
501
+ _entity: Optional[str]
502
+ _project: Optional[str]
503
+ _group: Optional[str]
504
+ _job_type: Optional[str]
505
+ _name: Optional[str]
506
+ _notes: Optional[str]
507
+ _sweep_id: Optional[str]
508
+
509
+ _run_obj: Optional[RunRecord]
510
+ # Use string literal annotation because of type reference loop
511
+ _backend: Optional["wandb.sdk.backend.backend.Backend"]
512
+ _internal_run_interface: Optional[
513
+ "wandb.sdk.interface.interface_queue.InterfaceQueue"
514
+ ]
515
+ _wl: Optional[_WandbSetup]
516
+
517
+ _out_redir: Optional[redirect.RedirectBase]
518
+ _err_redir: Optional[redirect.RedirectBase]
519
+ _redirect_cb: Optional[Callable[[str, str], None]]
520
+ _redirect_raw_cb: Optional[Callable[[str, str], None]]
521
+ _output_writer: Optional["filesystem.CRDedupedFile"]
522
+ _quiet: Optional[bool]
523
+
524
+ _atexit_cleanup_called: bool
525
+ _hooks: Optional[ExitHooks]
526
+ _exit_code: Optional[int]
527
+
528
+ _run_status_checker: Optional[RunStatusChecker]
529
+
530
+ _check_version: Optional["CheckVersionResponse"]
531
+ _sampled_history: Optional["SampledHistoryResponse"]
532
+ _final_summary: Optional["GetSummaryResponse"]
533
+ _poll_exit_handle: Optional[MailboxHandle]
534
+ _poll_exit_response: Optional[PollExitResponse]
535
+ _server_info_response: Optional[ServerInfoResponse]
536
+ _internal_messages_response: Optional["InternalMessagesResponse"]
537
+
538
+ _stdout_slave_fd: Optional[int]
539
+ _stderr_slave_fd: Optional[int]
540
+ _artifact_slots: List[str]
541
+
542
+ _init_pid: int
543
+ _attach_pid: int
544
+ _iface_pid: Optional[int]
545
+ _iface_port: Optional[int]
546
+
547
+ _attach_id: Optional[str]
548
+ _is_attached: bool
549
+ _is_finished: bool
550
+ _settings: Settings
551
+
552
+ _launch_artifacts: Optional[Dict[str, Any]]
553
+ _printer: Union["PrinterTerm", "PrinterJupyter"]
554
+
555
+ def __init__(
556
+ self,
557
+ settings: Settings,
558
+ config: Optional[Dict[str, Any]] = None,
559
+ sweep_config: Optional[Dict[str, Any]] = None,
560
+ launch_config: Optional[Dict[str, Any]] = None,
561
+ ) -> None:
562
+ # pid is set, so we know if this run object was initialized by this process
563
+ self._init_pid = os.getpid()
564
+ self._init(
565
+ settings=settings,
566
+ config=config,
567
+ sweep_config=sweep_config,
568
+ launch_config=launch_config,
569
+ )
570
+
571
+ def _init(
572
+ self,
573
+ settings: Settings,
574
+ config: Optional[Dict[str, Any]] = None,
575
+ sweep_config: Optional[Dict[str, Any]] = None,
576
+ launch_config: Optional[Dict[str, Any]] = None,
577
+ ) -> None:
578
+ self._settings = settings
579
+ self._config = wandb_config.Config()
580
+ self._config._set_callback(self._config_callback)
581
+ self._config._set_artifact_callback(self._config_artifact_callback)
582
+ self._config._set_settings(self._settings)
583
+ self._backend = None
584
+ self._internal_run_interface = None
585
+ # todo: perhaps this should be a property that is a noop on a finished run
586
+ self.summary = wandb_summary.Summary(
587
+ self._summary_get_current_summary_callback,
588
+ )
589
+ self.summary._set_update_callback(self._summary_update_callback)
590
+ self._step = 0
591
+ self._torch_history: Optional[wandb.wandb_torch.TorchHistory] = None
592
+
593
+ # todo: eventually would be nice to make this configurable using self._settings._start_time
594
+ # need to test (jhr): if you set start time to 2 days ago and run a test for 15 minutes,
595
+ # does the total time get calculated right (not as 2 days and 15 minutes)?
596
+ self._start_time = time.time()
597
+
598
+ _datatypes_set_callback(self._datatypes_callback)
599
+
600
+ self._printer = get_printer(self._settings._jupyter)
601
+ self._wl = None
602
+ self._reporter: Optional[Reporter] = None
603
+
604
+ self._entity = None
605
+ self._project = None
606
+ self._group = None
607
+ self._job_type = None
608
+ self._run_id = self._settings.run_id
609
+ self._starting_step = 0
610
+ self._name = None
611
+ self._notes = None
612
+ self._tags = None
613
+ self._remote_url = None
614
+ self._commit = None
615
+ self._sweep_id = None
616
+
617
+ self._hooks = None
618
+ self._teardown_hooks = []
619
+ self._out_redir = None
620
+ self._err_redir = None
621
+ self._stdout_slave_fd = None
622
+ self._stderr_slave_fd = None
623
+ self._exit_code = None
624
+ self._exit_result = None
625
+ self._quiet = self._settings.quiet
626
+
627
+ self._output_writer = None
628
+ self._used_artifact_slots: Dict[str, str] = {}
629
+
630
+ # Returned from backend request_run(), set from wandb_init?
631
+ self._run_obj = None
632
+
633
+ # Created when the run "starts".
634
+ self._run_status_checker = None
635
+
636
+ self._check_version = None
637
+ self._sampled_history = None
638
+ self._final_summary = None
639
+ self._poll_exit_response = None
640
+ self._server_info_response = None
641
+ self._internal_messages_response = None
642
+ self._poll_exit_handle = None
643
+
644
+ # Initialize telemetry object
645
+ self._telemetry_obj = telemetry.TelemetryRecord()
646
+ self._telemetry_obj_active = False
647
+ self._telemetry_obj_flushed = b""
648
+ self._telemetry_obj_dirty = False
649
+
650
+ self._atexit_cleanup_called = False
651
+
652
+ # Pull info from settings
653
+ self._init_from_settings(self._settings)
654
+
655
+ # Initial scope setup for sentry.
656
+ # This might get updated when the actual run comes back.
657
+ wandb._sentry.configure_scope(
658
+ tags=dict(self._settings),
659
+ process_context="user",
660
+ )
661
+
662
+ # Populate config
663
+ config = config or dict()
664
+ wandb_key = "_wandb"
665
+ config.setdefault(wandb_key, dict())
666
+ self._launch_artifact_mapping: Dict[str, Any] = {}
667
+ self._unique_launch_artifact_sequence_names: Dict[str, Any] = {}
668
+ if self._settings.save_code and self._settings.program_relpath:
669
+ config[wandb_key]["code_path"] = LogicalPath(
670
+ os.path.join("code", self._settings.program_relpath)
671
+ )
672
+
673
+ if self._settings.fork_from is not None:
674
+ config[wandb_key]["branch_point"] = {
675
+ "run_id": self._settings.fork_from.run,
676
+ "step": self._settings.fork_from.value,
677
+ }
678
+
679
+ self._config._update(config, ignore_locked=True)
680
+
681
+ if sweep_config:
682
+ self._config.merge_locked(
683
+ sweep_config, user="sweep", _allow_val_change=True
684
+ )
685
+
686
+ if launch_config:
687
+ self._config.merge_locked(
688
+ launch_config, user="launch", _allow_val_change=True
689
+ )
690
+
691
+ # if run is from a launch queue, add queue id to _wandb config
692
+ launch_queue_name = wandb.env.get_launch_queue_name()
693
+ if launch_queue_name:
694
+ self._config[wandb_key]["launch_queue_name"] = launch_queue_name
695
+
696
+ launch_queue_entity = wandb.env.get_launch_queue_entity()
697
+ if launch_queue_entity:
698
+ self._config[wandb_key]["launch_queue_entity"] = launch_queue_entity
699
+
700
+ launch_trace_id = wandb.env.get_launch_trace_id()
701
+ if launch_trace_id:
702
+ self._config[wandb_key]["launch_trace_id"] = launch_trace_id
703
+
704
+ # interface pid and port configured when backend is configured (See _hack_set_run)
705
+ # TODO: using pid isn't the best for windows as pid reuse can happen more often than unix
706
+ self._iface_pid = None
707
+ self._iface_port = None
708
+ self._attach_id = None
709
+ self._is_attached = False
710
+ self._is_finished = False
711
+
712
+ self._attach_pid = os.getpid()
713
+
714
+ # for now, use runid as attach id, this could/should be versioned in the future
715
+ if not self._settings._disable_service:
716
+ self._attach_id = self._settings.run_id
717
+
718
+ def _set_iface_pid(self, iface_pid: int) -> None:
719
+ self._iface_pid = iface_pid
720
+
721
+ def _set_iface_port(self, iface_port: int) -> None:
722
+ self._iface_port = iface_port
723
+
724
+ def _handle_launch_artifact_overrides(self) -> None:
725
+ if self._settings.launch and (os.environ.get("WANDB_ARTIFACTS") is not None):
726
+ try:
727
+ artifacts: Dict[str, Any] = json.loads(
728
+ os.environ.get("WANDB_ARTIFACTS", "{}")
729
+ )
730
+ except (ValueError, SyntaxError):
731
+ wandb.termwarn("Malformed WANDB_ARTIFACTS, using original artifacts")
732
+ else:
733
+ self._initialize_launch_artifact_maps(artifacts)
734
+
735
+ elif (
736
+ self._settings.launch
737
+ and self._settings.launch_config_path
738
+ and os.path.exists(self._settings.launch_config_path)
739
+ ):
740
+ self.save(self._settings.launch_config_path)
741
+ with open(self._settings.launch_config_path) as fp:
742
+ launch_config = json.loads(fp.read())
743
+ if launch_config.get("overrides", {}).get("artifacts") is not None:
744
+ artifacts = launch_config.get("overrides").get("artifacts")
745
+ self._initialize_launch_artifact_maps(artifacts)
746
+
747
+ def _initialize_launch_artifact_maps(self, artifacts: Dict[str, Any]) -> None:
748
+ for key, item in artifacts.items():
749
+ self._launch_artifact_mapping[key] = item
750
+ artifact_sequence_tuple_or_slot = key.split(":")
751
+
752
+ if len(artifact_sequence_tuple_or_slot) == 2:
753
+ sequence_name = artifact_sequence_tuple_or_slot[0].split("/")[-1]
754
+ if self._unique_launch_artifact_sequence_names.get(sequence_name):
755
+ self._unique_launch_artifact_sequence_names.pop(sequence_name)
756
+ else:
757
+ self._unique_launch_artifact_sequence_names[sequence_name] = item
758
+
759
+ def _telemetry_callback(self, telem_obj: telemetry.TelemetryRecord) -> None:
760
+ self._telemetry_obj.MergeFrom(telem_obj)
761
+ self._telemetry_obj_dirty = True
762
+ self._telemetry_flush()
763
+
764
+ def _telemetry_flush(self) -> None:
765
+ if not self._telemetry_obj_active:
766
+ return
767
+ if not self._telemetry_obj_dirty:
768
+ return
769
+ if self._backend and self._backend.interface:
770
+ serialized = self._telemetry_obj.SerializeToString()
771
+ if serialized == self._telemetry_obj_flushed:
772
+ return
773
+ self._backend.interface._publish_telemetry(self._telemetry_obj)
774
+ self._telemetry_obj_flushed = serialized
775
+ self._telemetry_obj_dirty = False
776
+
777
+ def _freeze(self) -> None:
778
+ self._frozen = True
779
+
780
+ def __setattr__(self, attr: str, value: object) -> None:
781
+ if getattr(self, "_frozen", None) and not hasattr(self, attr):
782
+ raise Exception(f"Attribute {attr} is not supported on Run object.")
783
+ super().__setattr__(attr, value)
784
+
785
+ def _update_settings(self, settings: Settings) -> None:
786
+ self._settings = settings
787
+ self._init_from_settings(settings)
788
+
789
+ def _init_from_settings(self, settings: Settings) -> None:
790
+ if settings.entity is not None:
791
+ self._entity = settings.entity
792
+ if settings.project is not None:
793
+ self._project = settings.project
794
+ if settings.run_group is not None:
795
+ self._group = settings.run_group
796
+ if settings.run_job_type is not None:
797
+ self._job_type = settings.run_job_type
798
+ if settings.run_name is not None:
799
+ self._name = settings.run_name
800
+ if settings.run_notes is not None:
801
+ self._notes = settings.run_notes
802
+ if settings.run_tags is not None:
803
+ self._tags = settings.run_tags
804
+ if settings.sweep_id is not None:
805
+ self._sweep_id = settings.sweep_id
806
+
807
+ def _make_proto_run(self, run: RunRecord) -> None:
808
+ """Populate protocol buffer RunData for interface/interface."""
809
+ if self._entity is not None:
810
+ run.entity = self._entity
811
+ if self._project is not None:
812
+ run.project = self._project
813
+ if self._group is not None:
814
+ run.run_group = self._group
815
+ if self._job_type is not None:
816
+ run.job_type = self._job_type
817
+ if self._run_id is not None:
818
+ run.run_id = self._run_id
819
+ if self._name is not None:
820
+ run.display_name = self._name
821
+ if self._notes is not None:
822
+ run.notes = self._notes
823
+ if self._tags is not None:
824
+ for tag in self._tags:
825
+ run.tags.append(tag)
826
+ if self._start_time is not None:
827
+ run.start_time.FromMicroseconds(int(self._start_time * 1e6))
828
+ if self._remote_url is not None:
829
+ run.git.remote_url = self._remote_url
830
+ if self._commit is not None:
831
+ run.git.commit = self._commit
832
+ if self._sweep_id is not None:
833
+ run.sweep_id = self._sweep_id
834
+ # Note: run.config is set in interface/interface:_make_run()
835
+
836
+ def _populate_git_info(self) -> None:
837
+ # Use user provided git info if available otherwise resolve it from the environment
838
+ try:
839
+ repo = GitRepo(
840
+ root=self._settings.git_root,
841
+ remote=self._settings.git_remote,
842
+ remote_url=self._settings.git_remote_url,
843
+ commit=self._settings.git_commit,
844
+ lazy=False,
845
+ )
846
+ self._remote_url, self._commit = repo.remote_url, repo.last_commit
847
+ except Exception:
848
+ wandb.termwarn("Cannot find valid git repo associated with this directory.")
849
+
850
+ def __deepcopy__(self, memo: Dict[int, Any]) -> "Run":
851
+ return self
852
+
853
+ def __getstate__(self) -> Any:
854
+ """Return run state as a custom pickle."""
855
+ # We only pickle in service mode
856
+ if not self._settings or self._settings._disable_service:
857
+ return
858
+
859
+ _attach_id = self._attach_id
860
+ if not _attach_id:
861
+ return
862
+
863
+ return dict(
864
+ _attach_id=_attach_id,
865
+ _init_pid=self._init_pid,
866
+ _is_finished=self._is_finished,
867
+ )
868
+
869
+ def __setstate__(self, state: Any) -> None:
870
+ """Set run state from a custom pickle."""
871
+ if not state:
872
+ return
873
+
874
+ _attach_id = state.get("_attach_id")
875
+ if not _attach_id:
876
+ return
877
+
878
+ if state["_init_pid"] == os.getpid():
879
+ raise RuntimeError("attach in the same process is not supported currently")
880
+
881
+ self.__dict__.update(state)
882
+
883
+ @property
884
+ def _torch(self) -> "wandb.wandb_torch.TorchHistory":
885
+ if self._torch_history is None:
886
+ self._torch_history = wandb.wandb_torch.TorchHistory()
887
+ return self._torch_history
888
+
889
+ @property
890
+ @_run_decorator._attach
891
+ def settings(self) -> Settings:
892
+ """A frozen copy of run's Settings object."""
893
+ cp = self._settings.copy()
894
+ cp.freeze()
895
+ return cp
896
+
897
+ @property
898
+ @_run_decorator._attach
899
+ def dir(self) -> str:
900
+ """The directory where files associated with the run are saved."""
901
+ return self._settings.files_dir
902
+
903
+ @property
904
+ @_run_decorator._attach
905
+ def config(self) -> wandb_config.Config:
906
+ """Config object associated with this run."""
907
+ return self._config
908
+
909
+ @property
910
+ @_run_decorator._attach
911
+ def config_static(self) -> wandb_config.ConfigStatic:
912
+ return wandb_config.ConfigStatic(self._config)
913
+
914
+ @property
915
+ @_run_decorator._attach
916
+ def name(self) -> Optional[str]:
917
+ """Display name of the run.
918
+
919
+ Display names are not guaranteed to be unique and may be descriptive.
920
+ By default, they are randomly generated.
921
+ """
922
+ if self._name:
923
+ return self._name
924
+ if not self._run_obj:
925
+ return None
926
+ return self._run_obj.display_name
927
+
928
+ @name.setter
929
+ @_run_decorator._noop_on_finish()
930
+ def name(self, name: str) -> None:
931
+ with telemetry.context(run=self) as tel:
932
+ tel.feature.set_run_name = True
933
+ self._name = name
934
+ if self._backend and self._backend.interface:
935
+ self._backend.interface.publish_run(self)
936
+
937
+ @property
938
+ @_run_decorator._attach
939
+ def notes(self) -> Optional[str]:
940
+ """Notes associated with the run, if there are any.
941
+
942
+ Notes can be a multiline string and can also use markdown and latex equations
943
+ inside `$$`, like `$x + 3$`.
944
+ """
945
+ if self._notes:
946
+ return self._notes
947
+ if not self._run_obj:
948
+ return None
949
+ return self._run_obj.notes
950
+
951
+ @notes.setter
952
+ @_run_decorator._noop_on_finish()
953
+ def notes(self, notes: str) -> None:
954
+ self._notes = notes
955
+ if self._backend and self._backend.interface:
956
+ self._backend.interface.publish_run(self)
957
+
958
+ @property
959
+ @_run_decorator._attach
960
+ def tags(self) -> Optional[Tuple]:
961
+ """Tags associated with the run, if there are any."""
962
+ if self._tags:
963
+ return self._tags
964
+ if self._run_obj:
965
+ return tuple(self._run_obj.tags)
966
+ return None
967
+
968
+ @tags.setter
969
+ @_run_decorator._noop_on_finish()
970
+ def tags(self, tags: Sequence) -> None:
971
+ with telemetry.context(run=self) as tel:
972
+ tel.feature.set_run_tags = True
973
+ self._tags = tuple(tags)
974
+ if self._backend and self._backend.interface:
975
+ self._backend.interface.publish_run(self)
976
+
977
+ @property
978
+ @_run_decorator._attach
979
+ def id(self) -> str:
980
+ """Identifier for this run."""
981
+ if TYPE_CHECKING:
982
+ assert self._run_id is not None
983
+ return self._run_id
984
+
985
+ @property
986
+ @_run_decorator._attach
987
+ def sweep_id(self) -> Optional[str]:
988
+ """ID of the sweep associated with the run, if there is one."""
989
+ if not self._run_obj:
990
+ return None
991
+ return self._run_obj.sweep_id or None
992
+
993
+ def _get_path(self) -> str:
994
+ parts = [
995
+ e for e in [self._entity, self._project, self._run_id] if e is not None
996
+ ]
997
+ return "/".join(parts)
998
+
999
+ @property
1000
+ @_run_decorator._attach
1001
+ def path(self) -> str:
1002
+ """Path to the run.
1003
+
1004
+ Run paths include entity, project, and run ID, in the format
1005
+ `entity/project/run_id`.
1006
+ """
1007
+ return self._get_path()
1008
+
1009
+ def _get_start_time(self) -> float:
1010
+ return (
1011
+ self._start_time
1012
+ if not self._run_obj
1013
+ else (self._run_obj.start_time.ToMicroseconds() / 1e6)
1014
+ )
1015
+
1016
+ @property
1017
+ @_run_decorator._attach
1018
+ def start_time(self) -> float:
1019
+ """Unix timestamp (in seconds) of when the run started."""
1020
+ return self._get_start_time()
1021
+
1022
+ def _get_starting_step(self) -> int:
1023
+ return self._starting_step if not self._run_obj else self._run_obj.starting_step
1024
+
1025
+ @property
1026
+ @_run_decorator._attach
1027
+ def starting_step(self) -> int:
1028
+ """The first step of the run."""
1029
+ return self._get_starting_step()
1030
+
1031
+ @property
1032
+ @_run_decorator._attach
1033
+ def resumed(self) -> bool:
1034
+ """True if the run was resumed, False otherwise."""
1035
+ return self._run_obj.resumed if self._run_obj else False
1036
+
1037
+ @property
1038
+ @_run_decorator._attach
1039
+ def step(self) -> int:
1040
+ """Current value of the step.
1041
+
1042
+ This counter is incremented by `wandb.log`.
1043
+ """
1044
+ return self._step
1045
+
1046
+ def project_name(self) -> str:
1047
+ return self._run_obj.project if self._run_obj else ""
1048
+
1049
+ @property
1050
+ @_run_decorator._attach
1051
+ def mode(self) -> str:
1052
+ """For compatibility with `0.9.x` and earlier, deprecate eventually."""
1053
+ deprecate.deprecate(
1054
+ field_name=deprecate.Deprecated.run__mode,
1055
+ warning_message=(
1056
+ "The mode property of wandb.run is deprecated "
1057
+ "and will be removed in a future release."
1058
+ ),
1059
+ )
1060
+ return "dryrun" if self._settings._offline else "run"
1061
+
1062
+ @property
1063
+ @_run_decorator._attach
1064
+ def offline(self) -> bool:
1065
+ return self._settings._offline
1066
+
1067
+ @property
1068
+ @_run_decorator._attach
1069
+ def disabled(self) -> bool:
1070
+ return self._settings._noop
1071
+
1072
+ def _get_group(self) -> str:
1073
+ return self._run_obj.run_group if self._run_obj else ""
1074
+
1075
+ @property
1076
+ @_run_decorator._attach
1077
+ def group(self) -> str:
1078
+ """Name of the group associated with the run.
1079
+
1080
+ Setting a group helps the W&B UI organize runs in a sensible way.
1081
+
1082
+ If you are doing a distributed training you should give all of the
1083
+ runs in the training the same group.
1084
+ If you are doing cross-validation you should give all the cross-validation
1085
+ folds the same group.
1086
+ """
1087
+ return self._get_group()
1088
+
1089
+ @property
1090
+ @_run_decorator._attach
1091
+ def job_type(self) -> str:
1092
+ return self._run_obj.job_type if self._run_obj else ""
1093
+
1094
+ @property
1095
+ @_run_decorator._attach
1096
+ def project(self) -> str:
1097
+ """Name of the W&B project associated with the run."""
1098
+ return self.project_name()
1099
+
1100
+ @_run_decorator._noop_on_finish()
1101
+ @_run_decorator._attach
1102
+ def log_code(
1103
+ self,
1104
+ root: Optional[str] = ".",
1105
+ name: Optional[str] = None,
1106
+ include_fn: Union[
1107
+ Callable[[str, str], bool], Callable[[str], bool]
1108
+ ] = _is_py_or_dockerfile,
1109
+ exclude_fn: Union[
1110
+ Callable[[str, str], bool], Callable[[str], bool]
1111
+ ] = filenames.exclude_wandb_fn,
1112
+ ) -> Optional[Artifact]:
1113
+ """Save the current state of your code to a W&B Artifact.
1114
+
1115
+ By default, it walks the current directory and logs all files that end with `.py`.
1116
+
1117
+ Arguments:
1118
+ root: The relative (to `os.getcwd()`) or absolute path to recursively find code from.
1119
+ name: (str, optional) The name of our code artifact. By default, we'll name
1120
+ the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want
1121
+ many runs to share the same artifact. Specifying name allows you to achieve that.
1122
+ include_fn: A callable that accepts a file path and (optionally) root path and
1123
+ returns True when it should be included and False otherwise. This
1124
+ defaults to: `lambda path, root: path.endswith(".py")`
1125
+ exclude_fn: A callable that accepts a file path and (optionally) root path and
1126
+ returns `True` when it should be excluded and `False` otherwise. This
1127
+ defaults to a function that excludes all files within `<root>/.wandb/`
1128
+ and `<root>/wandb/` directories.
1129
+
1130
+ Examples:
1131
+ Basic usage
1132
+ ```python
1133
+ run.log_code()
1134
+ ```
1135
+
1136
+ Advanced usage
1137
+ ```python
1138
+ run.log_code(
1139
+ "../",
1140
+ include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"),
1141
+ exclude_fn=lambda path, root: os.path.relpath(path, root).startswith("cache/"),
1142
+ )
1143
+ ```
1144
+
1145
+ Returns:
1146
+ An `Artifact` object if code was logged
1147
+ """
1148
+ if name is None:
1149
+ if self.settings._jupyter:
1150
+ notebook_name = None
1151
+ if self.settings.notebook_name:
1152
+ notebook_name = self.settings.notebook_name
1153
+ elif self.settings._jupyter_path:
1154
+ if self.settings._jupyter_path.startswith("fileId="):
1155
+ notebook_name = self.settings._jupyter_name
1156
+ else:
1157
+ notebook_name = self.settings._jupyter_path
1158
+ name_string = f"{self._project}-{notebook_name}"
1159
+ else:
1160
+ name_string = f"{self._project}-{self._settings.program_relpath}"
1161
+ name = wandb.util.make_artifact_name_safe(f"source-{name_string}")
1162
+ art = wandb.Artifact(name, "code")
1163
+ files_added = False
1164
+ if root is not None:
1165
+ root = os.path.abspath(root)
1166
+ for file_path in filenames.filtered_dir(root, include_fn, exclude_fn):
1167
+ files_added = True
1168
+ save_name = os.path.relpath(file_path, root)
1169
+ art.add_file(file_path, name=save_name)
1170
+ # Add any manually staged files such as ipynb notebooks
1171
+ for dirpath, _, files in os.walk(self._settings._tmp_code_dir):
1172
+ for fname in files:
1173
+ file_path = os.path.join(dirpath, fname)
1174
+ save_name = os.path.relpath(file_path, self._settings._tmp_code_dir)
1175
+ files_added = True
1176
+ art.add_file(file_path, name=save_name)
1177
+ if not files_added:
1178
+ wandb.termwarn(
1179
+ "No relevant files were detected in the specified directory. No code will be logged to your run."
1180
+ )
1181
+ return None
1182
+
1183
+ return self._log_artifact(art)
1184
+
1185
+ def get_url(self) -> Optional[str]:
1186
+ """Return the url for the W&B run, if there is one.
1187
+
1188
+ Offline runs will not have a url.
1189
+ """
1190
+ if self._settings._offline:
1191
+ wandb.termwarn("URL not available in offline run")
1192
+ return None
1193
+ return self._settings.run_url
1194
+
1195
+ def get_project_url(self) -> Optional[str]:
1196
+ """Return the url for the W&B project associated with the run, if there is one.
1197
+
1198
+ Offline runs will not have a project url.
1199
+ """
1200
+ if self._settings._offline:
1201
+ wandb.termwarn("URL not available in offline run")
1202
+ return None
1203
+ return self._settings.project_url
1204
+
1205
+ def get_sweep_url(self) -> Optional[str]:
1206
+ """Return the url for the sweep associated with the run, if there is one."""
1207
+ if self._settings._offline:
1208
+ wandb.termwarn("URL not available in offline run")
1209
+ return None
1210
+ return self._settings.sweep_url
1211
+
1212
+ @property
1213
+ @_run_decorator._attach
1214
+ def url(self) -> Optional[str]:
1215
+ """The W&B url associated with the run."""
1216
+ return self.get_url()
1217
+
1218
+ @property
1219
+ @_run_decorator._attach
1220
+ def entity(self) -> str:
1221
+ """The name of the W&B entity associated with the run.
1222
+
1223
+ Entity can be a username or the name of a team or organization.
1224
+ """
1225
+ return self._entity or ""
1226
+
1227
+ def _label_internal(
1228
+ self,
1229
+ code: Optional[str] = None,
1230
+ repo: Optional[str] = None,
1231
+ code_version: Optional[str] = None,
1232
+ ) -> None:
1233
+ with telemetry.context(run=self) as tel:
1234
+ if code and RE_LABEL.match(code):
1235
+ tel.label.code_string = code
1236
+ if repo and RE_LABEL.match(repo):
1237
+ tel.label.repo_string = repo
1238
+ if code_version and RE_LABEL.match(code_version):
1239
+ tel.label.code_version = code_version
1240
+
1241
+ def _label(
1242
+ self,
1243
+ code: Optional[str] = None,
1244
+ repo: Optional[str] = None,
1245
+ code_version: Optional[str] = None,
1246
+ **kwargs: str,
1247
+ ) -> None:
1248
+ if self._settings.label_disable:
1249
+ return
1250
+ for k, v in (("code", code), ("repo", repo), ("code_version", code_version)):
1251
+ if v and not RE_LABEL.match(v):
1252
+ wandb.termwarn(
1253
+ f"Label added for '{k}' with invalid identifier '{v}' (ignored).",
1254
+ repeat=False,
1255
+ )
1256
+ for v in kwargs:
1257
+ wandb.termwarn(
1258
+ f"Label added for unsupported key {v!r} (ignored).",
1259
+ repeat=False,
1260
+ )
1261
+
1262
+ self._label_internal(code=code, repo=repo, code_version=code_version)
1263
+
1264
+ # update telemetry in the backend immediately for _label() callers
1265
+ self._telemetry_flush()
1266
+
1267
+ def _label_probe_lines(self, lines: List[str]) -> None:
1268
+ if not lines:
1269
+ return
1270
+ parsed = telemetry._parse_label_lines(lines)
1271
+ if not parsed:
1272
+ return
1273
+ label_dict = {}
1274
+ code = parsed.get("code") or parsed.get("c")
1275
+ if code:
1276
+ label_dict["code"] = code
1277
+ repo = parsed.get("repo") or parsed.get("r")
1278
+ if repo:
1279
+ label_dict["repo"] = repo
1280
+ code_ver = parsed.get("version") or parsed.get("v")
1281
+ if code_ver:
1282
+ label_dict["code_version"] = code_ver
1283
+ self._label_internal(**label_dict)
1284
+
1285
+ def _label_probe_main(self) -> None:
1286
+ m = sys.modules.get("__main__")
1287
+ if not m:
1288
+ return
1289
+ doc = getattr(m, "__doc__", None)
1290
+ if not doc:
1291
+ return
1292
+
1293
+ doclines = doc.splitlines()
1294
+ self._label_probe_lines(doclines)
1295
+
1296
+ # TODO: annotate jupyter Notebook class
1297
+ def _label_probe_notebook(self, notebook: Any) -> None:
1298
+ logger.info("probe notebook")
1299
+ lines = None
1300
+ try:
1301
+ data = notebook.probe_ipynb()
1302
+ cell0 = data.get("cells", [])[0]
1303
+ lines = cell0.get("source")
1304
+ # kaggle returns a string instead of a list
1305
+ if isinstance(lines, str):
1306
+ lines = lines.split()
1307
+ except Exception as e:
1308
+ logger.info(f"Unable to probe notebook: {e}")
1309
+ return
1310
+ if lines:
1311
+ self._label_probe_lines(lines)
1312
+
1313
+ @_run_decorator._attach
1314
+ def display(self, height: int = 420, hidden: bool = False) -> bool:
1315
+ """Display this run in jupyter."""
1316
+ if self._settings._jupyter:
1317
+ ipython.display_html(self.to_html(height, hidden))
1318
+ return True
1319
+ else:
1320
+ wandb.termwarn(".display() only works in jupyter environments")
1321
+ return False
1322
+
1323
+ @_run_decorator._attach
1324
+ def to_html(self, height: int = 420, hidden: bool = False) -> str:
1325
+ """Generate HTML containing an iframe displaying the current run."""
1326
+ url = self._settings.run_url + "?jupyter=true"
1327
+ style = f"border:none;width:100%;height:{height}px;"
1328
+ prefix = ""
1329
+ if hidden:
1330
+ style += "display:none;"
1331
+ prefix = ipython.toggle_button()
1332
+ return prefix + f"<iframe src={url!r} style={style!r}></iframe>"
1333
+
1334
+ def _repr_mimebundle_(
1335
+ self, include: Optional[Any] = None, exclude: Optional[Any] = None
1336
+ ) -> Dict[str, str]:
1337
+ return {"text/html": self.to_html(hidden=True)}
1338
+
1339
+ @_run_decorator._noop_on_finish()
1340
+ def _config_callback(
1341
+ self,
1342
+ key: Optional[Union[Tuple[str, ...], str]] = None,
1343
+ val: Optional[Any] = None,
1344
+ data: Optional[Dict[str, object]] = None,
1345
+ ) -> None:
1346
+ logger.info(f"config_cb {key} {val} {data}")
1347
+ if self._backend and self._backend.interface:
1348
+ self._backend.interface.publish_config(key=key, val=val, data=data)
1349
+
1350
+ def _config_artifact_callback(
1351
+ self, key: str, val: Union[str, Artifact, dict]
1352
+ ) -> Artifact:
1353
+ # artifacts can look like dicts as they are passed into the run config
1354
+ # since the run config stores them on the backend as a dict with fields shown
1355
+ # in wandb.util.artifact_to_json
1356
+ if _is_artifact_version_weave_dict(val):
1357
+ assert isinstance(val, dict)
1358
+ public_api = self._public_api()
1359
+ artifact = Artifact._from_id(val["id"], public_api.client)
1360
+ return self.use_artifact(artifact, use_as=key)
1361
+ elif _is_artifact_string(val):
1362
+ # this will never fail, but is required to make mypy happy
1363
+ assert isinstance(val, str)
1364
+ artifact_string, base_url, is_id = parse_artifact_string(val)
1365
+ overrides = {}
1366
+ if base_url is not None:
1367
+ overrides = {"base_url": base_url}
1368
+ public_api = public.Api(overrides)
1369
+ else:
1370
+ public_api = self._public_api()
1371
+ if is_id:
1372
+ artifact = Artifact._from_id(artifact_string, public_api._client)
1373
+ else:
1374
+ artifact = public_api.artifact(name=artifact_string)
1375
+ # in the future we'll need to support using artifacts from
1376
+ # different instances of wandb.
1377
+
1378
+ return self.use_artifact(artifact, use_as=key)
1379
+ elif _is_artifact_object(val):
1380
+ return self.use_artifact(val, use_as=key)
1381
+ else:
1382
+ raise ValueError(
1383
+ f"Cannot call _config_artifact_callback on type {type(val)}"
1384
+ )
1385
+
1386
+ def _set_config_wandb(self, key: str, val: Any) -> None:
1387
+ self._config_callback(key=("_wandb", key), val=val)
1388
+
1389
+ @_run_decorator._noop_on_finish()
1390
+ def _summary_update_callback(self, summary_record: SummaryRecord) -> None:
1391
+ with telemetry.context(run=self) as tel:
1392
+ tel.feature.set_summary = True
1393
+ if self._backend and self._backend.interface:
1394
+ self._backend.interface.publish_summary(summary_record)
1395
+
1396
+ def _on_progress_get_summary(self, handle: MailboxProgress) -> None:
1397
+ pass
1398
+ # TODO(jhr): enable printing for get_summary in later mailbox dev phase
1399
+ # line = "Waiting for run.summary data..."
1400
+ # self._printer.display(line)
1401
+
1402
+ def _summary_get_current_summary_callback(self) -> Dict[str, Any]:
1403
+ if not self._backend or not self._backend.interface:
1404
+ return {}
1405
+ handle = self._backend.interface.deliver_get_summary()
1406
+ result = handle.wait(
1407
+ timeout=self._settings.summary_timeout,
1408
+ on_progress=self._on_progress_get_summary,
1409
+ )
1410
+ if not result:
1411
+ return {}
1412
+ get_summary_response = result.response.get_summary_response
1413
+ return proto_util.dict_from_proto_list(get_summary_response.item)
1414
+
1415
+ def _metric_callback(self, metric_record: MetricRecord) -> None:
1416
+ if self._backend and self._backend.interface:
1417
+ self._backend.interface._publish_metric(metric_record)
1418
+
1419
+ def _datatypes_callback(self, fname: str) -> None:
1420
+ if not self._backend or not self._backend.interface:
1421
+ return
1422
+ files: FilesDict = dict(files=[(GlobStr(glob.escape(fname)), "now")])
1423
+ self._backend.interface.publish_files(files)
1424
+
1425
+ def _visualization_hack(self, row: Dict[str, Any]) -> Dict[str, Any]:
1426
+ # TODO(jhr): move visualize hack somewhere else
1427
+ chart_keys = set()
1428
+ split_table_set = set()
1429
+ for k in row:
1430
+ if isinstance(row[k], Visualize):
1431
+ key = row[k].get_config_key(k)
1432
+ value = row[k].get_config_value(k)
1433
+ row[k] = row[k]._data
1434
+ self._config_callback(val=value, key=key)
1435
+ elif isinstance(row[k], CustomChart):
1436
+ chart_keys.add(k)
1437
+ key = row[k].get_config_key(k)
1438
+ if row[k]._split_table:
1439
+ value = row[k].get_config_value(
1440
+ "Vega2", row[k].user_query(f"Custom Chart Tables/{k}_table")
1441
+ )
1442
+ split_table_set.add(k)
1443
+ else:
1444
+ value = row[k].get_config_value(
1445
+ "Vega2", row[k].user_query(f"{k}_table")
1446
+ )
1447
+ row[k] = row[k]._data
1448
+ self._config_callback(val=value, key=key)
1449
+
1450
+ for k in chart_keys:
1451
+ # remove the chart key from the row
1452
+ # TODO: is this really the right move? what if the user logs
1453
+ # a non-custom chart to this key?
1454
+ if k in split_table_set:
1455
+ row[f"Custom Chart Tables/{k}_table"] = row.pop(k)
1456
+ else:
1457
+ row[f"{k}_table"] = row.pop(k)
1458
+ return row
1459
+
1460
+ def _partial_history_callback(
1461
+ self,
1462
+ row: Dict[str, Any],
1463
+ step: Optional[int] = None,
1464
+ commit: Optional[bool] = None,
1465
+ ) -> None:
1466
+ row = row.copy()
1467
+ if row:
1468
+ row = self._visualization_hack(row)
1469
+
1470
+ if self._backend and self._backend.interface:
1471
+ not_using_tensorboard = len(wandb.patched["tensorboard"]) == 0
1472
+
1473
+ self._backend.interface.publish_partial_history(
1474
+ row,
1475
+ user_step=self._step,
1476
+ step=step,
1477
+ flush=commit,
1478
+ publish_step=not_using_tensorboard,
1479
+ )
1480
+
1481
+ def _console_callback(self, name: str, data: str) -> None:
1482
+ # logger.info("console callback: %s, %s", name, data)
1483
+ if self._backend and self._backend.interface:
1484
+ self._backend.interface.publish_output(name, data)
1485
+
1486
+ @_run_decorator._noop_on_finish(only_warn=True)
1487
+ def _console_raw_callback(self, name: str, data: str) -> None:
1488
+ # logger.info("console callback: %s, %s", name, data)
1489
+
1490
+ # NOTE: console output is only allowed on the process which installed the callback
1491
+ # this will prevent potential corruption in the socket to the service. Other methods
1492
+ # are protected by the _attach run decorator, but this callback was installed on the
1493
+ # write function of stdout and stderr streams.
1494
+ console_pid = getattr(self, "_attach_pid", 0)
1495
+ if console_pid != os.getpid():
1496
+ return
1497
+
1498
+ if self._backend and self._backend.interface:
1499
+ self._backend.interface.publish_output_raw(name, data)
1500
+
1501
+ def _tensorboard_callback(
1502
+ self, logdir: str, save: bool = True, root_logdir: str = ""
1503
+ ) -> None:
1504
+ logger.info("tensorboard callback: %s, %s", logdir, save)
1505
+ if self._backend and self._backend.interface:
1506
+ self._backend.interface.publish_tbdata(logdir, save, root_logdir)
1507
+
1508
+ def _set_library(self, library: _WandbSetup) -> None:
1509
+ self._wl = library
1510
+
1511
+ def _set_backend(self, backend: "wandb.sdk.backend.backend.Backend") -> None:
1512
+ self._backend = backend
1513
+
1514
+ def _set_internal_run_interface(
1515
+ self,
1516
+ interface: "wandb.sdk.interface.interface_queue.InterfaceQueue",
1517
+ ) -> None:
1518
+ self._internal_run_interface = interface
1519
+
1520
+ def _set_reporter(self, reporter: Reporter) -> None:
1521
+ self._reporter = reporter
1522
+
1523
+ def _set_teardown_hooks(self, hooks: List[TeardownHook]) -> None:
1524
+ self._teardown_hooks = hooks
1525
+
1526
+ def _set_run_obj(self, run_obj: RunRecord) -> None:
1527
+ self._run_obj = run_obj
1528
+ if self.settings._offline:
1529
+ return
1530
+
1531
+ self._entity = run_obj.entity
1532
+ self._project = run_obj.project
1533
+
1534
+ # Grab the config from resuming
1535
+ if run_obj.config:
1536
+ c_dict = config_util.dict_no_value_from_proto_list(run_obj.config.update)
1537
+ # TODO: Windows throws a wild error when this is set...
1538
+ if "_wandb" in c_dict:
1539
+ del c_dict["_wandb"]
1540
+ # We update the config object here without triggering the callback
1541
+ self._config._update(c_dict, allow_val_change=True, ignore_locked=True)
1542
+ # Update the summary, this will trigger an un-needed graphql request :(
1543
+ if run_obj.summary:
1544
+ summary_dict = {}
1545
+ for orig in run_obj.summary.update:
1546
+ summary_dict[orig.key] = json.loads(orig.value_json)
1547
+ if summary_dict:
1548
+ self.summary.update(summary_dict)
1549
+ self._step = self._get_starting_step()
1550
+
1551
+ # update settings from run_obj
1552
+ self._settings._apply_run_start(message_to_dict(self._run_obj))
1553
+ self._update_settings(self._settings)
1554
+
1555
+ wandb._sentry.configure_scope(
1556
+ process_context="user",
1557
+ tags=dict(self._settings),
1558
+ )
1559
+
1560
+ def _add_singleton(
1561
+ self, data_type: str, key: str, value: Dict[Union[int, str], str]
1562
+ ) -> None:
1563
+ """Store a singleton item to wandb config.
1564
+
1565
+ A singleton in this context is a piece of data that is continually
1566
+ logged with the same value in each history step, but represented
1567
+ as a single item in the config.
1568
+
1569
+ We do this to avoid filling up history with a lot of repeated unnecessary data
1570
+
1571
+ Add singleton can be called many times in one run, and it will only be
1572
+ updated when the value changes. The last value logged will be the one
1573
+ persisted to the server.
1574
+ """
1575
+ value_extra = {"type": data_type, "key": key, "value": value}
1576
+
1577
+ if data_type not in self._config["_wandb"]:
1578
+ self._config["_wandb"][data_type] = {}
1579
+
1580
+ if data_type in self._config["_wandb"][data_type]:
1581
+ old_value = self._config["_wandb"][data_type][key]
1582
+ else:
1583
+ old_value = None
1584
+
1585
+ if value_extra != old_value:
1586
+ self._config["_wandb"][data_type][key] = value_extra
1587
+ self._config.persist()
1588
+
1589
+ def _log(
1590
+ self,
1591
+ data: Dict[str, Any],
1592
+ step: Optional[int] = None,
1593
+ commit: Optional[bool] = None,
1594
+ ) -> None:
1595
+ if not isinstance(data, Mapping):
1596
+ raise ValueError("wandb.log must be passed a dictionary")
1597
+
1598
+ if any(not isinstance(key, str) for key in data.keys()):
1599
+ raise ValueError("Key values passed to `wandb.log` must be strings.")
1600
+
1601
+ self._partial_history_callback(data, step, commit)
1602
+
1603
+ if step is not None:
1604
+ if os.getpid() != self._init_pid or self._is_attached:
1605
+ wandb.termwarn(
1606
+ "Note that setting step in multiprocessing can result in data loss. "
1607
+ "Please log your step values as a metric such as 'global_step'",
1608
+ repeat=False,
1609
+ )
1610
+ # if step is passed in when tensorboard_sync is used we honor the step passed
1611
+ # to make decisions about how to close out the history record, but will strip
1612
+ # this history later on in publish_history()
1613
+ if len(wandb.patched["tensorboard"]) > 0:
1614
+ wandb.termwarn(
1615
+ "Step cannot be set when using syncing with tensorboard. "
1616
+ "Please log your step values as a metric such as 'global_step'",
1617
+ repeat=False,
1618
+ )
1619
+ if step > self._step:
1620
+ self._step = step
1621
+
1622
+ if (step is None and commit is None) or commit:
1623
+ self._step += 1
1624
+
1625
+ @_run_decorator._noop
1626
+ @_run_decorator._noop_on_finish()
1627
+ @_run_decorator._attach
1628
+ def log(
1629
+ self,
1630
+ data: Dict[str, Any],
1631
+ step: Optional[int] = None,
1632
+ commit: Optional[bool] = None,
1633
+ sync: Optional[bool] = None,
1634
+ ) -> None:
1635
+ """Log a dictionary of data to the current run's history.
1636
+
1637
+ Use `wandb.log` to log data from runs, such as scalars, images, video,
1638
+ histograms, plots, and tables.
1639
+
1640
+ See our [guides to logging](https://docs.wandb.ai/guides/track/log) for
1641
+ live examples, code snippets, best practices, and more.
1642
+
1643
+ The most basic usage is `wandb.log({"train-loss": 0.5, "accuracy": 0.9})`.
1644
+ This will save the loss and accuracy to the run's history and update
1645
+ the summary values for these metrics.
1646
+
1647
+ Visualize logged data in the workspace at [wandb.ai](https://wandb.ai),
1648
+ or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting)
1649
+ of the W&B app, or export data to visualize and explore locally, e.g. in
1650
+ Jupyter notebooks, with [our API](https://docs.wandb.ai/guides/track/public-api-guide).
1651
+
1652
+ In the UI, summary values show up in the run table to compare single values across runs.
1653
+ Summary values can also be set directly with `wandb.run.summary["key"] = value`.
1654
+
1655
+ Logged values don't have to be scalars. Logging any wandb object is supported.
1656
+ For example `wandb.log({"example": wandb.Image("myimage.jpg")})` will log an
1657
+ example image which will be displayed nicely in the W&B UI.
1658
+ See the [reference documentation](https://docs.wandb.com/ref/python/data-types)
1659
+ for all of the different supported types or check out our
1660
+ [guides to logging](https://docs.wandb.ai/guides/track/log) for examples,
1661
+ from 3D molecular structures and segmentation masks to PR curves and histograms.
1662
+ `wandb.Table`s can be used to logged structured data. See our
1663
+ [guide to logging tables](https://docs.wandb.ai/guides/data-vis/log-tables)
1664
+ for details.
1665
+
1666
+ Logging nested metrics is encouraged and is supported in the W&B UI.
1667
+ If you log with a nested dictionary like `wandb.log({"train":
1668
+ {"acc": 0.9}, "val": {"acc": 0.8}})`, the metrics will be organized into
1669
+ `train` and `val` sections in the W&B UI.
1670
+
1671
+ wandb keeps track of a global step, which by default increments with each
1672
+ call to `wandb.log`, so logging related metrics together is encouraged.
1673
+ If it's inconvenient to log related metrics together
1674
+ calling `wandb.log({"train-loss": 0.5}, commit=False)` and then
1675
+ `wandb.log({"accuracy": 0.9})` is equivalent to calling
1676
+ `wandb.log({"train-loss": 0.5, "accuracy": 0.9})`.
1677
+
1678
+ `wandb.log` is not intended to be called more than a few times per second.
1679
+ If you want to log more frequently than that it's better to aggregate
1680
+ the data on the client side or you may get degraded performance.
1681
+
1682
+ Arguments:
1683
+ data: (dict, optional) A dict of serializable python objects i.e `str`,
1684
+ `ints`, `floats`, `Tensors`, `dicts`, or any of the `wandb.data_types`.
1685
+ commit: (boolean, optional) Save the metrics dict to the wandb server
1686
+ and increment the step. If false `wandb.log` just updates the current
1687
+ metrics dict with the data argument and metrics won't be saved until
1688
+ `wandb.log` is called with `commit=True`.
1689
+ step: (integer, optional) The global step in processing. This persists
1690
+ any non-committed earlier steps but defaults to not committing the
1691
+ specified step.
1692
+ sync: (boolean, True) This argument is deprecated and currently doesn't
1693
+ change the behaviour of `wandb.log`.
1694
+
1695
+ Examples:
1696
+ For more and more detailed examples, see
1697
+ [our guides to logging](https://docs.wandb.com/guides/track/log).
1698
+
1699
+ ### Basic usage
1700
+ <!--yeadoc-test:init-and-log-basic-->
1701
+ ```python
1702
+ import wandb
1703
+
1704
+ run = wandb.init()
1705
+ run.log({"accuracy": 0.9, "epoch": 5})
1706
+ ```
1707
+
1708
+ ### Incremental logging
1709
+ <!--yeadoc-test:init-and-log-incremental-->
1710
+ ```python
1711
+ import wandb
1712
+
1713
+ run = wandb.init()
1714
+ run.log({"loss": 0.2}, commit=False)
1715
+ # Somewhere else when I'm ready to report this step:
1716
+ run.log({"accuracy": 0.8})
1717
+ ```
1718
+
1719
+ ### Histogram
1720
+ <!--yeadoc-test:init-and-log-histogram-->
1721
+ ```python
1722
+ import numpy as np
1723
+ import wandb
1724
+
1725
+ # sample gradients at random from normal distribution
1726
+ gradients = np.random.randn(100, 100)
1727
+ run = wandb.init()
1728
+ run.log({"gradients": wandb.Histogram(gradients)})
1729
+ ```
1730
+
1731
+ ### Image from numpy
1732
+ <!--yeadoc-test:init-and-log-image-numpy-->
1733
+ ```python
1734
+ import numpy as np
1735
+ import wandb
1736
+
1737
+ run = wandb.init()
1738
+ examples = []
1739
+ for i in range(3):
1740
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
1741
+ image = wandb.Image(pixels, caption=f"random field {i}")
1742
+ examples.append(image)
1743
+ run.log({"examples": examples})
1744
+ ```
1745
+
1746
+ ### Image from PIL
1747
+ <!--yeadoc-test:init-and-log-image-pillow-->
1748
+ ```python
1749
+ import numpy as np
1750
+ from PIL import Image as PILImage
1751
+ import wandb
1752
+
1753
+ run = wandb.init()
1754
+ examples = []
1755
+ for i in range(3):
1756
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)
1757
+ pil_image = PILImage.fromarray(pixels, mode="RGB")
1758
+ image = wandb.Image(pil_image, caption=f"random field {i}")
1759
+ examples.append(image)
1760
+ run.log({"examples": examples})
1761
+ ```
1762
+
1763
+ ### Video from numpy
1764
+ <!--yeadoc-test:init-and-log-video-numpy-->
1765
+ ```python
1766
+ import numpy as np
1767
+ import wandb
1768
+
1769
+ run = wandb.init()
1770
+ # axes are (time, channel, height, width)
1771
+ frames = np.random.randint(low=0, high=256, size=(10, 3, 100, 100), dtype=np.uint8)
1772
+ run.log({"video": wandb.Video(frames, fps=4)})
1773
+ ```
1774
+
1775
+ ### Matplotlib Plot
1776
+ <!--yeadoc-test:init-and-log-matplotlib-->
1777
+ ```python
1778
+ from matplotlib import pyplot as plt
1779
+ import numpy as np
1780
+ import wandb
1781
+
1782
+ run = wandb.init()
1783
+ fig, ax = plt.subplots()
1784
+ x = np.linspace(0, 10)
1785
+ y = x * x
1786
+ ax.plot(x, y) # plot y = x^2
1787
+ run.log({"chart": fig})
1788
+ ```
1789
+
1790
+ ### PR Curve
1791
+ ```python
1792
+ import wandb
1793
+
1794
+ run = wandb.init()
1795
+ run.log({"pr": wandb.plots.precision_recall(y_test, y_probas, labels)})
1796
+ ```
1797
+
1798
+ ### 3D Object
1799
+ ```python
1800
+ import wandb
1801
+
1802
+ run = wandb.init()
1803
+ run.log(
1804
+ {
1805
+ "generated_samples": [
1806
+ wandb.Object3D(open("sample.obj")),
1807
+ wandb.Object3D(open("sample.gltf")),
1808
+ wandb.Object3D(open("sample.glb")),
1809
+ ]
1810
+ }
1811
+ )
1812
+ ```
1813
+
1814
+ Raises:
1815
+ wandb.Error: if called before `wandb.init`
1816
+ ValueError: if invalid data is passed
1817
+
1818
+ """
1819
+ if step is not None:
1820
+ with telemetry.context(run=self) as tel:
1821
+ tel.feature.set_step_log = True
1822
+
1823
+ if sync is not None:
1824
+ deprecate.deprecate(
1825
+ field_name=deprecate.Deprecated.run__log_sync,
1826
+ warning_message=(
1827
+ "`sync` argument is deprecated and does not affect the behaviour of `wandb.log`"
1828
+ ),
1829
+ )
1830
+ if self._settings._shared and step is not None:
1831
+ wandb.termwarn(
1832
+ "In shared mode, the use of `wandb.log` with the step argument is not supported "
1833
+ f"and will be ignored. Please refer to {wburls.get('wandb_define_metric')} "
1834
+ "on how to customize your x-axis.",
1835
+ repeat=False,
1836
+ )
1837
+ self._log(data=data, step=step, commit=commit)
1838
+
1839
+ @_run_decorator._noop_on_finish()
1840
+ @_run_decorator._attach
1841
+ def save(
1842
+ self,
1843
+ glob_str: Optional[Union[str, os.PathLike]] = None,
1844
+ base_path: Optional[Union[str, os.PathLike]] = None,
1845
+ policy: "PolicyName" = "live",
1846
+ ) -> Union[bool, List[str]]:
1847
+ """Sync one or more files to W&B.
1848
+
1849
+ Relative paths are relative to the current working directory.
1850
+
1851
+ A Unix glob, such as "myfiles/*", is expanded at the time `save` is
1852
+ called regardless of the `policy`. In particular, new files are not
1853
+ picked up automatically.
1854
+
1855
+ A `base_path` may be provided to control the directory structure of
1856
+ uploaded files. It should be a prefix of `glob_str`, and the direcotry
1857
+ structure beneath it is preserved. It's best understood through
1858
+ examples:
1859
+
1860
+ ```
1861
+ wandb.save("these/are/myfiles/*")
1862
+ # => Saves files in a "these/are/myfiles/" folder in the run.
1863
+
1864
+ wandb.save("these/are/myfiles/*", base_path="these")
1865
+ # => Saves files in an "are/myfiles/" folder in the run.
1866
+
1867
+ wandb.save("/User/username/Documents/run123/*.txt")
1868
+ # => Saves files in a "run123/" folder in the run. See note below.
1869
+
1870
+ wandb.save("/User/username/Documents/run123/*.txt", base_path="/User")
1871
+ # => Saves files in a "username/Documents/run123/" folder in the run.
1872
+
1873
+ wandb.save("files/*/saveme.txt")
1874
+ # => Saves each "saveme.txt" file in an appropriate subdirectory
1875
+ # of "files/".
1876
+ ```
1877
+
1878
+ Note: when given an absolute path or glob and no `base_path`, one
1879
+ directory level is preserved as in the example above.
1880
+
1881
+ Arguments:
1882
+ glob_str: A relative or absolute path or Unix glob.
1883
+ base_path: A path to use to infer a directory structure; see examples.
1884
+ policy: One of `live`, `now`, or `end`.
1885
+ * live: upload the file as it changes, overwriting the previous version
1886
+ * now: upload the file once now
1887
+ * end: upload file when the run ends
1888
+
1889
+ Returns:
1890
+ Paths to the symlinks created for the matched files.
1891
+
1892
+ For historical reasons, this may return a boolean in legacy code.
1893
+ """
1894
+ if glob_str is None:
1895
+ # noop for historical reasons, run.save() may be called in legacy code
1896
+ deprecate.deprecate(
1897
+ field_name=deprecate.Deprecated.run__save_no_args,
1898
+ warning_message=(
1899
+ "Calling wandb.run.save without any arguments is deprecated."
1900
+ "Changes to attributes are automatically persisted."
1901
+ ),
1902
+ )
1903
+ return True
1904
+
1905
+ if isinstance(glob_str, bytes):
1906
+ # Preserved for backward compatibility: allow bytes inputs.
1907
+ glob_str = glob_str.decode("utf-8")
1908
+ if isinstance(glob_str, str) and (
1909
+ glob_str.startswith("gs://") or glob_str.startswith("s3://")
1910
+ ):
1911
+ # Provide a better error message for a common misuse.
1912
+ wandb.termlog(f"{glob_str} is a cloud storage url, can't save file to W&B.")
1913
+ return []
1914
+ glob_path = pathlib.Path(glob_str)
1915
+
1916
+ if base_path is not None:
1917
+ base_path = pathlib.Path(base_path)
1918
+ elif not glob_path.is_absolute():
1919
+ base_path = pathlib.Path(".")
1920
+ else:
1921
+ # Absolute glob paths with no base path get special handling.
1922
+ wandb.termwarn(
1923
+ "Saving files without folders. If you want to preserve "
1924
+ "subdirectories pass base_path to wandb.save, i.e. "
1925
+ 'wandb.save("/mnt/folder/file.h5", base_path="/mnt")',
1926
+ repeat=False,
1927
+ )
1928
+ base_path = glob_path.resolve().parent.parent
1929
+
1930
+ if policy not in ("live", "end", "now"):
1931
+ raise ValueError(
1932
+ 'Only "live", "end" and "now" policies are currently supported.'
1933
+ )
1934
+
1935
+ resolved_glob_path = glob_path.resolve()
1936
+ resolved_base_path = base_path.resolve()
1937
+
1938
+ return self._save(
1939
+ resolved_glob_path,
1940
+ resolved_base_path,
1941
+ policy,
1942
+ )
1943
+
1944
+ def _save(
1945
+ self,
1946
+ glob_path: pathlib.Path,
1947
+ base_path: pathlib.Path,
1948
+ policy: "PolicyName",
1949
+ ) -> List[str]:
1950
+ # Can't use is_relative_to() because that's added in Python 3.9,
1951
+ # but we support down to Python 3.7.
1952
+ if not str(glob_path).startswith(str(base_path)):
1953
+ raise ValueError("Glob may not walk above the base path")
1954
+
1955
+ if glob_path == base_path:
1956
+ raise ValueError("Glob cannot be the same as the base path")
1957
+
1958
+ relative_glob = glob_path.relative_to(base_path)
1959
+ if relative_glob.parts[0] == "*":
1960
+ raise ValueError("Glob may not start with '*' relative to the base path")
1961
+ relative_glob_str = GlobStr(str(relative_glob))
1962
+
1963
+ with telemetry.context(run=self) as tel:
1964
+ tel.feature.save = True
1965
+
1966
+ # Files in the files directory matched by the glob, including old and
1967
+ # new ones.
1968
+ globbed_files = set(
1969
+ pathlib.Path(
1970
+ self._settings.files_dir,
1971
+ ).glob(relative_glob_str)
1972
+ )
1973
+
1974
+ had_symlinked_files = len(globbed_files) > 0
1975
+ is_star_glob = "*" in relative_glob_str
1976
+
1977
+ # The base_path may itself be a glob, so we can't do
1978
+ # base_path.glob(relative_glob_str)
1979
+ for path_str in glob.glob(str(base_path / relative_glob_str)):
1980
+ source_path = pathlib.Path(path_str).absolute()
1981
+
1982
+ # We can't use relative_to() because base_path may be a glob.
1983
+ relative_path = pathlib.Path(*source_path.parts[len(base_path.parts) :])
1984
+
1985
+ target_path = pathlib.Path(self._settings.files_dir, relative_path)
1986
+ globbed_files.add(target_path)
1987
+
1988
+ # If the file is already where it needs to be, don't create a symlink.
1989
+ if source_path.resolve() == target_path.resolve():
1990
+ continue
1991
+
1992
+ target_path.parent.mkdir(parents=True, exist_ok=True)
1993
+
1994
+ # Delete the symlink if it exists.
1995
+ try:
1996
+ target_path.unlink()
1997
+ except FileNotFoundError:
1998
+ # In Python 3.8, we would pass missing_ok=True, but as of now
1999
+ # we support down to Python 3.7.
2000
+ pass
2001
+
2002
+ target_path.symlink_to(source_path)
2003
+
2004
+ # Inform users that new files aren't detected automatically.
2005
+ if not had_symlinked_files and is_star_glob:
2006
+ file_str = f"{len(globbed_files)} file"
2007
+ if len(globbed_files) > 1:
2008
+ file_str += "s"
2009
+ wandb.termwarn(
2010
+ f"Symlinked {file_str} into the W&B run directory, "
2011
+ "call wandb.save again to sync new files."
2012
+ )
2013
+
2014
+ files_dict: FilesDict = {
2015
+ "files": [
2016
+ (
2017
+ GlobStr(str(f.relative_to(self._settings.files_dir))),
2018
+ policy,
2019
+ )
2020
+ for f in globbed_files
2021
+ ]
2022
+ }
2023
+ if self._backend and self._backend.interface:
2024
+ self._backend.interface.publish_files(files_dict)
2025
+
2026
+ return [str(f) for f in globbed_files]
2027
+
2028
+ @_run_decorator._attach
2029
+ def restore(
2030
+ self,
2031
+ name: str,
2032
+ run_path: Optional[str] = None,
2033
+ replace: bool = False,
2034
+ root: Optional[str] = None,
2035
+ ) -> Union[None, TextIO]:
2036
+ return restore(
2037
+ name,
2038
+ run_path or self._get_path(),
2039
+ replace,
2040
+ root or self._settings.files_dir,
2041
+ )
2042
+
2043
+ @_run_decorator._noop
2044
+ @_run_decorator._attach
2045
+ def finish(
2046
+ self, exit_code: Optional[int] = None, quiet: Optional[bool] = None
2047
+ ) -> None:
2048
+ """Mark a run as finished, and finish uploading all data.
2049
+
2050
+ This is used when creating multiple runs in the same process. We automatically
2051
+ call this method when your script exits or if you use the run context manager.
2052
+
2053
+ Arguments:
2054
+ exit_code: Set to something other than 0 to mark a run as failed
2055
+ quiet: Set to true to minimize log output
2056
+ """
2057
+ return self._finish(exit_code, quiet)
2058
+
2059
+ def _finish(
2060
+ self, exit_code: Optional[int] = None, quiet: Optional[bool] = None
2061
+ ) -> None:
2062
+ if quiet is not None:
2063
+ self._quiet = quiet
2064
+ with telemetry.context(run=self) as tel:
2065
+ tel.feature.finish = True
2066
+ logger.info(f"finishing run {self._get_path()}")
2067
+ # detach jupyter hooks / others that needs to happen before backend shutdown
2068
+ for hook in self._teardown_hooks:
2069
+ if hook.stage == TeardownStage.EARLY:
2070
+ hook.call()
2071
+
2072
+ self._atexit_cleanup(exit_code=exit_code)
2073
+ if self._wl and len(self._wl._global_run_stack) > 0:
2074
+ self._wl._global_run_stack.pop()
2075
+ # detach logger / others meant to be run after we've shutdown the backend
2076
+ for hook in self._teardown_hooks:
2077
+ if hook.stage == TeardownStage.LATE:
2078
+ hook.call()
2079
+ self._teardown_hooks = []
2080
+ module.unset_globals()
2081
+
2082
+ # inform manager this run is finished
2083
+ manager = self._wl and self._wl._get_manager()
2084
+ if manager:
2085
+ manager._inform_finish(run_id=self._run_id)
2086
+
2087
+ self._is_finished = True
2088
+ # end sentry session
2089
+ wandb._sentry.end_session()
2090
+
2091
+ @_run_decorator._noop
2092
+ @_run_decorator._attach
2093
+ def join(self, exit_code: Optional[int] = None) -> None:
2094
+ """Deprecated alias for `finish()` - use finish instead."""
2095
+ deprecate.deprecate(
2096
+ field_name=deprecate.Deprecated.run__join,
2097
+ warning_message=(
2098
+ "wandb.run.join() is deprecated, please use wandb.run.finish()."
2099
+ ),
2100
+ )
2101
+ self._finish(exit_code=exit_code)
2102
+
2103
+ @_run_decorator._noop_on_finish()
2104
+ @_run_decorator._attach
2105
+ def status(
2106
+ self,
2107
+ ) -> RunStatus:
2108
+ """Get sync info from the internal backend, about the current run's sync status."""
2109
+ if not self._backend or not self._backend.interface:
2110
+ return RunStatus()
2111
+
2112
+ handle_run_status = self._backend.interface.deliver_request_run_status()
2113
+ result = handle_run_status.wait(timeout=-1)
2114
+ assert result
2115
+ sync_data = result.response.run_status_response
2116
+
2117
+ sync_time = None
2118
+ if sync_data.sync_time.seconds:
2119
+ sync_time = datetime.fromtimestamp(
2120
+ sync_data.sync_time.seconds + sync_data.sync_time.nanos / 1e9
2121
+ )
2122
+ return RunStatus(
2123
+ sync_items_total=sync_data.sync_items_total,
2124
+ sync_items_pending=sync_data.sync_items_pending,
2125
+ sync_time=sync_time,
2126
+ )
2127
+
2128
+ @staticmethod
2129
+ def plot_table(
2130
+ vega_spec_name: str,
2131
+ data_table: "wandb.Table",
2132
+ fields: Dict[str, Any],
2133
+ string_fields: Optional[Dict[str, Any]] = None,
2134
+ split_table: Optional[bool] = False,
2135
+ ) -> CustomChart:
2136
+ """Create a custom plot on a table.
2137
+
2138
+ Arguments:
2139
+ vega_spec_name: the name of the spec for the plot
2140
+ data_table: a wandb.Table object containing the data to
2141
+ be used on the visualization
2142
+ fields: a dict mapping from table keys to fields that the custom
2143
+ visualization needs
2144
+ string_fields: a dict that provides values for any string constants
2145
+ the custom visualization needs
2146
+ """
2147
+ return custom_chart(
2148
+ vega_spec_name, data_table, fields, string_fields or {}, split_table
2149
+ )
2150
+
2151
+ def _add_panel(
2152
+ self, visualize_key: str, panel_type: str, panel_config: dict
2153
+ ) -> None:
2154
+ config = {
2155
+ "panel_type": panel_type,
2156
+ "panel_config": panel_config,
2157
+ }
2158
+ self._config_callback(val=config, key=("_wandb", "visualize", visualize_key))
2159
+
2160
+ def _set_globals(self) -> None:
2161
+ module.set_global(
2162
+ run=self,
2163
+ config=self.config,
2164
+ log=self.log,
2165
+ summary=self.summary,
2166
+ save=self.save,
2167
+ use_artifact=self.use_artifact,
2168
+ log_artifact=self.log_artifact,
2169
+ define_metric=self.define_metric,
2170
+ plot_table=self.plot_table,
2171
+ alert=self.alert,
2172
+ mark_preempting=self.mark_preempting,
2173
+ log_model=self.log_model,
2174
+ use_model=self.use_model,
2175
+ link_model=self.link_model,
2176
+ )
2177
+
2178
+ def _redirect(
2179
+ self,
2180
+ stdout_slave_fd: Optional[int],
2181
+ stderr_slave_fd: Optional[int],
2182
+ console: Optional[str] = None,
2183
+ ) -> None:
2184
+ if console is None:
2185
+ console = self._settings.console
2186
+ # only use raw for service to minimize potential changes
2187
+ if console == "wrap":
2188
+ if not self._settings._disable_service:
2189
+ console = "wrap_raw"
2190
+ else:
2191
+ console = "wrap_emu"
2192
+ logger.info("redirect: %s", console)
2193
+
2194
+ out_redir: redirect.RedirectBase
2195
+ err_redir: redirect.RedirectBase
2196
+
2197
+ # raw output handles the output_log writing in the internal process
2198
+ if console in {"redirect", "wrap_emu"}:
2199
+ output_log_path = os.path.join(
2200
+ self._settings.files_dir, filenames.OUTPUT_FNAME
2201
+ )
2202
+ # output writer might have been set up, see wrap_fallback case
2203
+ if not self._output_writer:
2204
+ self._output_writer = filesystem.CRDedupedFile(
2205
+ open(output_log_path, "wb")
2206
+ )
2207
+
2208
+ if console == "redirect":
2209
+ logger.info("Redirecting console.")
2210
+ out_redir = redirect.Redirect(
2211
+ src="stdout",
2212
+ cbs=[
2213
+ lambda data: self._console_callback("stdout", data),
2214
+ self._output_writer.write, # type: ignore
2215
+ ],
2216
+ )
2217
+ err_redir = redirect.Redirect(
2218
+ src="stderr",
2219
+ cbs=[
2220
+ lambda data: self._console_callback("stderr", data),
2221
+ self._output_writer.write, # type: ignore
2222
+ ],
2223
+ )
2224
+ if os.name == "nt":
2225
+
2226
+ def wrap_fallback() -> None:
2227
+ if self._out_redir:
2228
+ self._out_redir.uninstall()
2229
+ if self._err_redir:
2230
+ self._err_redir.uninstall()
2231
+ msg = (
2232
+ "Tensorflow detected. Stream redirection is not supported "
2233
+ "on Windows when tensorflow is imported. Falling back to "
2234
+ "wrapping stdout/err."
2235
+ )
2236
+ wandb.termlog(msg)
2237
+ self._redirect(None, None, console="wrap")
2238
+
2239
+ add_import_hook("tensorflow", wrap_fallback)
2240
+ elif console == "wrap_emu":
2241
+ logger.info("Wrapping output streams.")
2242
+ out_redir = redirect.StreamWrapper(
2243
+ src="stdout",
2244
+ cbs=[
2245
+ lambda data: self._console_callback("stdout", data),
2246
+ self._output_writer.write, # type: ignore
2247
+ ],
2248
+ )
2249
+ err_redir = redirect.StreamWrapper(
2250
+ src="stderr",
2251
+ cbs=[
2252
+ lambda data: self._console_callback("stderr", data),
2253
+ self._output_writer.write, # type: ignore
2254
+ ],
2255
+ )
2256
+ elif console == "wrap_raw":
2257
+ logger.info("Wrapping output streams.")
2258
+ out_redir = redirect.StreamRawWrapper(
2259
+ src="stdout",
2260
+ cbs=[
2261
+ lambda data: self._console_raw_callback("stdout", data),
2262
+ ],
2263
+ )
2264
+ err_redir = redirect.StreamRawWrapper(
2265
+ src="stderr",
2266
+ cbs=[
2267
+ lambda data: self._console_raw_callback("stderr", data),
2268
+ ],
2269
+ )
2270
+ elif console == "off":
2271
+ return
2272
+ else:
2273
+ raise ValueError("unhandled console")
2274
+ try:
2275
+ # save stdout and stderr before installing new write functions
2276
+ out_redir.save()
2277
+ err_redir.save()
2278
+ out_redir.install()
2279
+ err_redir.install()
2280
+ self._out_redir = out_redir
2281
+ self._err_redir = err_redir
2282
+ logger.info("Redirects installed.")
2283
+ except Exception as e:
2284
+ print(e)
2285
+ logger.error("Failed to redirect.", exc_info=e)
2286
+ return
2287
+
2288
+ def _restore(self) -> None:
2289
+ logger.info("restore")
2290
+ # TODO(jhr): drain and shutdown all threads
2291
+ if self._out_redir:
2292
+ self._out_redir.uninstall()
2293
+ if self._err_redir:
2294
+ self._err_redir.uninstall()
2295
+ logger.info("restore done")
2296
+
2297
+ def _atexit_cleanup(self, exit_code: Optional[int] = None) -> None:
2298
+ if self._backend is None:
2299
+ logger.warning("process exited without backend configured")
2300
+ return
2301
+ if self._atexit_cleanup_called:
2302
+ return
2303
+ self._atexit_cleanup_called = True
2304
+
2305
+ exit_code = exit_code or self._hooks.exit_code if self._hooks else 0
2306
+ logger.info(f"got exitcode: {exit_code}")
2307
+ if exit_code == 0:
2308
+ # Cleanup our resume file on a clean exit
2309
+ if os.path.exists(self._settings.resume_fname):
2310
+ os.remove(self._settings.resume_fname)
2311
+
2312
+ self._exit_code = exit_code
2313
+ report_failure = False
2314
+ try:
2315
+ self._on_finish()
2316
+ except KeyboardInterrupt as ki:
2317
+ if wandb.wandb_agent._is_running():
2318
+ raise ki
2319
+ wandb.termerror("Control-C detected -- Run data was not synced")
2320
+ if not self._settings._notebook:
2321
+ os._exit(-1)
2322
+ except Exception as e:
2323
+ if not self._settings._notebook:
2324
+ report_failure = True
2325
+ self._console_stop()
2326
+ self._backend.cleanup()
2327
+ logger.error("Problem finishing run", exc_info=e)
2328
+ wandb.termerror("Problem finishing run")
2329
+ traceback.print_exc()
2330
+ else:
2331
+ self._on_final()
2332
+ finally:
2333
+ if report_failure:
2334
+ os._exit(-1)
2335
+
2336
+ def _console_start(self) -> None:
2337
+ logger.info("atexit reg")
2338
+ self._hooks = ExitHooks()
2339
+
2340
+ manager = self._wl and self._wl._get_manager()
2341
+ if not manager:
2342
+ self._hooks.hook()
2343
+ # NB: manager will perform atexit hook like behavior for outstanding runs
2344
+ atexit.register(lambda: self._atexit_cleanup())
2345
+
2346
+ self._redirect(self._stdout_slave_fd, self._stderr_slave_fd)
2347
+
2348
+ def _console_stop(self) -> None:
2349
+ self._restore()
2350
+ if self._output_writer:
2351
+ self._output_writer.close()
2352
+ self._output_writer = None
2353
+
2354
+ def _on_init(self) -> None:
2355
+ if self._settings._offline:
2356
+ return
2357
+ if self._backend and self._backend.interface:
2358
+ if not self._settings._disable_update_check:
2359
+ logger.info("communicating current version")
2360
+ version_handle = self._backend.interface.deliver_check_version(
2361
+ current_version=wandb.__version__
2362
+ )
2363
+ version_result = version_handle.wait(timeout=30)
2364
+ if not version_result:
2365
+ version_handle.abandon()
2366
+ else:
2367
+ self._check_version = version_result.response.check_version_response
2368
+ logger.info("got version response %s", self._check_version)
2369
+
2370
+ def _on_start(self) -> None:
2371
+ # would like to move _set_global to _on_ready to unify _on_start and _on_attach
2372
+ # (we want to do the set globals after attach)
2373
+ # TODO(console) However _console_start calls Redirect that uses `wandb.run` hence breaks
2374
+ # TODO(jupyter) However _header calls _header_run_info that uses wandb.jupyter that uses
2375
+ # `wandb.run` and hence breaks
2376
+ self._set_globals()
2377
+ self._header(
2378
+ self._check_version, settings=self._settings, printer=self._printer
2379
+ )
2380
+
2381
+ if self._settings.save_code and self._settings.code_dir is not None:
2382
+ self.log_code(self._settings.code_dir)
2383
+
2384
+ if self._settings._save_requirements:
2385
+ if self._backend and self._backend.interface:
2386
+ from wandb.util import working_set
2387
+
2388
+ logger.debug(
2389
+ "Saving list of pip packages installed into the current environment"
2390
+ )
2391
+ self._backend.interface.publish_python_packages(working_set())
2392
+
2393
+ if self._backend and self._backend.interface and not self._settings._offline:
2394
+ self._run_status_checker = RunStatusChecker(
2395
+ interface=self._backend.interface,
2396
+ )
2397
+ self._run_status_checker.start()
2398
+
2399
+ self._console_start()
2400
+ self._on_ready()
2401
+
2402
+ def _on_attach(self) -> None:
2403
+ """Event triggered when run is attached to another run."""
2404
+ with telemetry.context(run=self) as tel:
2405
+ tel.feature.attach = True
2406
+
2407
+ self._set_globals()
2408
+ self._is_attached = True
2409
+ self._on_ready()
2410
+
2411
+ def _register_telemetry_import_hooks(
2412
+ self,
2413
+ ) -> None:
2414
+ def _telemetry_import_hook(
2415
+ run: "Run",
2416
+ module: Any,
2417
+ ) -> None:
2418
+ with telemetry.context(run=run) as tel:
2419
+ try:
2420
+ name = getattr(module, "__name__", None)
2421
+ if name is not None:
2422
+ setattr(tel.imports_finish, name, True)
2423
+ except AttributeError:
2424
+ return
2425
+
2426
+ import_telemetry_set = telemetry.list_telemetry_imports()
2427
+ import_hook_fn = functools.partial(_telemetry_import_hook, self)
2428
+ for module_name in import_telemetry_set:
2429
+ register_post_import_hook(
2430
+ import_hook_fn,
2431
+ self._run_id,
2432
+ module_name,
2433
+ )
2434
+
2435
+ def _on_ready(self) -> None:
2436
+ """Event triggered when run is ready for the user."""
2437
+ self._register_telemetry_import_hooks()
2438
+
2439
+ # start reporting any telemetry changes
2440
+ self._telemetry_obj_active = True
2441
+ self._telemetry_flush()
2442
+
2443
+ # object is about to be returned to the user, don't let them modify it
2444
+ self._freeze()
2445
+
2446
+ if not self._settings.resume:
2447
+ if os.path.exists(self._settings.resume_fname):
2448
+ os.remove(self._settings.resume_fname)
2449
+
2450
+ def _make_job_source_reqs(self) -> Tuple[List[str], Dict[str, Any], Dict[str, Any]]:
2451
+ from wandb.util import working_set
2452
+
2453
+ installed_packages_list = sorted(f"{d.key}=={d.version}" for d in working_set())
2454
+ input_types = TypeRegistry.type_of(self.config.as_dict()).to_json()
2455
+ output_types = TypeRegistry.type_of(self.summary._as_dict()).to_json()
2456
+
2457
+ return installed_packages_list, input_types, output_types
2458
+
2459
+ def _construct_job_artifact(
2460
+ self,
2461
+ name: str,
2462
+ source_dict: "JobSourceDict",
2463
+ installed_packages_list: List[str],
2464
+ patch_path: Optional[os.PathLike] = None,
2465
+ ) -> "Artifact":
2466
+ job_artifact = job_builder.JobArtifact(name)
2467
+ if patch_path and os.path.exists(patch_path):
2468
+ job_artifact.add_file(FilePathStr(str(patch_path)), "diff.patch")
2469
+ with job_artifact.new_file("requirements.frozen.txt") as f:
2470
+ f.write("\n".join(installed_packages_list))
2471
+ with job_artifact.new_file("wandb-job.json") as f:
2472
+ f.write(json.dumps(source_dict))
2473
+
2474
+ return job_artifact
2475
+
2476
+ def _create_image_job(
2477
+ self,
2478
+ input_types: Dict[str, Any],
2479
+ output_types: Dict[str, Any],
2480
+ installed_packages_list: List[str],
2481
+ docker_image_name: Optional[str] = None,
2482
+ args: Optional[List[str]] = None,
2483
+ ) -> Optional["Artifact"]:
2484
+ docker_image_name = docker_image_name or os.getenv("WANDB_DOCKER")
2485
+
2486
+ if not docker_image_name:
2487
+ return None
2488
+
2489
+ name = wandb.util.make_artifact_name_safe(f"job-{docker_image_name}")
2490
+ s_args: Sequence[str] = args if args is not None else self._settings._args
2491
+ source_info: JobSourceDict = {
2492
+ "_version": "v0",
2493
+ "source_type": "image",
2494
+ "source": {"image": docker_image_name, "args": s_args},
2495
+ "input_types": input_types,
2496
+ "output_types": output_types,
2497
+ "runtime": self._settings._python,
2498
+ }
2499
+ job_artifact = self._construct_job_artifact(
2500
+ name, source_info, installed_packages_list
2501
+ )
2502
+
2503
+ return job_artifact
2504
+
2505
+ def _log_job_artifact_with_image(
2506
+ self, docker_image_name: str, args: Optional[List[str]] = None
2507
+ ) -> Artifact:
2508
+ packages, in_types, out_types = self._make_job_source_reqs()
2509
+ job_artifact = self._create_image_job(
2510
+ in_types,
2511
+ out_types,
2512
+ packages,
2513
+ args=args,
2514
+ docker_image_name=docker_image_name,
2515
+ )
2516
+
2517
+ artifact = self.log_artifact(job_artifact)
2518
+
2519
+ if not artifact:
2520
+ raise wandb.Error(f"Job Artifact log unsuccessful: {artifact}")
2521
+ else:
2522
+ return artifact
2523
+
2524
+ def _on_probe_exit(self, probe_handle: MailboxProbe) -> None:
2525
+ handle = probe_handle.get_mailbox_handle()
2526
+ if handle:
2527
+ result = handle.wait(timeout=0, release=False)
2528
+ if not result:
2529
+ return
2530
+ probe_handle.set_probe_result(result)
2531
+ assert self._backend and self._backend.interface
2532
+ handle = self._backend.interface.deliver_poll_exit()
2533
+ probe_handle.set_mailbox_handle(handle)
2534
+
2535
+ def _on_progress_exit(self, progress_handle: MailboxProgress) -> None:
2536
+ probe_handles = progress_handle.get_probe_handles()
2537
+ assert probe_handles and len(probe_handles) == 1
2538
+
2539
+ result = probe_handles[0].get_probe_result()
2540
+ if not result:
2541
+ return
2542
+ self._footer_file_pusher_status_info(
2543
+ result.response.poll_exit_response, printer=self._printer
2544
+ )
2545
+
2546
+ def _on_finish(self) -> None:
2547
+ trigger.call("on_finished")
2548
+
2549
+ if self._run_status_checker is not None:
2550
+ self._run_status_checker.stop()
2551
+
2552
+ self._console_stop() # TODO: there's a race here with jupyter console logging
2553
+
2554
+ assert self._backend and self._backend.interface
2555
+ exit_handle = self._backend.interface.deliver_exit(self._exit_code)
2556
+ exit_handle.add_probe(on_probe=self._on_probe_exit)
2557
+
2558
+ # this message is confusing, we should remove it
2559
+ # self._footer_exit_status_info(
2560
+ # self._exit_code, settings=self._settings, printer=self._printer
2561
+ # )
2562
+
2563
+ _ = exit_handle.wait(timeout=-1, on_progress=self._on_progress_exit)
2564
+
2565
+ poll_exit_handle = self._backend.interface.deliver_poll_exit()
2566
+ # wait for them, it's ok to do this serially but this can be improved
2567
+ result = poll_exit_handle.wait(timeout=-1)
2568
+ assert result
2569
+ self._footer_file_pusher_status_info(
2570
+ result.response.poll_exit_response, printer=self._printer
2571
+ )
2572
+ self._poll_exit_response = result.response.poll_exit_response
2573
+ internal_messages_handle = self._backend.interface.deliver_internal_messages()
2574
+ result = internal_messages_handle.wait(timeout=-1)
2575
+ assert result
2576
+ self._internal_messages_response = result.response.internal_messages_response
2577
+
2578
+ # dispatch all our final requests
2579
+
2580
+ server_info_handle = self._backend.interface.deliver_request_server_info()
2581
+ final_summary_handle = self._backend.interface.deliver_get_summary()
2582
+ sampled_history_handle = (
2583
+ self._backend.interface.deliver_request_sampled_history()
2584
+ )
2585
+
2586
+ result = server_info_handle.wait(timeout=-1)
2587
+ assert result
2588
+ self._server_info_response = result.response.server_info_response
2589
+
2590
+ result = sampled_history_handle.wait(timeout=-1)
2591
+ assert result
2592
+ self._sampled_history = result.response.sampled_history_response
2593
+
2594
+ result = final_summary_handle.wait(timeout=-1)
2595
+ assert result
2596
+ self._final_summary = result.response.get_summary_response
2597
+
2598
+ if self._backend:
2599
+ self._backend.cleanup()
2600
+
2601
+ if self._run_status_checker:
2602
+ self._run_status_checker.join()
2603
+
2604
+ self._unregister_telemetry_import_hooks(self._run_id)
2605
+
2606
+ @staticmethod
2607
+ def _unregister_telemetry_import_hooks(run_id: str) -> None:
2608
+ import_telemetry_set = telemetry.list_telemetry_imports()
2609
+ for module_name in import_telemetry_set:
2610
+ unregister_post_import_hook(module_name, run_id)
2611
+
2612
+ def _on_final(self) -> None:
2613
+ self._footer(
2614
+ sampled_history=self._sampled_history,
2615
+ final_summary=self._final_summary,
2616
+ poll_exit_response=self._poll_exit_response,
2617
+ server_info_response=self._server_info_response,
2618
+ check_version_response=self._check_version,
2619
+ internal_messages_response=self._internal_messages_response,
2620
+ reporter=self._reporter,
2621
+ quiet=self._quiet,
2622
+ settings=self._settings,
2623
+ printer=self._printer,
2624
+ )
2625
+
2626
+ @_run_decorator._noop_on_finish()
2627
+ @_run_decorator._attach
2628
+ def define_metric(
2629
+ self,
2630
+ name: str,
2631
+ step_metric: Union[str, wandb_metric.Metric, None] = None,
2632
+ step_sync: Optional[bool] = None,
2633
+ hidden: Optional[bool] = None,
2634
+ summary: Optional[str] = None,
2635
+ goal: Optional[str] = None,
2636
+ overwrite: Optional[bool] = None,
2637
+ **kwargs: Any,
2638
+ ) -> wandb_metric.Metric:
2639
+ """Define metric properties which will later be logged with `wandb.log()`.
2640
+
2641
+ Arguments:
2642
+ name: Name of the metric.
2643
+ step_metric: Independent variable associated with the metric.
2644
+ step_sync: Automatically add `step_metric` to history if needed.
2645
+ Defaults to True if step_metric is specified.
2646
+ hidden: Hide this metric from automatic plots.
2647
+ summary: Specify aggregate metrics added to summary.
2648
+ Supported aggregations: "min,max,mean,best,last,none"
2649
+ Default aggregation is `copy`
2650
+ Aggregation `best` defaults to `goal`==`minimize`
2651
+ goal: Specify direction for optimizing the metric.
2652
+ Supported directions: "minimize,maximize"
2653
+
2654
+ Returns:
2655
+ A metric object is returned that can be further specified.
2656
+
2657
+ """
2658
+ return self._define_metric(
2659
+ name, step_metric, step_sync, hidden, summary, goal, overwrite, **kwargs
2660
+ )
2661
+
2662
+ def _define_metric(
2663
+ self,
2664
+ name: str,
2665
+ step_metric: Union[str, wandb_metric.Metric, None] = None,
2666
+ step_sync: Optional[bool] = None,
2667
+ hidden: Optional[bool] = None,
2668
+ summary: Optional[str] = None,
2669
+ goal: Optional[str] = None,
2670
+ overwrite: Optional[bool] = None,
2671
+ **kwargs: Any,
2672
+ ) -> wandb_metric.Metric:
2673
+ if not name:
2674
+ raise wandb.Error("define_metric() requires non-empty name argument")
2675
+ for k in kwargs:
2676
+ wandb.termwarn(f"Unhandled define_metric() arg: {k}")
2677
+ if isinstance(step_metric, wandb_metric.Metric):
2678
+ step_metric = step_metric.name
2679
+ for arg_name, arg_val, exp_type in (
2680
+ ("name", name, str),
2681
+ ("step_metric", step_metric, str),
2682
+ ("step_sync", step_sync, bool),
2683
+ ("hidden", hidden, bool),
2684
+ ("summary", summary, str),
2685
+ ("goal", goal, str),
2686
+ ("overwrite", overwrite, bool),
2687
+ ):
2688
+ # NOTE: type checking is broken for isinstance and str
2689
+ if arg_val is not None and not isinstance(arg_val, exp_type):
2690
+ arg_type = type(arg_val).__name__
2691
+ raise wandb.Error(
2692
+ f"Unhandled define_metric() arg: {arg_name} type: {arg_type}"
2693
+ )
2694
+ stripped = name[:-1] if name.endswith("*") else name
2695
+ if "*" in stripped:
2696
+ raise wandb.Error(
2697
+ f"Unhandled define_metric() arg: name (glob suffixes only): {name}"
2698
+ )
2699
+ summary_ops: Optional[Sequence[str]] = None
2700
+ if summary:
2701
+ summary_items = [s.lower() for s in summary.split(",")]
2702
+ summary_ops = []
2703
+ valid = {"min", "max", "mean", "best", "last", "copy", "none"}
2704
+ for i in summary_items:
2705
+ if i not in valid:
2706
+ raise wandb.Error(f"Unhandled define_metric() arg: summary op: {i}")
2707
+ summary_ops.append(i)
2708
+ goal_cleaned: Optional[str] = None
2709
+ if goal is not None:
2710
+ goal_cleaned = goal[:3].lower()
2711
+ valid_goal = {"min", "max"}
2712
+ if goal_cleaned not in valid_goal:
2713
+ raise wandb.Error(f"Unhandled define_metric() arg: goal: {goal}")
2714
+ m = wandb_metric.Metric(
2715
+ name=name,
2716
+ step_metric=step_metric,
2717
+ step_sync=step_sync,
2718
+ summary=summary_ops,
2719
+ hidden=hidden,
2720
+ goal=goal_cleaned,
2721
+ overwrite=overwrite,
2722
+ )
2723
+ m._set_callback(self._metric_callback)
2724
+ m._commit()
2725
+ with telemetry.context(run=self) as tel:
2726
+ tel.feature.metric = True
2727
+ return m
2728
+
2729
+ # TODO(jhr): annotate this
2730
+ @_run_decorator._attach
2731
+ def watch( # type: ignore
2732
+ self,
2733
+ models,
2734
+ criterion=None,
2735
+ log="gradients",
2736
+ log_freq=100,
2737
+ idx=None,
2738
+ log_graph=False,
2739
+ ) -> None:
2740
+ wandb.watch(models, criterion, log, log_freq, idx, log_graph)
2741
+
2742
+ # TODO(jhr): annotate this
2743
+ @_run_decorator._attach
2744
+ def unwatch(self, models=None) -> None: # type: ignore
2745
+ wandb.unwatch(models=models)
2746
+
2747
+ # TODO(kdg): remove all artifact swapping logic
2748
+ def _swap_artifact_name(self, artifact_name: str, use_as: Optional[str]) -> str:
2749
+ artifact_key_string = use_as or artifact_name
2750
+ replacement_artifact_info = self._launch_artifact_mapping.get(
2751
+ artifact_key_string
2752
+ )
2753
+ if replacement_artifact_info is not None:
2754
+ new_name = replacement_artifact_info.get("name")
2755
+ entity = replacement_artifact_info.get("entity")
2756
+ project = replacement_artifact_info.get("project")
2757
+ if new_name is None or entity is None or project is None:
2758
+ raise ValueError(
2759
+ "Misconfigured artifact in launch config. Must include name, project and entity keys."
2760
+ )
2761
+ return f"{entity}/{project}/{new_name}"
2762
+ elif replacement_artifact_info is None and use_as is None:
2763
+ sequence_name = artifact_name.split(":")[0].split("/")[-1]
2764
+ unique_artifact_replacement_info = (
2765
+ self._unique_launch_artifact_sequence_names.get(sequence_name)
2766
+ )
2767
+ if unique_artifact_replacement_info is not None:
2768
+ new_name = unique_artifact_replacement_info.get("name")
2769
+ entity = unique_artifact_replacement_info.get("entity")
2770
+ project = unique_artifact_replacement_info.get("project")
2771
+ if new_name is None or entity is None or project is None:
2772
+ raise ValueError(
2773
+ "Misconfigured artifact in launch config. Must include name, project and entity keys."
2774
+ )
2775
+ return f"{entity}/{project}/{new_name}"
2776
+
2777
+ else:
2778
+ return artifact_name
2779
+
2780
+ return artifact_name
2781
+
2782
+ def _detach(self) -> None:
2783
+ pass
2784
+
2785
+ @_run_decorator._noop_on_finish()
2786
+ @_run_decorator._attach
2787
+ def link_artifact(
2788
+ self,
2789
+ artifact: Artifact,
2790
+ target_path: str,
2791
+ aliases: Optional[List[str]] = None,
2792
+ ) -> None:
2793
+ """Link the given artifact to a portfolio (a promoted collection of artifacts).
2794
+
2795
+ The linked artifact will be visible in the UI for the specified portfolio.
2796
+
2797
+ Arguments:
2798
+ artifact: the (public or local) artifact which will be linked
2799
+ target_path: `str` - takes the following forms: {portfolio}, {project}/{portfolio},
2800
+ or {entity}/{project}/{portfolio}
2801
+ aliases: `List[str]` - optional alias(es) that will only be applied on this linked artifact
2802
+ inside the portfolio.
2803
+ The alias "latest" will always be applied to the latest version of an artifact that is linked.
2804
+
2805
+ Returns:
2806
+ None
2807
+
2808
+ """
2809
+ portfolio, project, entity = wandb.util._parse_entity_project_item(target_path)
2810
+ if aliases is None:
2811
+ aliases = []
2812
+
2813
+ if self._backend and self._backend.interface:
2814
+ if artifact.is_draft() and not artifact._is_draft_save_started():
2815
+ artifact = self._log_artifact(artifact)
2816
+ if not self._settings._offline:
2817
+ self._backend.interface.publish_link_artifact(
2818
+ self,
2819
+ artifact,
2820
+ portfolio,
2821
+ aliases,
2822
+ entity,
2823
+ project,
2824
+ )
2825
+ if artifact._ttl_duration_seconds is not None:
2826
+ wandb.termwarn(
2827
+ "Artifact TTL will be disabled for source artifacts that are linked to portfolios."
2828
+ )
2829
+ else:
2830
+ # TODO: implement offline mode + sync
2831
+ raise NotImplementedError
2832
+
2833
+ @_run_decorator._noop_on_finish()
2834
+ @_run_decorator._attach
2835
+ def use_artifact(
2836
+ self,
2837
+ artifact_or_name: Union[str, Artifact],
2838
+ type: Optional[str] = None,
2839
+ aliases: Optional[List[str]] = None,
2840
+ use_as: Optional[str] = None,
2841
+ ) -> Artifact:
2842
+ """Declare an artifact as an input to a run.
2843
+
2844
+ Call `download` or `file` on the returned object to get the contents locally.
2845
+
2846
+ Arguments:
2847
+ artifact_or_name: (str or Artifact) An artifact name.
2848
+ May be prefixed with entity/project/. Valid names
2849
+ can be in the following forms:
2850
+ - name:version
2851
+ - name:alias
2852
+ You can also pass an Artifact object created by calling `wandb.Artifact`
2853
+ type: (str, optional) The type of artifact to use.
2854
+ aliases: (list, optional) Aliases to apply to this artifact
2855
+ use_as: (string, optional) Optional string indicating what purpose the artifact was used with.
2856
+ Will be shown in UI.
2857
+
2858
+ Returns:
2859
+ An `Artifact` object.
2860
+ """
2861
+ if self._settings._offline:
2862
+ raise TypeError("Cannot use artifact when in offline mode.")
2863
+ r = self._run_obj
2864
+ assert r is not None
2865
+ api = internal.Api(default_settings={"entity": r.entity, "project": r.project})
2866
+ api.set_current_run_id(self._run_id)
2867
+
2868
+ if isinstance(artifact_or_name, str):
2869
+ if self._launch_artifact_mapping:
2870
+ name = self._swap_artifact_name(artifact_or_name, use_as)
2871
+ else:
2872
+ name = artifact_or_name
2873
+ public_api = self._public_api()
2874
+ artifact = public_api.artifact(type=type, name=name)
2875
+ if type is not None and type != artifact.type:
2876
+ raise ValueError(
2877
+ "Supplied type {} does not match type {} of artifact {}".format(
2878
+ type, artifact.type, artifact.name
2879
+ )
2880
+ )
2881
+ artifact._use_as = use_as or artifact_or_name
2882
+ if use_as:
2883
+ if (
2884
+ use_as in self._used_artifact_slots.keys()
2885
+ and self._used_artifact_slots[use_as] != artifact.id
2886
+ ):
2887
+ raise ValueError(
2888
+ "Cannot call use_artifact with the same use_as argument more than once"
2889
+ )
2890
+ elif ":" in use_as or "/" in use_as:
2891
+ raise ValueError(
2892
+ "use_as cannot contain special characters ':' or '/'"
2893
+ )
2894
+ self._used_artifact_slots[use_as] = artifact.id
2895
+ api.use_artifact(
2896
+ artifact.id,
2897
+ entity_name=r.entity,
2898
+ use_as=use_as or artifact_or_name,
2899
+ )
2900
+ else:
2901
+ artifact = artifact_or_name
2902
+ if aliases is None:
2903
+ aliases = []
2904
+ elif isinstance(aliases, str):
2905
+ aliases = [aliases]
2906
+ if isinstance(artifact_or_name, Artifact) and artifact.is_draft():
2907
+ if use_as is not None:
2908
+ wandb.termwarn(
2909
+ "Indicating use_as is not supported when using a draft artifact"
2910
+ )
2911
+ self._log_artifact(
2912
+ artifact,
2913
+ aliases=aliases,
2914
+ is_user_created=True,
2915
+ use_after_commit=True,
2916
+ )
2917
+ artifact.wait()
2918
+ artifact._use_as = use_as or artifact.name
2919
+ elif isinstance(artifact, Artifact) and not artifact.is_draft():
2920
+ if (
2921
+ self._launch_artifact_mapping
2922
+ and artifact.name in self._launch_artifact_mapping.keys()
2923
+ ):
2924
+ wandb.termwarn(
2925
+ "Swapping artifacts is not supported when using a non-draft artifact. "
2926
+ f"Using {artifact.name}."
2927
+ )
2928
+ artifact._use_as = use_as or artifact.name
2929
+ api.use_artifact(
2930
+ artifact.id, use_as=use_as or artifact._use_as or artifact.name
2931
+ )
2932
+ else:
2933
+ raise ValueError(
2934
+ 'You must pass an artifact name (e.g. "pedestrian-dataset:v1"), '
2935
+ "an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`"
2936
+ )
2937
+ if self._backend and self._backend.interface:
2938
+ self._backend.interface.publish_use_artifact(artifact)
2939
+ return artifact
2940
+
2941
+ @_run_decorator._noop_on_finish()
2942
+ @_run_decorator._attach
2943
+ def log_artifact(
2944
+ self,
2945
+ artifact_or_path: Union[Artifact, StrPath],
2946
+ name: Optional[str] = None,
2947
+ type: Optional[str] = None,
2948
+ aliases: Optional[List[str]] = None,
2949
+ ) -> Artifact:
2950
+ """Declare an artifact as an output of a run.
2951
+
2952
+ Arguments:
2953
+ artifact_or_path: (str or Artifact) A path to the contents of this artifact,
2954
+ can be in the following forms:
2955
+ - `/local/directory`
2956
+ - `/local/directory/file.txt`
2957
+ - `s3://bucket/path`
2958
+ You can also pass an Artifact object created by calling
2959
+ `wandb.Artifact`.
2960
+ name: (str, optional) An artifact name. May be prefixed with entity/project.
2961
+ Valid names can be in the following forms:
2962
+ - name:version
2963
+ - name:alias
2964
+ - digest
2965
+ This will default to the basename of the path prepended with the current
2966
+ run id if not specified.
2967
+ type: (str) The type of artifact to log, examples include `dataset`, `model`
2968
+ aliases: (list, optional) Aliases to apply to this artifact,
2969
+ defaults to `["latest"]`
2970
+
2971
+ Returns:
2972
+ An `Artifact` object.
2973
+ """
2974
+ return self._log_artifact(
2975
+ artifact_or_path, name=name, type=type, aliases=aliases
2976
+ )
2977
+
2978
+ @_run_decorator._noop_on_finish()
2979
+ @_run_decorator._attach
2980
+ def upsert_artifact(
2981
+ self,
2982
+ artifact_or_path: Union[Artifact, str],
2983
+ name: Optional[str] = None,
2984
+ type: Optional[str] = None,
2985
+ aliases: Optional[List[str]] = None,
2986
+ distributed_id: Optional[str] = None,
2987
+ ) -> Artifact:
2988
+ """Declare (or append to) a non-finalized artifact as output of a run.
2989
+
2990
+ Note that you must call run.finish_artifact() to finalize the artifact.
2991
+ This is useful when distributed jobs need to all contribute to the same artifact.
2992
+
2993
+ Arguments:
2994
+ artifact_or_path: (str or Artifact) A path to the contents of this artifact,
2995
+ can be in the following forms:
2996
+ - `/local/directory`
2997
+ - `/local/directory/file.txt`
2998
+ - `s3://bucket/path`
2999
+ You can also pass an Artifact object created by calling
3000
+ `wandb.Artifact`.
3001
+ name: (str, optional) An artifact name. May be prefixed with entity/project.
3002
+ Valid names can be in the following forms:
3003
+ - name:version
3004
+ - name:alias
3005
+ - digest
3006
+ This will default to the basename of the path prepended with the current
3007
+ run id if not specified.
3008
+ type: (str) The type of artifact to log, examples include `dataset`, `model`
3009
+ aliases: (list, optional) Aliases to apply to this artifact,
3010
+ defaults to `["latest"]`
3011
+ distributed_id: (string, optional) Unique string that all distributed jobs share. If None,
3012
+ defaults to the run's group name.
3013
+
3014
+ Returns:
3015
+ An `Artifact` object.
3016
+ """
3017
+ if self._get_group() == "" and distributed_id is None:
3018
+ raise TypeError(
3019
+ "Cannot upsert artifact unless run is in a group or distributed_id is provided"
3020
+ )
3021
+ if distributed_id is None:
3022
+ distributed_id = self._get_group()
3023
+ return self._log_artifact(
3024
+ artifact_or_path,
3025
+ name=name,
3026
+ type=type,
3027
+ aliases=aliases,
3028
+ distributed_id=distributed_id,
3029
+ finalize=False,
3030
+ )
3031
+
3032
+ @_run_decorator._noop_on_finish()
3033
+ @_run_decorator._attach
3034
+ def finish_artifact(
3035
+ self,
3036
+ artifact_or_path: Union[Artifact, str],
3037
+ name: Optional[str] = None,
3038
+ type: Optional[str] = None,
3039
+ aliases: Optional[List[str]] = None,
3040
+ distributed_id: Optional[str] = None,
3041
+ ) -> Artifact:
3042
+ """Finishes a non-finalized artifact as output of a run.
3043
+
3044
+ Subsequent "upserts" with the same distributed ID will result in a new version.
3045
+
3046
+ Arguments:
3047
+ artifact_or_path: (str or Artifact) A path to the contents of this artifact,
3048
+ can be in the following forms:
3049
+ - `/local/directory`
3050
+ - `/local/directory/file.txt`
3051
+ - `s3://bucket/path`
3052
+ You can also pass an Artifact object created by calling
3053
+ `wandb.Artifact`.
3054
+ name: (str, optional) An artifact name. May be prefixed with entity/project.
3055
+ Valid names can be in the following forms:
3056
+ - name:version
3057
+ - name:alias
3058
+ - digest
3059
+ This will default to the basename of the path prepended with the current
3060
+ run id if not specified.
3061
+ type: (str) The type of artifact to log, examples include `dataset`, `model`
3062
+ aliases: (list, optional) Aliases to apply to this artifact,
3063
+ defaults to `["latest"]`
3064
+ distributed_id: (string, optional) Unique string that all distributed jobs share. If None,
3065
+ defaults to the run's group name.
3066
+
3067
+ Returns:
3068
+ An `Artifact` object.
3069
+ """
3070
+ if self._get_group() == "" and distributed_id is None:
3071
+ raise TypeError(
3072
+ "Cannot finish artifact unless run is in a group or distributed_id is provided"
3073
+ )
3074
+ if distributed_id is None:
3075
+ distributed_id = self._get_group()
3076
+
3077
+ return self._log_artifact(
3078
+ artifact_or_path,
3079
+ name,
3080
+ type,
3081
+ aliases,
3082
+ distributed_id=distributed_id,
3083
+ finalize=True,
3084
+ )
3085
+
3086
+ def _log_artifact(
3087
+ self,
3088
+ artifact_or_path: Union[Artifact, StrPath],
3089
+ name: Optional[str] = None,
3090
+ type: Optional[str] = None,
3091
+ aliases: Optional[List[str]] = None,
3092
+ distributed_id: Optional[str] = None,
3093
+ finalize: bool = True,
3094
+ is_user_created: bool = False,
3095
+ use_after_commit: bool = False,
3096
+ ) -> Artifact:
3097
+ api = internal.Api()
3098
+ if api.settings().get("anonymous") == "true":
3099
+ wandb.termwarn(
3100
+ "Artifacts logged anonymously cannot be claimed and expire after 7 days."
3101
+ )
3102
+ if not finalize and distributed_id is None:
3103
+ raise TypeError("Must provide distributed_id if artifact is not finalize")
3104
+ if aliases is not None:
3105
+ if any(invalid in alias for alias in aliases for invalid in ["/", ":"]):
3106
+ raise ValueError(
3107
+ "Aliases must not contain any of the following characters: /, :"
3108
+ )
3109
+ artifact, aliases = self._prepare_artifact(
3110
+ artifact_or_path, name, type, aliases
3111
+ )
3112
+ artifact.distributed_id = distributed_id
3113
+ self._assert_can_log_artifact(artifact)
3114
+ if self._backend and self._backend.interface:
3115
+ if not self._settings._offline:
3116
+ future = self._backend.interface.communicate_artifact(
3117
+ self,
3118
+ artifact,
3119
+ aliases,
3120
+ self.step,
3121
+ finalize=finalize,
3122
+ is_user_created=is_user_created,
3123
+ use_after_commit=use_after_commit,
3124
+ )
3125
+ artifact._set_save_future(future, self._public_api().client)
3126
+ else:
3127
+ self._backend.interface.publish_artifact(
3128
+ self,
3129
+ artifact,
3130
+ aliases,
3131
+ finalize=finalize,
3132
+ is_user_created=is_user_created,
3133
+ use_after_commit=use_after_commit,
3134
+ )
3135
+ elif self._internal_run_interface:
3136
+ self._internal_run_interface.publish_artifact(
3137
+ self,
3138
+ artifact,
3139
+ aliases,
3140
+ finalize=finalize,
3141
+ is_user_created=is_user_created,
3142
+ use_after_commit=use_after_commit,
3143
+ )
3144
+ return artifact
3145
+
3146
+ def _public_api(self, overrides: Optional[Dict[str, str]] = None) -> PublicApi:
3147
+ overrides = {"run": self._run_id}
3148
+ if not (self._settings._offline or self._run_obj is None):
3149
+ overrides["entity"] = self._run_obj.entity
3150
+ overrides["project"] = self._run_obj.project
3151
+ return public.Api(overrides)
3152
+
3153
+ # TODO(jhr): annotate this
3154
+ def _assert_can_log_artifact(self, artifact) -> None: # type: ignore
3155
+ if self._settings._offline:
3156
+ return
3157
+ try:
3158
+ public_api = self._public_api()
3159
+ entity = public_api.settings["entity"]
3160
+ project = public_api.settings["project"]
3161
+ expected_type = Artifact._expected_type(
3162
+ entity, project, artifact.name, public_api.client
3163
+ )
3164
+ except requests.exceptions.RequestException:
3165
+ # Just return early if there is a network error. This is
3166
+ # ok, as this function is intended to help catch an invalid
3167
+ # type early, but not a hard requirement for valid operation.
3168
+ return
3169
+ if expected_type is not None and artifact.type != expected_type:
3170
+ raise ValueError(
3171
+ f"Artifact {artifact.name} already exists with type '{expected_type}'; "
3172
+ f"cannot create another with type '{artifact.type}'"
3173
+ )
3174
+ if entity and artifact._source_entity and entity != artifact._source_entity:
3175
+ raise ValueError(
3176
+ f"Artifact {artifact.name} is owned by entity "
3177
+ f"'{artifact._source_entity}'; it can't be moved to '{entity}'"
3178
+ )
3179
+ if project and artifact._source_project and project != artifact._source_project:
3180
+ raise ValueError(
3181
+ f"Artifact {artifact.name} exists in project "
3182
+ f"'{artifact._source_project}'; it can't be moved to '{project}'"
3183
+ )
3184
+
3185
+ def _prepare_artifact(
3186
+ self,
3187
+ artifact_or_path: Union[Artifact, StrPath],
3188
+ name: Optional[str] = None,
3189
+ type: Optional[str] = None,
3190
+ aliases: Optional[List[str]] = None,
3191
+ ) -> Tuple[Artifact, List[str]]:
3192
+ if isinstance(artifact_or_path, (str, os.PathLike)):
3193
+ name = name or f"run-{self._run_id}-{os.path.basename(artifact_or_path)}"
3194
+ artifact = wandb.Artifact(name, type or "unspecified")
3195
+ if os.path.isfile(artifact_or_path):
3196
+ artifact.add_file(str(artifact_or_path))
3197
+ elif os.path.isdir(artifact_or_path):
3198
+ artifact.add_dir(str(artifact_or_path))
3199
+ elif "://" in str(artifact_or_path):
3200
+ artifact.add_reference(str(artifact_or_path))
3201
+ else:
3202
+ raise ValueError(
3203
+ "path must be a file, directory or external"
3204
+ "reference like s3://bucket/path"
3205
+ )
3206
+ else:
3207
+ artifact = artifact_or_path
3208
+ if not isinstance(artifact, wandb.Artifact):
3209
+ raise ValueError(
3210
+ "You must pass an instance of wandb.Artifact or a "
3211
+ "valid file path to log_artifact"
3212
+ )
3213
+ artifact.finalize()
3214
+ return artifact, _resolve_aliases(aliases)
3215
+
3216
+ @_run_decorator._noop_on_finish()
3217
+ @_run_decorator._attach
3218
+ def log_model(
3219
+ self,
3220
+ path: StrPath,
3221
+ name: Optional[str] = None,
3222
+ aliases: Optional[List[str]] = None,
3223
+ ) -> None:
3224
+ """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run.
3225
+
3226
+ Arguments:
3227
+ path: (str) A path to the contents of this model,
3228
+ can be in the following forms:
3229
+ - `/local/directory`
3230
+ - `/local/directory/file.txt`
3231
+ - `s3://bucket/path`
3232
+ name: (str, optional) A name to assign to the model artifact that the file contents will be added to.
3233
+ The string must contain only the following alphanumeric characters: dashes, underscores, and dots.
3234
+ This will default to the basename of the path prepended with the current
3235
+ run id if not specified.
3236
+ aliases: (list, optional) Aliases to apply to the created model artifact,
3237
+ defaults to `["latest"]`
3238
+
3239
+ Examples:
3240
+ ```python
3241
+ run.log_model(
3242
+ path="/local/directory",
3243
+ name="my_model_artifact",
3244
+ aliases=["production"],
3245
+ )
3246
+ ```
3247
+
3248
+ Invalid usage
3249
+ ```python
3250
+ run.log_model(
3251
+ path="/local/directory",
3252
+ name="my_entity/my_project/my_model_artifact",
3253
+ aliases=["production"],
3254
+ )
3255
+ ```
3256
+
3257
+ Raises:
3258
+ ValueError: if name has invalid special characters
3259
+
3260
+ Returns:
3261
+ None
3262
+ """
3263
+ self._log_artifact(
3264
+ artifact_or_path=path, name=name, type="model", aliases=aliases
3265
+ )
3266
+
3267
+ @_run_decorator._noop_on_finish()
3268
+ @_run_decorator._attach
3269
+ def use_model(self, name: str) -> FilePathStr:
3270
+ """Download the files logged in a model artifact 'name'.
3271
+
3272
+ Arguments:
3273
+ name: (str) A model artifact name. 'name' must match the name of an existing logged
3274
+ model artifact.
3275
+ May be prefixed with entity/project/. Valid names
3276
+ can be in the following forms:
3277
+ - model_artifact_name:version
3278
+ - model_artifact_name:alias
3279
+
3280
+ Examples:
3281
+ ```python
3282
+ run.use_model(
3283
+ name="my_model_artifact:latest",
3284
+ )
3285
+
3286
+ run.use_model(
3287
+ name="my_project/my_model_artifact:v0",
3288
+ )
3289
+
3290
+ run.use_model(
3291
+ name="my_entity/my_project/my_model_artifact:<digest>",
3292
+ )
3293
+ ```
3294
+
3295
+ Invalid usage
3296
+ ```python
3297
+ run.use_model(
3298
+ name="my_entity/my_project/my_model_artifact",
3299
+ )
3300
+ ```
3301
+
3302
+ Raises:
3303
+ AssertionError: if model artifact 'name' is of a type that does not contain the substring 'model'.
3304
+
3305
+ Returns:
3306
+ path: (str) path to downloaded model artifact file(s).
3307
+ """
3308
+ artifact = self.use_artifact(artifact_or_name=name)
3309
+ assert (
3310
+ "model" in str(artifact.type.lower())
3311
+ ), "You can only use this method for 'model' artifacts. For an artifact to be a 'model' artifact, its type property must contain the substring 'model'."
3312
+ path = artifact.download()
3313
+
3314
+ # If returned directory contains only one file, return path to that file
3315
+ dir_list = os.listdir(path)
3316
+ if len(dir_list) == 1:
3317
+ return FilePathStr(os.path.join(path, dir_list[0]))
3318
+ return path
3319
+
3320
+ @_run_decorator._noop_on_finish()
3321
+ @_run_decorator._attach
3322
+ def link_model(
3323
+ self,
3324
+ path: StrPath,
3325
+ registered_model_name: str,
3326
+ name: Optional[str] = None,
3327
+ aliases: Optional[List[str]] = None,
3328
+ ) -> None:
3329
+ """Log a model artifact version and link it to a registered model in the model registry.
3330
+
3331
+ The linked model version will be visible in the UI for the specified registered model.
3332
+
3333
+ Steps:
3334
+ - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files
3335
+ located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name'
3336
+ of type 'model'.
3337
+ - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project.
3338
+ If not, create a new registered model with name 'registered_model_name'.
3339
+ - Link version of model artifact 'name' to registered model, 'registered_model_name'.
3340
+ - Attach aliases from 'aliases' list to the newly linked model artifact version.
3341
+
3342
+ Arguments:
3343
+ path: (str) A path to the contents of this model,
3344
+ can be in the following forms:
3345
+ - `/local/directory`
3346
+ - `/local/directory/file.txt`
3347
+ - `s3://bucket/path`
3348
+ registered_model_name: (str) - the name of the registered model that the model is to be linked to.
3349
+ A registered model is a collection of model versions linked to the model registry, typically representing a
3350
+ team's specific ML Task. The entity that this registered model belongs to will be derived from the run
3351
+ name: (str, optional) - the name of the model artifact that files in 'path' will be logged to. This will
3352
+ default to the basename of the path prepended with the current run id if not specified.
3353
+ aliases: (List[str], optional) - alias(es) that will only be applied on this linked artifact
3354
+ inside the registered model.
3355
+ The alias "latest" will always be applied to the latest version of an artifact that is linked.
3356
+
3357
+ Examples:
3358
+ ```python
3359
+ run.link_model(
3360
+ path="/local/directory",
3361
+ registered_model_name="my_reg_model",
3362
+ name="my_model_artifact",
3363
+ aliases=["production"],
3364
+ )
3365
+ ```
3366
+
3367
+ Invalid usage
3368
+ ```python
3369
+ run.link_model(
3370
+ path="/local/directory",
3371
+ registered_model_name="my_entity/my_project/my_reg_model",
3372
+ name="my_model_artifact",
3373
+ aliases=["production"],
3374
+ )
3375
+
3376
+ run.link_model(
3377
+ path="/local/directory",
3378
+ registered_model_name="my_reg_model",
3379
+ name="my_entity/my_project/my_model_artifact",
3380
+ aliases=["production"],
3381
+ )
3382
+ ```
3383
+
3384
+ Raises:
3385
+ AssertionError: if registered_model_name is a path or
3386
+ if model artifact 'name' is of a type that does not contain the substring 'model'
3387
+ ValueError: if name has invalid special characters
3388
+
3389
+ Returns:
3390
+ None
3391
+ """
3392
+ name_parts = registered_model_name.split("/")
3393
+ assert (
3394
+ len(name_parts) == 1
3395
+ ), "Please provide only the name of the registered model. Do not append the entity or project name."
3396
+ project = "model-registry"
3397
+ target_path = self.entity + "/" + project + "/" + registered_model_name
3398
+
3399
+ public_api = self._public_api()
3400
+ try:
3401
+ artifact = public_api.artifact(name=f"{name}:latest")
3402
+ assert (
3403
+ "model" in str(artifact.type.lower())
3404
+ ), "You can only use this method for 'model' artifacts. For an artifact to be a 'model' artifact, its type property must contain the substring 'model'."
3405
+ artifact = self._log_artifact(
3406
+ artifact_or_path=path, name=name, type=artifact.type
3407
+ )
3408
+ except (ValueError, wandb.CommError):
3409
+ artifact = self._log_artifact(
3410
+ artifact_or_path=path, name=name, type="model"
3411
+ )
3412
+ self.link_artifact(artifact=artifact, target_path=target_path, aliases=aliases)
3413
+
3414
+ @_run_decorator._noop_on_finish()
3415
+ @_run_decorator._attach
3416
+ def alert(
3417
+ self,
3418
+ title: str,
3419
+ text: str,
3420
+ level: Optional[Union[str, "AlertLevel"]] = None,
3421
+ wait_duration: Union[int, float, timedelta, None] = None,
3422
+ ) -> None:
3423
+ """Launch an alert with the given title and text.
3424
+
3425
+ Arguments:
3426
+ title: (str) The title of the alert, must be less than 64 characters long.
3427
+ text: (str) The text body of the alert.
3428
+ level: (str or wandb.AlertLevel, optional) The alert level to use, either: `INFO`, `WARN`, or `ERROR`.
3429
+ wait_duration: (int, float, or timedelta, optional) The time to wait (in seconds) before sending another
3430
+ alert with this title.
3431
+ """
3432
+ level = level or wandb.AlertLevel.INFO
3433
+ level_str: str = level.value if isinstance(level, wandb.AlertLevel) else level
3434
+ if level_str not in {lev.value for lev in wandb.AlertLevel}:
3435
+ raise ValueError("level must be one of 'INFO', 'WARN', or 'ERROR'")
3436
+
3437
+ wait_duration = wait_duration or timedelta(minutes=1)
3438
+ if isinstance(wait_duration, int) or isinstance(wait_duration, float):
3439
+ wait_duration = timedelta(seconds=wait_duration)
3440
+ elif not callable(getattr(wait_duration, "total_seconds", None)):
3441
+ raise ValueError(
3442
+ "wait_duration must be an int, float, or datetime.timedelta"
3443
+ )
3444
+ wait_duration = int(wait_duration.total_seconds() * 1000)
3445
+
3446
+ if self._backend and self._backend.interface:
3447
+ self._backend.interface.publish_alert(title, text, level_str, wait_duration)
3448
+
3449
+ def __enter__(self) -> "Run":
3450
+ return self
3451
+
3452
+ def __exit__(
3453
+ self,
3454
+ exc_type: Type[BaseException],
3455
+ exc_val: BaseException,
3456
+ exc_tb: TracebackType,
3457
+ ) -> bool:
3458
+ exception_raised = exc_type is not None
3459
+ if exception_raised:
3460
+ traceback.print_exception(exc_type, exc_val, exc_tb)
3461
+ exit_code = 1 if exception_raised else 0
3462
+ self._finish(exit_code=exit_code)
3463
+ return not exception_raised
3464
+
3465
+ @_run_decorator._noop_on_finish()
3466
+ @_run_decorator._attach
3467
+ def mark_preempting(self) -> None:
3468
+ """Mark this run as preempting.
3469
+
3470
+ Also tells the internal process to immediately report this to server.
3471
+ """
3472
+ if self._backend and self._backend.interface:
3473
+ self._backend.interface.publish_preempting()
3474
+
3475
+ @property
3476
+ @_run_decorator._noop_on_finish()
3477
+ @_run_decorator._attach
3478
+ def _system_metrics(self) -> Dict[str, List[Tuple[datetime, float]]]:
3479
+ """Returns a dictionary of system metrics.
3480
+
3481
+ Returns:
3482
+ A dictionary of system metrics.
3483
+ """
3484
+
3485
+ def pb_to_dict(
3486
+ system_metrics_pb: wandb.proto.wandb_internal_pb2.GetSystemMetricsResponse,
3487
+ ) -> Dict[str, List[Tuple[datetime, float]]]:
3488
+ res = {}
3489
+
3490
+ for metric, records in system_metrics_pb.system_metrics.items():
3491
+ measurements = []
3492
+ for record in records.record:
3493
+ # Convert timestamp to datetime
3494
+ dt = datetime.fromtimestamp(
3495
+ record.timestamp.seconds, tz=timezone.utc
3496
+ )
3497
+ dt = dt.replace(microsecond=record.timestamp.nanos // 1000)
3498
+
3499
+ measurements.append((dt, record.value))
3500
+
3501
+ res[metric] = measurements
3502
+
3503
+ return res
3504
+
3505
+ if not self._backend or not self._backend.interface:
3506
+ return {}
3507
+
3508
+ handle = self._backend.interface.deliver_get_system_metrics()
3509
+ result = handle.wait(timeout=1)
3510
+
3511
+ if result:
3512
+ try:
3513
+ response = result.response.get_system_metrics_response
3514
+ if response:
3515
+ return pb_to_dict(response)
3516
+ except Exception as e:
3517
+ logger.error("Error getting system metrics: %s", e)
3518
+ return {}
3519
+
3520
+ # ------------------------------------------------------------------------------
3521
+ # HEADER
3522
+ # ------------------------------------------------------------------------------
3523
+ # Note: All the header methods are static methods since we want to share the printing logic
3524
+ # with the service execution path that doesn't have access to the run instance
3525
+ @staticmethod
3526
+ def _header(
3527
+ check_version: Optional["CheckVersionResponse"] = None,
3528
+ *,
3529
+ settings: "Settings",
3530
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3531
+ ) -> None:
3532
+ Run._header_version_check_info(
3533
+ check_version, settings=settings, printer=printer
3534
+ )
3535
+ Run._header_wandb_version_info(settings=settings, printer=printer)
3536
+ Run._header_sync_info(settings=settings, printer=printer)
3537
+ Run._header_run_info(settings=settings, printer=printer)
3538
+
3539
+ @staticmethod
3540
+ def _header_version_check_info(
3541
+ check_version: Optional["CheckVersionResponse"] = None,
3542
+ *,
3543
+ settings: "Settings",
3544
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3545
+ ) -> None:
3546
+ if not check_version or settings._offline:
3547
+ return
3548
+
3549
+ if check_version.delete_message:
3550
+ printer.display(check_version.delete_message, level="error")
3551
+ elif check_version.yank_message:
3552
+ printer.display(check_version.yank_message, level="warn")
3553
+
3554
+ printer.display(
3555
+ check_version.upgrade_message, off=not check_version.upgrade_message
3556
+ )
3557
+
3558
+ @staticmethod
3559
+ def _header_wandb_version_info(
3560
+ *,
3561
+ settings: "Settings",
3562
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3563
+ ) -> None:
3564
+ if settings.quiet or settings.silent:
3565
+ return
3566
+
3567
+ # TODO: add this to a higher verbosity level
3568
+ printer.display(
3569
+ f"Tracking run with wandb version {wandb.__version__}", off=False
3570
+ )
3571
+
3572
+ @staticmethod
3573
+ def _header_sync_info(
3574
+ *,
3575
+ settings: "Settings",
3576
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3577
+ ) -> None:
3578
+ if settings._offline:
3579
+ printer.display(
3580
+ [
3581
+ f"W&B syncing is set to {printer.code('`offline`')} in this directory. ",
3582
+ f"Run {printer.code('`wandb online`')} or set {printer.code('WANDB_MODE=online')} "
3583
+ "to enable cloud syncing.",
3584
+ ]
3585
+ )
3586
+ else:
3587
+ info = [f"Run data is saved locally in {printer.files(settings.sync_dir)}"]
3588
+ if not printer._html:
3589
+ info.append(
3590
+ f"Run {printer.code('`wandb offline`')} to turn off syncing."
3591
+ )
3592
+ printer.display(info, off=settings.quiet or settings.silent)
3593
+
3594
+ @staticmethod
3595
+ def _header_run_info(
3596
+ *,
3597
+ settings: "Settings",
3598
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3599
+ ) -> None:
3600
+ if settings._offline or settings.silent:
3601
+ return
3602
+
3603
+ run_url = settings.run_url
3604
+ project_url = settings.project_url
3605
+ sweep_url = settings.sweep_url
3606
+
3607
+ run_state_str = "Resuming run" if settings.resumed else "Syncing run"
3608
+ run_name = settings.run_name
3609
+ if not run_name:
3610
+ return
3611
+
3612
+ if printer._html:
3613
+ if not wandb.jupyter.maybe_display():
3614
+ run_line = f"<strong>{printer.link(run_url, run_name)}</strong>"
3615
+ project_line, sweep_line = "", ""
3616
+
3617
+ # TODO(settings): make settings the source of truth
3618
+ if not wandb.jupyter.quiet():
3619
+ doc_html = printer.link(wburls.get("doc_run"), "docs")
3620
+
3621
+ project_html = printer.link(project_url, "Weights & Biases")
3622
+ project_line = f"to {project_html} ({doc_html})"
3623
+
3624
+ if sweep_url:
3625
+ sweep_line = f"Sweep page: {printer.link(sweep_url, sweep_url)}"
3626
+
3627
+ printer.display(
3628
+ [f"{run_state_str} {run_line} {project_line}", sweep_line],
3629
+ )
3630
+
3631
+ else:
3632
+ printer.display(
3633
+ f"{run_state_str} {printer.name(run_name)}", off=not run_name
3634
+ )
3635
+
3636
+ if not settings.quiet:
3637
+ # TODO: add verbosity levels and add this to higher levels
3638
+ printer.display(
3639
+ f'{printer.emoji("star")} View project at {printer.link(project_url)}'
3640
+ )
3641
+ if sweep_url:
3642
+ printer.display(
3643
+ f'{printer.emoji("broom")} View sweep at {printer.link(sweep_url)}'
3644
+ )
3645
+ printer.display(
3646
+ f'{printer.emoji("rocket")} View run at {printer.link(run_url)}',
3647
+ )
3648
+
3649
+ # TODO(settings) use `wandb_settings` (if self.settings.anonymous == "true":)
3650
+ if Api().api.settings().get("anonymous") == "true":
3651
+ printer.display(
3652
+ "Do NOT share these links with anyone. They can be used to claim your runs.",
3653
+ level="warn",
3654
+ off=not run_name,
3655
+ )
3656
+
3657
+ # ------------------------------------------------------------------------------
3658
+ # FOOTER
3659
+ # ------------------------------------------------------------------------------
3660
+ # Note: All the footer methods are static methods since we want to share the printing logic
3661
+ # with the service execution path that doesn't have acess to the run instance
3662
+ @staticmethod
3663
+ def _footer(
3664
+ sampled_history: Optional["SampledHistoryResponse"] = None,
3665
+ final_summary: Optional["GetSummaryResponse"] = None,
3666
+ poll_exit_response: Optional[PollExitResponse] = None,
3667
+ server_info_response: Optional[ServerInfoResponse] = None,
3668
+ check_version_response: Optional["CheckVersionResponse"] = None,
3669
+ internal_messages_response: Optional["InternalMessagesResponse"] = None,
3670
+ reporter: Optional[Reporter] = None,
3671
+ quiet: Optional[bool] = None,
3672
+ *,
3673
+ settings: "Settings",
3674
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3675
+ ) -> None:
3676
+ Run._footer_history_summary_info(
3677
+ history=sampled_history,
3678
+ summary=final_summary,
3679
+ quiet=quiet,
3680
+ settings=settings,
3681
+ printer=printer,
3682
+ )
3683
+
3684
+ Run._footer_sync_info(
3685
+ poll_exit_response=poll_exit_response,
3686
+ quiet=quiet,
3687
+ settings=settings,
3688
+ printer=printer,
3689
+ )
3690
+ Run._footer_log_dir_info(quiet=quiet, settings=settings, printer=printer)
3691
+ Run._footer_version_check_info(
3692
+ check_version=check_version_response,
3693
+ quiet=quiet,
3694
+ settings=settings,
3695
+ printer=printer,
3696
+ )
3697
+ Run._footer_local_warn(
3698
+ server_info_response=server_info_response,
3699
+ quiet=quiet,
3700
+ settings=settings,
3701
+ printer=printer,
3702
+ )
3703
+ Run._footer_internal_messages(
3704
+ internal_messages_response=internal_messages_response,
3705
+ quiet=quiet,
3706
+ settings=settings,
3707
+ printer=printer,
3708
+ )
3709
+ Run._footer_reporter_warn_err(
3710
+ reporter=reporter, quiet=quiet, settings=settings, printer=printer
3711
+ )
3712
+ Run._footer_server_messages(
3713
+ server_info_response=server_info_response,
3714
+ quiet=quiet,
3715
+ settings=settings,
3716
+ printer=printer,
3717
+ )
3718
+
3719
+ @staticmethod
3720
+ def _footer_exit_status_info(
3721
+ exit_code: Optional[int],
3722
+ *,
3723
+ settings: "Settings",
3724
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3725
+ ) -> None:
3726
+ if settings.silent:
3727
+ return
3728
+
3729
+ status = "(success)." if not exit_code else f"(failed {exit_code})."
3730
+ info = [
3731
+ f"Waiting for W&B process to finish... {printer.status(status, bool(exit_code))}"
3732
+ ]
3733
+
3734
+ if not settings._offline and exit_code:
3735
+ info.append(f"Press {printer.abort()} to abort syncing.")
3736
+
3737
+ printer.display(f'{" ".join(info)}')
3738
+
3739
+ # fixme: Temporary hack until we move to rich which allows multiple spinners
3740
+ @staticmethod
3741
+ def _footer_file_pusher_status_info(
3742
+ poll_exit_responses: Optional[
3743
+ Union[PollExitResponse, List[Optional[PollExitResponse]]]
3744
+ ] = None,
3745
+ *,
3746
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3747
+ ) -> None:
3748
+ if not poll_exit_responses:
3749
+ return
3750
+ if isinstance(poll_exit_responses, PollExitResponse):
3751
+ Run._footer_single_run_file_pusher_status_info(
3752
+ poll_exit_responses, printer=printer
3753
+ )
3754
+ elif isinstance(poll_exit_responses, list):
3755
+ poll_exit_responses_list = poll_exit_responses
3756
+ assert all(
3757
+ response is None or isinstance(response, PollExitResponse)
3758
+ for response in poll_exit_responses_list
3759
+ )
3760
+ if len(poll_exit_responses_list) == 0:
3761
+ return
3762
+ elif len(poll_exit_responses_list) == 1:
3763
+ Run._footer_single_run_file_pusher_status_info(
3764
+ poll_exit_responses_list[0], printer=printer
3765
+ )
3766
+ else:
3767
+ Run._footer_multiple_runs_file_pusher_status_info(
3768
+ poll_exit_responses_list, printer=printer
3769
+ )
3770
+ else:
3771
+ logger.error(
3772
+ f"Got the type `{type(poll_exit_responses)}` for `poll_exit_responses`. "
3773
+ "Expected either None, PollExitResponse or a List[Union[PollExitResponse, None]]"
3774
+ )
3775
+
3776
+ @staticmethod
3777
+ def _footer_single_run_file_pusher_status_info(
3778
+ poll_exit_response: Optional[PollExitResponse] = None,
3779
+ *,
3780
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3781
+ ) -> None:
3782
+ # todo: is this same as settings._offline?
3783
+ if not poll_exit_response:
3784
+ return
3785
+
3786
+ progress = poll_exit_response.pusher_stats
3787
+ done = poll_exit_response.done
3788
+
3789
+ megabyte = wandb.util.POW_2_BYTES[2][1]
3790
+ line = f"{progress.uploaded_bytes / megabyte :.3f} MB of {progress.total_bytes / megabyte:.3f} MB uploaded"
3791
+ if progress.deduped_bytes > 0:
3792
+ line += f" ({progress.deduped_bytes / megabyte:.3f} MB deduped)\r"
3793
+ else:
3794
+ line += "\r"
3795
+
3796
+ percent_done = (
3797
+ 1.0
3798
+ if progress.total_bytes == 0
3799
+ else progress.uploaded_bytes / progress.total_bytes
3800
+ )
3801
+
3802
+ printer.progress_update(line, percent_done)
3803
+ if done:
3804
+ printer.progress_close()
3805
+
3806
+ dedupe_fraction = (
3807
+ progress.deduped_bytes / float(progress.total_bytes)
3808
+ if progress.total_bytes > 0
3809
+ else 0
3810
+ )
3811
+ if dedupe_fraction > 0.01:
3812
+ printer.display(
3813
+ f"W&B sync reduced upload amount by {dedupe_fraction * 100:.1f}% "
3814
+ )
3815
+
3816
+ @staticmethod
3817
+ def _footer_multiple_runs_file_pusher_status_info(
3818
+ poll_exit_responses: List[Optional[PollExitResponse]],
3819
+ *,
3820
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3821
+ ) -> None:
3822
+ # todo: is this same as settings._offline?
3823
+ if not all(poll_exit_responses):
3824
+ return
3825
+
3826
+ megabyte = wandb.util.POW_2_BYTES[2][1]
3827
+ total_files: int = sum(
3828
+ sum(
3829
+ [
3830
+ response.file_counts.wandb_count,
3831
+ response.file_counts.media_count,
3832
+ response.file_counts.artifact_count,
3833
+ response.file_counts.other_count,
3834
+ ]
3835
+ )
3836
+ for response in poll_exit_responses
3837
+ if response is not None and response.file_counts is not None
3838
+ )
3839
+ uploaded = sum(
3840
+ response.pusher_stats.uploaded_bytes
3841
+ for response in poll_exit_responses
3842
+ if response is not None and response.pusher_stats is not None
3843
+ )
3844
+ total = sum(
3845
+ response.pusher_stats.total_bytes
3846
+ for response in poll_exit_responses
3847
+ if response is not None and response.pusher_stats is not None
3848
+ )
3849
+
3850
+ line = (
3851
+ f"Processing {len(poll_exit_responses)} runs with {total_files} files "
3852
+ f"({uploaded/megabyte :.2f} MB/{total/megabyte :.2f} MB)\r"
3853
+ )
3854
+ # line = "{}{:<{max_len}}\r".format(line, " ", max_len=(80 - len(line)))
3855
+ printer.progress_update(line) # type:ignore[call-arg]
3856
+
3857
+ done = all(
3858
+ [
3859
+ poll_exit_response.done
3860
+ for poll_exit_response in poll_exit_responses
3861
+ if poll_exit_response
3862
+ ]
3863
+ )
3864
+ if done:
3865
+ printer.progress_close()
3866
+
3867
+ @staticmethod
3868
+ def _footer_sync_info(
3869
+ poll_exit_response: Optional[PollExitResponse] = None,
3870
+ quiet: Optional[bool] = None,
3871
+ *,
3872
+ settings: "Settings",
3873
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3874
+ ) -> None:
3875
+ if settings.silent:
3876
+ return
3877
+
3878
+ if settings._offline:
3879
+ printer.display(
3880
+ [
3881
+ "You can sync this run to the cloud by running:",
3882
+ printer.code(f"wandb sync {settings.sync_dir}"),
3883
+ ],
3884
+ off=(quiet or settings.quiet),
3885
+ )
3886
+ else:
3887
+ info = []
3888
+ if settings.run_name and settings.run_url:
3889
+ info.append(
3890
+ f"{printer.emoji('rocket')} View run {printer.name(settings.run_name)} at: {printer.link(settings.run_url)}"
3891
+ )
3892
+ if settings.project_url:
3893
+ info.append(
3894
+ f"{printer.emoji('star')} View project at: {printer.link(settings.project_url)}"
3895
+ )
3896
+ if poll_exit_response and poll_exit_response.file_counts:
3897
+ logger.info("logging synced files")
3898
+ file_counts = poll_exit_response.file_counts
3899
+ info.append(
3900
+ f"Synced {file_counts.wandb_count} W&B file(s), {file_counts.media_count} media file(s), "
3901
+ f"{file_counts.artifact_count} artifact file(s) and {file_counts.other_count} other file(s)",
3902
+ )
3903
+ printer.display(info)
3904
+
3905
+ @staticmethod
3906
+ def _footer_log_dir_info(
3907
+ quiet: Optional[bool] = None,
3908
+ *,
3909
+ settings: "Settings",
3910
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3911
+ ) -> None:
3912
+ if (quiet or settings.quiet) or settings.silent:
3913
+ return
3914
+
3915
+ log_dir = settings.log_user or settings.log_internal
3916
+ if log_dir:
3917
+ log_dir = os.path.dirname(log_dir.replace(os.getcwd(), "."))
3918
+ printer.display(
3919
+ f"Find logs at: {printer.files(log_dir)}",
3920
+ )
3921
+
3922
+ @staticmethod
3923
+ def _footer_history_summary_info(
3924
+ history: Optional["SampledHistoryResponse"] = None,
3925
+ summary: Optional["GetSummaryResponse"] = None,
3926
+ quiet: Optional[bool] = None,
3927
+ *,
3928
+ settings: "Settings",
3929
+ printer: Union["PrinterTerm", "PrinterJupyter"],
3930
+ ) -> None:
3931
+ if (quiet or settings.quiet) or settings.silent:
3932
+ return
3933
+
3934
+ panel = []
3935
+
3936
+ # Render history if available
3937
+ if history:
3938
+ logger.info("rendering history")
3939
+
3940
+ sampled_history = {
3941
+ item.key: wandb.util.downsample(
3942
+ item.values_float or item.values_int, 40
3943
+ )
3944
+ for item in history.item
3945
+ if not item.key.startswith("_")
3946
+ }
3947
+
3948
+ history_rows = []
3949
+ for key, values in sorted(sampled_history.items()):
3950
+ if any(not isinstance(value, numbers.Number) for value in values):
3951
+ continue
3952
+ sparkline = printer.sparklines(values)
3953
+ if sparkline:
3954
+ history_rows.append([key, sparkline])
3955
+ if history_rows:
3956
+ history_grid = printer.grid(
3957
+ history_rows,
3958
+ "Run history:",
3959
+ )
3960
+ panel.append(history_grid)
3961
+
3962
+ # Render summary if available
3963
+ if summary:
3964
+ final_summary = {
3965
+ item.key: json.loads(item.value_json)
3966
+ for item in summary.item
3967
+ if not item.key.startswith("_")
3968
+ }
3969
+
3970
+ logger.info("rendering summary")
3971
+ summary_rows = []
3972
+ for key, value in sorted(final_summary.items()):
3973
+ # arrays etc. might be too large. for now, we just don't print them
3974
+ if isinstance(value, str):
3975
+ value = value[:20] + "..." * (len(value) >= 20)
3976
+ summary_rows.append([key, value])
3977
+ elif isinstance(value, numbers.Number):
3978
+ value = round(value, 5) if isinstance(value, float) else value
3979
+ summary_rows.append([key, str(value)])
3980
+ else:
3981
+ continue
3982
+
3983
+ if summary_rows:
3984
+ summary_grid = printer.grid(
3985
+ summary_rows,
3986
+ "Run summary:",
3987
+ )
3988
+ panel.append(summary_grid)
3989
+
3990
+ if panel:
3991
+ printer.display(printer.panel(panel))
3992
+
3993
+ @staticmethod
3994
+ def _footer_local_warn(
3995
+ server_info_response: Optional[ServerInfoResponse] = None,
3996
+ quiet: Optional[bool] = None,
3997
+ *,
3998
+ settings: "Settings",
3999
+ printer: Union["PrinterTerm", "PrinterJupyter"],
4000
+ ) -> None:
4001
+ if (quiet or settings.quiet) or settings.silent:
4002
+ return
4003
+
4004
+ if settings._offline:
4005
+ return
4006
+
4007
+ if not server_info_response or not server_info_response.local_info:
4008
+ return
4009
+
4010
+ if settings.is_local:
4011
+ local_info = server_info_response.local_info
4012
+ latest_version, out_of_date = local_info.version, local_info.out_of_date
4013
+ if out_of_date:
4014
+ printer.display(
4015
+ f"Upgrade to the {latest_version} version of W&B Server to get the latest features. "
4016
+ f"Learn more: {printer.link(wburls.get('upgrade_server'))}",
4017
+ level="warn",
4018
+ )
4019
+
4020
+ @staticmethod
4021
+ def _footer_internal_messages(
4022
+ internal_messages_response: Optional["InternalMessagesResponse"] = None,
4023
+ quiet: Optional[bool] = None,
4024
+ *,
4025
+ settings: "Settings",
4026
+ printer: Union["PrinterTerm", "PrinterJupyter"],
4027
+ ) -> None:
4028
+ if (quiet or settings.quiet) or settings.silent:
4029
+ return
4030
+
4031
+ if not internal_messages_response:
4032
+ return
4033
+
4034
+ for message in internal_messages_response.messages.warning:
4035
+ printer.display(message, level="warn")
4036
+
4037
+ @staticmethod
4038
+ def _footer_server_messages(
4039
+ server_info_response: Optional[ServerInfoResponse] = None,
4040
+ quiet: Optional[bool] = None,
4041
+ *,
4042
+ settings: "Settings",
4043
+ printer: Union["PrinterTerm", "PrinterJupyter"],
4044
+ ) -> None:
4045
+ if (quiet or settings.quiet) or settings.silent:
4046
+ return
4047
+
4048
+ if settings.disable_hints:
4049
+ return
4050
+
4051
+ if server_info_response and server_info_response.server_messages:
4052
+ for message in server_info_response.server_messages.item:
4053
+ printer.display(
4054
+ message.html_text if printer._html else message.utf_text,
4055
+ default_text=message.plain_text,
4056
+ level=message.level,
4057
+ off=message.type.lower() != "footer",
4058
+ )
4059
+
4060
+ @staticmethod
4061
+ def _footer_version_check_info(
4062
+ check_version: Optional["CheckVersionResponse"] = None,
4063
+ quiet: Optional[bool] = None,
4064
+ *,
4065
+ settings: "Settings",
4066
+ printer: Union["PrinterTerm", "PrinterJupyter"],
4067
+ ) -> None:
4068
+ if not check_version:
4069
+ return
4070
+
4071
+ if settings._offline:
4072
+ return
4073
+
4074
+ if (quiet or settings.quiet) or settings.silent:
4075
+ return
4076
+
4077
+ if check_version.delete_message:
4078
+ printer.display(check_version.delete_message, level="error")
4079
+ elif check_version.yank_message:
4080
+ printer.display(check_version.yank_message, level="warn")
4081
+
4082
+ # only display upgrade message if packages are bad
4083
+ package_problem = check_version.delete_message or check_version.yank_message
4084
+ if package_problem and check_version.upgrade_message:
4085
+ printer.display(check_version.upgrade_message)
4086
+
4087
+ @staticmethod
4088
+ def _footer_reporter_warn_err(
4089
+ reporter: Optional[Reporter] = None,
4090
+ quiet: Optional[bool] = None,
4091
+ *,
4092
+ settings: "Settings",
4093
+ printer: Union["PrinterTerm", "PrinterJupyter"],
4094
+ ) -> None:
4095
+ if (quiet or settings.quiet) or settings.silent:
4096
+ return
4097
+
4098
+ if not reporter:
4099
+ return
4100
+
4101
+ warning_lines = reporter.warning_lines
4102
+ if warning_lines:
4103
+ warnings = ["Warnings:"] + [f"{line}" for line in warning_lines]
4104
+ if len(warning_lines) < reporter.warning_count:
4105
+ warnings.append("More warnings...")
4106
+ printer.display(warnings)
4107
+
4108
+ error_lines = reporter.error_lines
4109
+ if error_lines:
4110
+ errors = ["Errors:"] + [f"{line}" for line in error_lines]
4111
+ if len(error_lines) < reporter.error_count:
4112
+ errors.append("More errors...")
4113
+ printer.display(errors)
4114
+
4115
+
4116
+ # We define this outside of the run context to support restoring before init
4117
+ def restore(
4118
+ name: str,
4119
+ run_path: Optional[str] = None,
4120
+ replace: bool = False,
4121
+ root: Optional[str] = None,
4122
+ ) -> Union[None, TextIO]:
4123
+ """Download the specified file from cloud storage.
4124
+
4125
+ File is placed into the current directory or run directory.
4126
+ By default, will only download the file if it doesn't already exist.
4127
+
4128
+ Arguments:
4129
+ name: the name of the file
4130
+ run_path: optional path to a run to pull files from, i.e. `username/project_name/run_id`
4131
+ if wandb.init has not been called, this is required.
4132
+ replace: whether to download the file even if it already exists locally
4133
+ root: the directory to download the file to. Defaults to the current
4134
+ directory or the run directory if wandb.init was called.
4135
+
4136
+ Returns:
4137
+ None if it can't find the file, otherwise a file object open for reading
4138
+
4139
+ Raises:
4140
+ wandb.CommError: if we can't connect to the wandb backend
4141
+ ValueError: if the file is not found or can't find run_path
4142
+ """
4143
+ is_disabled = wandb.run is not None and wandb.run.disabled
4144
+ run = None if is_disabled else wandb.run
4145
+ if run_path is None:
4146
+ if run is not None:
4147
+ run_path = run.path
4148
+ else:
4149
+ raise ValueError(
4150
+ "run_path required when calling wandb.restore before wandb.init"
4151
+ )
4152
+ if root is None:
4153
+ if run is not None:
4154
+ root = run.dir
4155
+ api = public.Api()
4156
+ api_run = api.run(run_path)
4157
+ if root is None:
4158
+ root = os.getcwd()
4159
+ path = os.path.join(root, name)
4160
+ if os.path.exists(path) and replace is False:
4161
+ return open(path)
4162
+ if is_disabled:
4163
+ return None
4164
+ files = api_run.files([name])
4165
+ if len(files) == 0:
4166
+ return None
4167
+ # if the file does not exist, the file has an md5 of 0
4168
+ if files[0].md5 == "0":
4169
+ raise ValueError(f"File {name} not found in {run_path or root}.")
4170
+ return files[0].download(root=root, replace=True)
4171
+
4172
+
4173
+ # propagate our doc string to the runs restore method
4174
+ try:
4175
+ Run.restore.__doc__ = restore.__doc__
4176
+ except AttributeError:
4177
+ pass
4178
+
4179
+
4180
+ def finish(exit_code: Optional[int] = None, quiet: Optional[bool] = None) -> None:
4181
+ """Mark a run as finished, and finish uploading all data.
4182
+
4183
+ This is used when creating multiple runs in the same process.
4184
+ We automatically call this method when your script exits.
4185
+
4186
+ Arguments:
4187
+ exit_code: Set to something other than 0 to mark a run as failed
4188
+ quiet: Set to true to minimize log output
4189
+ """
4190
+ if wandb.run:
4191
+ wandb.run.finish(exit_code=exit_code, quiet=quiet)