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