wandb 0.18.0__py3-none-macosx_10_13_x86_64.whl

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