wandb 0.18.2__py3-none-musllinux_1_2_x86_64.whl

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