wandb 0.18.1__py3-none-macosx_11_0_x86_64.whl

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