wandb 0.17.0__py3-none-win_amd64.whl

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