wandb 0.17.0rc1__py3-none-macosx_11_0_arm64.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (842) hide show
  1. package_readme.md +95 -0
  2. wandb/__init__.py +253 -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 +386 -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 +228 -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 +1045 -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 +634 -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 +803 -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/apple_gpu_stats +0 -0
  60. wandb/bin/wandb-core +0 -0
  61. wandb/catboost/__init__.py +9 -0
  62. wandb/cli/__init__.py +0 -0
  63. wandb/cli/cli.py +2890 -0
  64. wandb/data_types.py +2068 -0
  65. wandb/docker/__init__.py +342 -0
  66. wandb/docker/auth.py +436 -0
  67. wandb/docker/wandb-entrypoint.sh +33 -0
  68. wandb/docker/www_authenticate.py +94 -0
  69. wandb/env.py +496 -0
  70. wandb/errors/__init__.py +46 -0
  71. wandb/errors/term.py +95 -0
  72. wandb/errors/util.py +57 -0
  73. wandb/fastai/__init__.py +9 -0
  74. wandb/filesync/__init__.py +0 -0
  75. wandb/filesync/dir_watcher.py +403 -0
  76. wandb/filesync/stats.py +100 -0
  77. wandb/filesync/step_checksum.py +145 -0
  78. wandb/filesync/step_prepare.py +199 -0
  79. wandb/filesync/step_upload.py +392 -0
  80. wandb/filesync/upload_job.py +218 -0
  81. wandb/integration/__init__.py +0 -0
  82. wandb/integration/catboost/__init__.py +5 -0
  83. wandb/integration/catboost/catboost.py +178 -0
  84. wandb/integration/cohere/__init__.py +3 -0
  85. wandb/integration/cohere/cohere.py +21 -0
  86. wandb/integration/cohere/resolver.py +347 -0
  87. wandb/integration/diffusers/__init__.py +3 -0
  88. wandb/integration/diffusers/autologger.py +76 -0
  89. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  90. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  91. wandb/integration/diffusers/resolvers/multimodal.py +882 -0
  92. wandb/integration/diffusers/resolvers/utils.py +102 -0
  93. wandb/integration/fastai/__init__.py +249 -0
  94. wandb/integration/gym/__init__.py +85 -0
  95. wandb/integration/huggingface/__init__.py +3 -0
  96. wandb/integration/huggingface/huggingface.py +18 -0
  97. wandb/integration/huggingface/resolver.py +213 -0
  98. wandb/integration/keras/__init__.py +14 -0
  99. wandb/integration/keras/callbacks/__init__.py +5 -0
  100. wandb/integration/keras/callbacks/metrics_logger.py +130 -0
  101. wandb/integration/keras/callbacks/model_checkpoint.py +200 -0
  102. wandb/integration/keras/callbacks/tables_builder.py +226 -0
  103. wandb/integration/keras/keras.py +1080 -0
  104. wandb/integration/kfp/__init__.py +6 -0
  105. wandb/integration/kfp/helpers.py +28 -0
  106. wandb/integration/kfp/kfp_patch.py +324 -0
  107. wandb/integration/kfp/wandb_logging.py +182 -0
  108. wandb/integration/langchain/__init__.py +3 -0
  109. wandb/integration/langchain/wandb_tracer.py +48 -0
  110. wandb/integration/lightgbm/__init__.py +239 -0
  111. wandb/integration/lightning/__init__.py +0 -0
  112. wandb/integration/lightning/fabric/__init__.py +3 -0
  113. wandb/integration/lightning/fabric/logger.py +762 -0
  114. wandb/integration/magic.py +556 -0
  115. wandb/integration/metaflow/__init__.py +3 -0
  116. wandb/integration/metaflow/metaflow.py +383 -0
  117. wandb/integration/openai/__init__.py +3 -0
  118. wandb/integration/openai/fine_tuning.py +454 -0
  119. wandb/integration/openai/openai.py +22 -0
  120. wandb/integration/openai/resolver.py +240 -0
  121. wandb/integration/prodigy/__init__.py +3 -0
  122. wandb/integration/prodigy/prodigy.py +299 -0
  123. wandb/integration/sacred/__init__.py +117 -0
  124. wandb/integration/sagemaker/__init__.py +12 -0
  125. wandb/integration/sagemaker/auth.py +28 -0
  126. wandb/integration/sagemaker/config.py +49 -0
  127. wandb/integration/sagemaker/files.py +3 -0
  128. wandb/integration/sagemaker/resources.py +34 -0
  129. wandb/integration/sb3/__init__.py +3 -0
  130. wandb/integration/sb3/sb3.py +153 -0
  131. wandb/integration/tensorboard/__init__.py +10 -0
  132. wandb/integration/tensorboard/log.py +358 -0
  133. wandb/integration/tensorboard/monkeypatch.py +185 -0
  134. wandb/integration/tensorflow/__init__.py +5 -0
  135. wandb/integration/tensorflow/estimator_hook.py +54 -0
  136. wandb/integration/torch/__init__.py +0 -0
  137. wandb/integration/ultralytics/__init__.py +11 -0
  138. wandb/integration/ultralytics/bbox_utils.py +208 -0
  139. wandb/integration/ultralytics/callback.py +524 -0
  140. wandb/integration/ultralytics/classification_utils.py +83 -0
  141. wandb/integration/ultralytics/mask_utils.py +202 -0
  142. wandb/integration/ultralytics/pose_utils.py +104 -0
  143. wandb/integration/xgboost/__init__.py +11 -0
  144. wandb/integration/xgboost/xgboost.py +189 -0
  145. wandb/integration/yolov8/__init__.py +0 -0
  146. wandb/integration/yolov8/yolov8.py +284 -0
  147. wandb/jupyter.py +501 -0
  148. wandb/keras/__init__.py +19 -0
  149. wandb/lightgbm/__init__.py +9 -0
  150. wandb/magic.py +3 -0
  151. wandb/mpmain/__init__.py +0 -0
  152. wandb/mpmain/__main__.py +1 -0
  153. wandb/old/__init__.py +0 -0
  154. wandb/old/core.py +131 -0
  155. wandb/old/settings.py +173 -0
  156. wandb/old/summary.py +435 -0
  157. wandb/plot/__init__.py +19 -0
  158. wandb/plot/bar.py +42 -0
  159. wandb/plot/confusion_matrix.py +99 -0
  160. wandb/plot/histogram.py +36 -0
  161. wandb/plot/line.py +40 -0
  162. wandb/plot/line_series.py +88 -0
  163. wandb/plot/pr_curve.py +135 -0
  164. wandb/plot/roc_curve.py +117 -0
  165. wandb/plot/scatter.py +32 -0
  166. wandb/plots/__init__.py +6 -0
  167. wandb/plots/explain_text.py +36 -0
  168. wandb/plots/heatmap.py +81 -0
  169. wandb/plots/named_entity.py +43 -0
  170. wandb/plots/part_of_speech.py +50 -0
  171. wandb/plots/plot_definitions.py +768 -0
  172. wandb/plots/precision_recall.py +121 -0
  173. wandb/plots/roc.py +103 -0
  174. wandb/plots/utils.py +195 -0
  175. wandb/proto/__init__.py +0 -0
  176. wandb/proto/v3/__init__.py +0 -0
  177. wandb/proto/v3/wandb_base_pb2.py +54 -0
  178. wandb/proto/v3/wandb_internal_pb2.py +1586 -0
  179. wandb/proto/v3/wandb_server_pb2.py +207 -0
  180. wandb/proto/v3/wandb_settings_pb2.py +111 -0
  181. wandb/proto/v3/wandb_telemetry_pb2.py +105 -0
  182. wandb/proto/v4/__init__.py +0 -0
  183. wandb/proto/v4/wandb_base_pb2.py +29 -0
  184. wandb/proto/v4/wandb_internal_pb2.py +354 -0
  185. wandb/proto/v4/wandb_server_pb2.py +62 -0
  186. wandb/proto/v4/wandb_settings_pb2.py +44 -0
  187. wandb/proto/v4/wandb_telemetry_pb2.py +40 -0
  188. wandb/proto/wandb_base_pb2.py +8 -0
  189. wandb/proto/wandb_deprecated.py +37 -0
  190. wandb/proto/wandb_internal_codegen.py +83 -0
  191. wandb/proto/wandb_internal_pb2.py +8 -0
  192. wandb/proto/wandb_server_pb2.py +8 -0
  193. wandb/proto/wandb_settings_pb2.py +8 -0
  194. wandb/proto/wandb_telemetry_pb2.py +8 -0
  195. wandb/py.typed +0 -0
  196. wandb/sacred/__init__.py +3 -0
  197. wandb/sdk/__init__.py +37 -0
  198. wandb/sdk/artifacts/__init__.py +0 -0
  199. wandb/sdk/artifacts/artifact.py +2317 -0
  200. wandb/sdk/artifacts/artifact_download_logger.py +43 -0
  201. wandb/sdk/artifacts/artifact_file_cache.py +229 -0
  202. wandb/sdk/artifacts/artifact_instance_cache.py +15 -0
  203. wandb/sdk/artifacts/artifact_manifest.py +72 -0
  204. wandb/sdk/artifacts/artifact_manifest_entry.py +205 -0
  205. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  206. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +90 -0
  207. wandb/sdk/artifacts/artifact_saver.py +270 -0
  208. wandb/sdk/artifacts/artifact_state.py +11 -0
  209. wandb/sdk/artifacts/artifact_ttl.py +7 -0
  210. wandb/sdk/artifacts/exceptions.py +56 -0
  211. wandb/sdk/artifacts/staging.py +25 -0
  212. wandb/sdk/artifacts/storage_handler.py +60 -0
  213. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  214. wandb/sdk/artifacts/storage_handlers/azure_handler.py +194 -0
  215. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +195 -0
  216. wandb/sdk/artifacts/storage_handlers/http_handler.py +113 -0
  217. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +135 -0
  218. wandb/sdk/artifacts/storage_handlers/multi_handler.py +54 -0
  219. wandb/sdk/artifacts/storage_handlers/s3_handler.py +300 -0
  220. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +68 -0
  221. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +133 -0
  222. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +72 -0
  223. wandb/sdk/artifacts/storage_layout.py +6 -0
  224. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  225. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  226. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +411 -0
  227. wandb/sdk/artifacts/storage_policy.py +83 -0
  228. wandb/sdk/backend/__init__.py +0 -0
  229. wandb/sdk/backend/backend.py +240 -0
  230. wandb/sdk/data_types/__init__.py +0 -0
  231. wandb/sdk/data_types/_dtypes.py +911 -0
  232. wandb/sdk/data_types/_private.py +10 -0
  233. wandb/sdk/data_types/base_types/__init__.py +0 -0
  234. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  235. wandb/sdk/data_types/base_types/media.py +313 -0
  236. wandb/sdk/data_types/base_types/wb_value.py +274 -0
  237. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  238. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +293 -0
  239. wandb/sdk/data_types/helper_types/classes.py +159 -0
  240. wandb/sdk/data_types/helper_types/image_mask.py +233 -0
  241. wandb/sdk/data_types/histogram.py +96 -0
  242. wandb/sdk/data_types/html.py +115 -0
  243. wandb/sdk/data_types/image.py +687 -0
  244. wandb/sdk/data_types/molecule.py +241 -0
  245. wandb/sdk/data_types/object_3d.py +363 -0
  246. wandb/sdk/data_types/plotly.py +82 -0
  247. wandb/sdk/data_types/saved_model.py +444 -0
  248. wandb/sdk/data_types/trace_tree.py +438 -0
  249. wandb/sdk/data_types/utils.py +180 -0
  250. wandb/sdk/data_types/video.py +245 -0
  251. wandb/sdk/integration_utils/__init__.py +0 -0
  252. wandb/sdk/integration_utils/auto_logging.py +239 -0
  253. wandb/sdk/integration_utils/data_logging.py +475 -0
  254. wandb/sdk/interface/__init__.py +0 -0
  255. wandb/sdk/interface/constants.py +4 -0
  256. wandb/sdk/interface/interface.py +949 -0
  257. wandb/sdk/interface/interface_queue.py +59 -0
  258. wandb/sdk/interface/interface_relay.py +53 -0
  259. wandb/sdk/interface/interface_shared.py +550 -0
  260. wandb/sdk/interface/interface_sock.py +61 -0
  261. wandb/sdk/interface/message_future.py +27 -0
  262. wandb/sdk/interface/message_future_poll.py +50 -0
  263. wandb/sdk/interface/router.py +118 -0
  264. wandb/sdk/interface/router_queue.py +44 -0
  265. wandb/sdk/interface/router_relay.py +39 -0
  266. wandb/sdk/interface/router_sock.py +36 -0
  267. wandb/sdk/interface/summary_record.py +67 -0
  268. wandb/sdk/internal/__init__.py +0 -0
  269. wandb/sdk/internal/context.py +89 -0
  270. wandb/sdk/internal/datastore.py +297 -0
  271. wandb/sdk/internal/file_pusher.py +184 -0
  272. wandb/sdk/internal/file_stream.py +708 -0
  273. wandb/sdk/internal/flow_control.py +263 -0
  274. wandb/sdk/internal/handler.py +909 -0
  275. wandb/sdk/internal/internal.py +417 -0
  276. wandb/sdk/internal/internal_api.py +4202 -0
  277. wandb/sdk/internal/internal_util.py +100 -0
  278. wandb/sdk/internal/job_builder.py +554 -0
  279. wandb/sdk/internal/profiler.py +78 -0
  280. wandb/sdk/internal/progress.py +111 -0
  281. wandb/sdk/internal/run.py +25 -0
  282. wandb/sdk/internal/sample.py +70 -0
  283. wandb/sdk/internal/sender.py +1642 -0
  284. wandb/sdk/internal/sender_config.py +197 -0
  285. wandb/sdk/internal/settings_static.py +83 -0
  286. wandb/sdk/internal/system/__init__.py +0 -0
  287. wandb/sdk/internal/system/assets/__init__.py +27 -0
  288. wandb/sdk/internal/system/assets/aggregators.py +37 -0
  289. wandb/sdk/internal/system/assets/asset_registry.py +20 -0
  290. wandb/sdk/internal/system/assets/cpu.py +163 -0
  291. wandb/sdk/internal/system/assets/disk.py +210 -0
  292. wandb/sdk/internal/system/assets/gpu.py +414 -0
  293. wandb/sdk/internal/system/assets/gpu_amd.py +230 -0
  294. wandb/sdk/internal/system/assets/gpu_apple.py +177 -0
  295. wandb/sdk/internal/system/assets/interfaces.py +207 -0
  296. wandb/sdk/internal/system/assets/ipu.py +177 -0
  297. wandb/sdk/internal/system/assets/memory.py +166 -0
  298. wandb/sdk/internal/system/assets/network.py +125 -0
  299. wandb/sdk/internal/system/assets/open_metrics.py +299 -0
  300. wandb/sdk/internal/system/assets/tpu.py +154 -0
  301. wandb/sdk/internal/system/assets/trainium.py +398 -0
  302. wandb/sdk/internal/system/env_probe_helpers.py +13 -0
  303. wandb/sdk/internal/system/system_info.py +247 -0
  304. wandb/sdk/internal/system/system_monitor.py +229 -0
  305. wandb/sdk/internal/tb_watcher.py +518 -0
  306. wandb/sdk/internal/thread_local_settings.py +18 -0
  307. wandb/sdk/internal/update.py +113 -0
  308. wandb/sdk/internal/writer.py +206 -0
  309. wandb/sdk/launch/__init__.py +6 -0
  310. wandb/sdk/launch/_launch.py +348 -0
  311. wandb/sdk/launch/_launch_add.py +257 -0
  312. wandb/sdk/launch/_project_spec.py +578 -0
  313. wandb/sdk/launch/agent/__init__.py +5 -0
  314. wandb/sdk/launch/agent/agent.py +878 -0
  315. wandb/sdk/launch/agent/config.py +299 -0
  316. wandb/sdk/launch/agent/job_status_tracker.py +53 -0
  317. wandb/sdk/launch/agent/run_queue_item_file_saver.py +47 -0
  318. wandb/sdk/launch/builder/__init__.py +0 -0
  319. wandb/sdk/launch/builder/abstract.py +89 -0
  320. wandb/sdk/launch/builder/build.py +706 -0
  321. wandb/sdk/launch/builder/docker_builder.py +193 -0
  322. wandb/sdk/launch/builder/kaniko_builder.py +579 -0
  323. wandb/sdk/launch/builder/noop.py +58 -0
  324. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +187 -0
  325. wandb/sdk/launch/create_job.py +520 -0
  326. wandb/sdk/launch/environment/abstract.py +29 -0
  327. wandb/sdk/launch/environment/aws_environment.py +297 -0
  328. wandb/sdk/launch/environment/azure_environment.py +105 -0
  329. wandb/sdk/launch/environment/gcp_environment.py +335 -0
  330. wandb/sdk/launch/environment/local_environment.py +66 -0
  331. wandb/sdk/launch/errors.py +19 -0
  332. wandb/sdk/launch/git_reference.py +109 -0
  333. wandb/sdk/launch/loader.py +249 -0
  334. wandb/sdk/launch/registry/abstract.py +48 -0
  335. wandb/sdk/launch/registry/anon.py +29 -0
  336. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  337. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  338. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  339. wandb/sdk/launch/registry/local_registry.py +67 -0
  340. wandb/sdk/launch/runner/__init__.py +0 -0
  341. wandb/sdk/launch/runner/abstract.py +195 -0
  342. wandb/sdk/launch/runner/kubernetes_monitor.py +441 -0
  343. wandb/sdk/launch/runner/kubernetes_runner.py +893 -0
  344. wandb/sdk/launch/runner/local_container.py +299 -0
  345. wandb/sdk/launch/runner/local_process.py +99 -0
  346. wandb/sdk/launch/runner/sagemaker_runner.py +422 -0
  347. wandb/sdk/launch/runner/vertex_runner.py +229 -0
  348. wandb/sdk/launch/sweeps/__init__.py +39 -0
  349. wandb/sdk/launch/sweeps/scheduler.py +738 -0
  350. wandb/sdk/launch/sweeps/scheduler_sweep.py +91 -0
  351. wandb/sdk/launch/sweeps/utils.py +316 -0
  352. wandb/sdk/launch/utils.py +866 -0
  353. wandb/sdk/launch/wandb_reference.py +138 -0
  354. wandb/sdk/lib/__init__.py +5 -0
  355. wandb/sdk/lib/_settings_toposort_generate.py +159 -0
  356. wandb/sdk/lib/_settings_toposort_generated.py +244 -0
  357. wandb/sdk/lib/_wburls_generate.py +25 -0
  358. wandb/sdk/lib/_wburls_generated.py +22 -0
  359. wandb/sdk/lib/apikey.py +258 -0
  360. wandb/sdk/lib/capped_dict.py +26 -0
  361. wandb/sdk/lib/config_util.py +101 -0
  362. wandb/sdk/lib/console.py +39 -0
  363. wandb/sdk/lib/deprecate.py +42 -0
  364. wandb/sdk/lib/disabled.py +190 -0
  365. wandb/sdk/lib/exit_hooks.py +54 -0
  366. wandb/sdk/lib/file_stream_utils.py +118 -0
  367. wandb/sdk/lib/filenames.py +64 -0
  368. wandb/sdk/lib/filesystem.py +372 -0
  369. wandb/sdk/lib/fsm.py +174 -0
  370. wandb/sdk/lib/gitlib.py +239 -0
  371. wandb/sdk/lib/gql_request.py +65 -0
  372. wandb/sdk/lib/handler_util.py +21 -0
  373. wandb/sdk/lib/hashutil.py +62 -0
  374. wandb/sdk/lib/import_hooks.py +275 -0
  375. wandb/sdk/lib/ipython.py +146 -0
  376. wandb/sdk/lib/json_util.py +80 -0
  377. wandb/sdk/lib/lazyloader.py +63 -0
  378. wandb/sdk/lib/mailbox.py +460 -0
  379. wandb/sdk/lib/module.py +69 -0
  380. wandb/sdk/lib/paths.py +106 -0
  381. wandb/sdk/lib/preinit.py +42 -0
  382. wandb/sdk/lib/printer.py +313 -0
  383. wandb/sdk/lib/proto_util.py +69 -0
  384. wandb/sdk/lib/redirect.py +840 -0
  385. wandb/sdk/lib/reporting.py +99 -0
  386. wandb/sdk/lib/retry.py +289 -0
  387. wandb/sdk/lib/run_moment.py +78 -0
  388. wandb/sdk/lib/runid.py +12 -0
  389. wandb/sdk/lib/server.py +52 -0
  390. wandb/sdk/lib/sock_client.py +291 -0
  391. wandb/sdk/lib/sparkline.py +45 -0
  392. wandb/sdk/lib/telemetry.py +100 -0
  393. wandb/sdk/lib/timed_input.py +133 -0
  394. wandb/sdk/lib/timer.py +19 -0
  395. wandb/sdk/lib/tracelog.py +255 -0
  396. wandb/sdk/lib/wburls.py +46 -0
  397. wandb/sdk/service/__init__.py +0 -0
  398. wandb/sdk/service/_startup_debug.py +22 -0
  399. wandb/sdk/service/port_file.py +53 -0
  400. wandb/sdk/service/server.py +119 -0
  401. wandb/sdk/service/server_sock.py +276 -0
  402. wandb/sdk/service/service.py +266 -0
  403. wandb/sdk/service/service_base.py +50 -0
  404. wandb/sdk/service/service_sock.py +70 -0
  405. wandb/sdk/service/streams.py +426 -0
  406. wandb/sdk/verify/__init__.py +0 -0
  407. wandb/sdk/verify/verify.py +501 -0
  408. wandb/sdk/wandb_alerts.py +12 -0
  409. wandb/sdk/wandb_config.py +319 -0
  410. wandb/sdk/wandb_helper.py +54 -0
  411. wandb/sdk/wandb_init.py +1220 -0
  412. wandb/sdk/wandb_login.py +339 -0
  413. wandb/sdk/wandb_manager.py +222 -0
  414. wandb/sdk/wandb_metric.py +110 -0
  415. wandb/sdk/wandb_require.py +92 -0
  416. wandb/sdk/wandb_require_helpers.py +44 -0
  417. wandb/sdk/wandb_run.py +4191 -0
  418. wandb/sdk/wandb_settings.py +1973 -0
  419. wandb/sdk/wandb_setup.py +335 -0
  420. wandb/sdk/wandb_summary.py +150 -0
  421. wandb/sdk/wandb_sweep.py +114 -0
  422. wandb/sdk/wandb_sync.py +75 -0
  423. wandb/sdk/wandb_watch.py +128 -0
  424. wandb/sklearn/__init__.py +37 -0
  425. wandb/sklearn/calculate/__init__.py +32 -0
  426. wandb/sklearn/calculate/calibration_curves.py +125 -0
  427. wandb/sklearn/calculate/class_proportions.py +68 -0
  428. wandb/sklearn/calculate/confusion_matrix.py +92 -0
  429. wandb/sklearn/calculate/decision_boundaries.py +40 -0
  430. wandb/sklearn/calculate/elbow_curve.py +55 -0
  431. wandb/sklearn/calculate/feature_importances.py +67 -0
  432. wandb/sklearn/calculate/learning_curve.py +64 -0
  433. wandb/sklearn/calculate/outlier_candidates.py +69 -0
  434. wandb/sklearn/calculate/residuals.py +86 -0
  435. wandb/sklearn/calculate/silhouette.py +118 -0
  436. wandb/sklearn/calculate/summary_metrics.py +62 -0
  437. wandb/sklearn/plot/__init__.py +35 -0
  438. wandb/sklearn/plot/classifier.py +331 -0
  439. wandb/sklearn/plot/clusterer.py +142 -0
  440. wandb/sklearn/plot/regressor.py +121 -0
  441. wandb/sklearn/plot/shared.py +91 -0
  442. wandb/sklearn/utils.py +183 -0
  443. wandb/sync/__init__.py +3 -0
  444. wandb/sync/sync.py +443 -0
  445. wandb/testing/relay.py +859 -0
  446. wandb/trigger.py +29 -0
  447. wandb/util.py +1925 -0
  448. wandb/vendor/__init__.py +0 -0
  449. wandb/vendor/gql-0.2.0/setup.py +40 -0
  450. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  451. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  452. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  453. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  454. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  455. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  456. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  457. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  458. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  459. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  460. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  461. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  462. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  463. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  464. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  465. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  466. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  467. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  468. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  469. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  470. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  471. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  472. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  473. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  474. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  475. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  476. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  477. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  478. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  479. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  480. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  481. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  482. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  483. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  484. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  485. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  486. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  487. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  488. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  489. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  490. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  491. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  492. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  493. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  494. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  495. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  496. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  497. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  498. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  499. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  500. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  501. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  502. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  503. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  504. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  505. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  506. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  507. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  508. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  509. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  510. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  511. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  512. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  513. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  514. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  515. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  516. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  517. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  518. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  519. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  520. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  521. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  522. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  523. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  524. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  525. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  526. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  527. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  528. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  529. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  530. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  531. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  532. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  533. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  534. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  535. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  549. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  550. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  551. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  552. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  553. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  554. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  555. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  556. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  557. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  558. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  559. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  560. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  561. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  562. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  563. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  564. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  565. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  566. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  567. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  568. wandb/vendor/promise-2.3.0/setup.py +64 -0
  569. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  570. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  571. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  572. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  573. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  574. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  575. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  576. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  577. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  578. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  579. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  580. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  581. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  582. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  583. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  584. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  585. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  586. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  587. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  588. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  589. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  590. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  591. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  592. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  593. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  594. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  595. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  596. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  597. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  598. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  599. wandb/vendor/pygments/__init__.py +90 -0
  600. wandb/vendor/pygments/cmdline.py +568 -0
  601. wandb/vendor/pygments/console.py +74 -0
  602. wandb/vendor/pygments/filter.py +74 -0
  603. wandb/vendor/pygments/filters/__init__.py +350 -0
  604. wandb/vendor/pygments/formatter.py +95 -0
  605. wandb/vendor/pygments/formatters/__init__.py +153 -0
  606. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  607. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  608. wandb/vendor/pygments/formatters/html.py +851 -0
  609. wandb/vendor/pygments/formatters/img.py +600 -0
  610. wandb/vendor/pygments/formatters/irc.py +182 -0
  611. wandb/vendor/pygments/formatters/latex.py +482 -0
  612. wandb/vendor/pygments/formatters/other.py +160 -0
  613. wandb/vendor/pygments/formatters/rtf.py +147 -0
  614. wandb/vendor/pygments/formatters/svg.py +153 -0
  615. wandb/vendor/pygments/formatters/terminal.py +136 -0
  616. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  617. wandb/vendor/pygments/lexer.py +871 -0
  618. wandb/vendor/pygments/lexers/__init__.py +329 -0
  619. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  620. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  621. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  622. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  623. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  624. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  625. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  626. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  627. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  628. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  629. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  630. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  631. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  632. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  633. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  634. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  635. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  636. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  637. wandb/vendor/pygments/lexers/agile.py +24 -0
  638. wandb/vendor/pygments/lexers/algebra.py +221 -0
  639. wandb/vendor/pygments/lexers/ambient.py +76 -0
  640. wandb/vendor/pygments/lexers/ampl.py +87 -0
  641. wandb/vendor/pygments/lexers/apl.py +101 -0
  642. wandb/vendor/pygments/lexers/archetype.py +318 -0
  643. wandb/vendor/pygments/lexers/asm.py +641 -0
  644. wandb/vendor/pygments/lexers/automation.py +374 -0
  645. wandb/vendor/pygments/lexers/basic.py +500 -0
  646. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  647. wandb/vendor/pygments/lexers/business.py +612 -0
  648. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  649. wandb/vendor/pygments/lexers/c_like.py +541 -0
  650. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  651. wandb/vendor/pygments/lexers/chapel.py +102 -0
  652. wandb/vendor/pygments/lexers/clean.py +288 -0
  653. wandb/vendor/pygments/lexers/compiled.py +34 -0
  654. wandb/vendor/pygments/lexers/configs.py +833 -0
  655. wandb/vendor/pygments/lexers/console.py +114 -0
  656. wandb/vendor/pygments/lexers/crystal.py +393 -0
  657. wandb/vendor/pygments/lexers/csound.py +366 -0
  658. wandb/vendor/pygments/lexers/css.py +689 -0
  659. wandb/vendor/pygments/lexers/d.py +251 -0
  660. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  661. wandb/vendor/pygments/lexers/data.py +555 -0
  662. wandb/vendor/pygments/lexers/diff.py +165 -0
  663. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  664. wandb/vendor/pygments/lexers/dsls.py +878 -0
  665. wandb/vendor/pygments/lexers/dylan.py +289 -0
  666. wandb/vendor/pygments/lexers/ecl.py +125 -0
  667. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  668. wandb/vendor/pygments/lexers/elm.py +121 -0
  669. wandb/vendor/pygments/lexers/erlang.py +533 -0
  670. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  671. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  672. wandb/vendor/pygments/lexers/factor.py +344 -0
  673. wandb/vendor/pygments/lexers/fantom.py +250 -0
  674. wandb/vendor/pygments/lexers/felix.py +273 -0
  675. wandb/vendor/pygments/lexers/forth.py +177 -0
  676. wandb/vendor/pygments/lexers/fortran.py +205 -0
  677. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  678. wandb/vendor/pygments/lexers/functional.py +21 -0
  679. wandb/vendor/pygments/lexers/go.py +101 -0
  680. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  681. wandb/vendor/pygments/lexers/graph.py +80 -0
  682. wandb/vendor/pygments/lexers/graphics.py +553 -0
  683. wandb/vendor/pygments/lexers/haskell.py +843 -0
  684. wandb/vendor/pygments/lexers/haxe.py +936 -0
  685. wandb/vendor/pygments/lexers/hdl.py +382 -0
  686. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  687. wandb/vendor/pygments/lexers/html.py +602 -0
  688. wandb/vendor/pygments/lexers/idl.py +270 -0
  689. wandb/vendor/pygments/lexers/igor.py +288 -0
  690. wandb/vendor/pygments/lexers/inferno.py +96 -0
  691. wandb/vendor/pygments/lexers/installers.py +322 -0
  692. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  693. wandb/vendor/pygments/lexers/iolang.py +63 -0
  694. wandb/vendor/pygments/lexers/j.py +146 -0
  695. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  696. wandb/vendor/pygments/lexers/julia.py +333 -0
  697. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  698. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  699. wandb/vendor/pygments/lexers/make.py +202 -0
  700. wandb/vendor/pygments/lexers/markup.py +595 -0
  701. wandb/vendor/pygments/lexers/math.py +21 -0
  702. wandb/vendor/pygments/lexers/matlab.py +663 -0
  703. wandb/vendor/pygments/lexers/ml.py +769 -0
  704. wandb/vendor/pygments/lexers/modeling.py +358 -0
  705. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  706. wandb/vendor/pygments/lexers/monte.py +204 -0
  707. wandb/vendor/pygments/lexers/ncl.py +894 -0
  708. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  709. wandb/vendor/pygments/lexers/nit.py +64 -0
  710. wandb/vendor/pygments/lexers/nix.py +136 -0
  711. wandb/vendor/pygments/lexers/oberon.py +105 -0
  712. wandb/vendor/pygments/lexers/objective.py +504 -0
  713. wandb/vendor/pygments/lexers/ooc.py +85 -0
  714. wandb/vendor/pygments/lexers/other.py +41 -0
  715. wandb/vendor/pygments/lexers/parasail.py +79 -0
  716. wandb/vendor/pygments/lexers/parsers.py +835 -0
  717. wandb/vendor/pygments/lexers/pascal.py +644 -0
  718. wandb/vendor/pygments/lexers/pawn.py +199 -0
  719. wandb/vendor/pygments/lexers/perl.py +620 -0
  720. wandb/vendor/pygments/lexers/php.py +267 -0
  721. wandb/vendor/pygments/lexers/praat.py +294 -0
  722. wandb/vendor/pygments/lexers/prolog.py +306 -0
  723. wandb/vendor/pygments/lexers/python.py +939 -0
  724. wandb/vendor/pygments/lexers/qvt.py +152 -0
  725. wandb/vendor/pygments/lexers/r.py +453 -0
  726. wandb/vendor/pygments/lexers/rdf.py +270 -0
  727. wandb/vendor/pygments/lexers/rebol.py +431 -0
  728. wandb/vendor/pygments/lexers/resource.py +85 -0
  729. wandb/vendor/pygments/lexers/rnc.py +67 -0
  730. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  731. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  732. wandb/vendor/pygments/lexers/ruby.py +519 -0
  733. wandb/vendor/pygments/lexers/rust.py +220 -0
  734. wandb/vendor/pygments/lexers/sas.py +228 -0
  735. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  736. wandb/vendor/pygments/lexers/shell.py +794 -0
  737. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  738. wandb/vendor/pygments/lexers/smv.py +79 -0
  739. wandb/vendor/pygments/lexers/snobol.py +83 -0
  740. wandb/vendor/pygments/lexers/special.py +103 -0
  741. wandb/vendor/pygments/lexers/sql.py +681 -0
  742. wandb/vendor/pygments/lexers/stata.py +108 -0
  743. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  744. wandb/vendor/pygments/lexers/tcl.py +145 -0
  745. wandb/vendor/pygments/lexers/templates.py +2283 -0
  746. wandb/vendor/pygments/lexers/testing.py +207 -0
  747. wandb/vendor/pygments/lexers/text.py +25 -0
  748. wandb/vendor/pygments/lexers/textedit.py +169 -0
  749. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  750. wandb/vendor/pygments/lexers/theorem.py +458 -0
  751. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  752. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  753. wandb/vendor/pygments/lexers/urbi.py +133 -0
  754. wandb/vendor/pygments/lexers/varnish.py +190 -0
  755. wandb/vendor/pygments/lexers/verification.py +111 -0
  756. wandb/vendor/pygments/lexers/web.py +24 -0
  757. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  758. wandb/vendor/pygments/lexers/whiley.py +116 -0
  759. wandb/vendor/pygments/lexers/x10.py +69 -0
  760. wandb/vendor/pygments/modeline.py +44 -0
  761. wandb/vendor/pygments/plugin.py +68 -0
  762. wandb/vendor/pygments/regexopt.py +92 -0
  763. wandb/vendor/pygments/scanner.py +105 -0
  764. wandb/vendor/pygments/sphinxext.py +158 -0
  765. wandb/vendor/pygments/style.py +155 -0
  766. wandb/vendor/pygments/styles/__init__.py +80 -0
  767. wandb/vendor/pygments/styles/abap.py +29 -0
  768. wandb/vendor/pygments/styles/algol.py +63 -0
  769. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  770. wandb/vendor/pygments/styles/arduino.py +98 -0
  771. wandb/vendor/pygments/styles/autumn.py +65 -0
  772. wandb/vendor/pygments/styles/borland.py +51 -0
  773. wandb/vendor/pygments/styles/bw.py +49 -0
  774. wandb/vendor/pygments/styles/colorful.py +81 -0
  775. wandb/vendor/pygments/styles/default.py +73 -0
  776. wandb/vendor/pygments/styles/emacs.py +72 -0
  777. wandb/vendor/pygments/styles/friendly.py +72 -0
  778. wandb/vendor/pygments/styles/fruity.py +42 -0
  779. wandb/vendor/pygments/styles/igor.py +29 -0
  780. wandb/vendor/pygments/styles/lovelace.py +97 -0
  781. wandb/vendor/pygments/styles/manni.py +75 -0
  782. wandb/vendor/pygments/styles/monokai.py +106 -0
  783. wandb/vendor/pygments/styles/murphy.py +80 -0
  784. wandb/vendor/pygments/styles/native.py +65 -0
  785. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  786. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  787. wandb/vendor/pygments/styles/pastie.py +75 -0
  788. wandb/vendor/pygments/styles/perldoc.py +69 -0
  789. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  790. wandb/vendor/pygments/styles/rrt.py +33 -0
  791. wandb/vendor/pygments/styles/sas.py +44 -0
  792. wandb/vendor/pygments/styles/stata.py +40 -0
  793. wandb/vendor/pygments/styles/tango.py +141 -0
  794. wandb/vendor/pygments/styles/trac.py +63 -0
  795. wandb/vendor/pygments/styles/vim.py +63 -0
  796. wandb/vendor/pygments/styles/vs.py +38 -0
  797. wandb/vendor/pygments/styles/xcode.py +51 -0
  798. wandb/vendor/pygments/token.py +213 -0
  799. wandb/vendor/pygments/unistring.py +217 -0
  800. wandb/vendor/pygments/util.py +388 -0
  801. wandb/vendor/pynvml/__init__.py +0 -0
  802. wandb/vendor/pynvml/pynvml.py +4779 -0
  803. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  804. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  805. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  806. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  807. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  808. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  809. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  810. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  811. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  812. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  813. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  814. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  815. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  816. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  817. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  818. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  819. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  820. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  821. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  822. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  823. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  824. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  825. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  826. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  827. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  828. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  829. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  830. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  831. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  832. wandb/viz.py +123 -0
  833. wandb/wandb_agent.py +586 -0
  834. wandb/wandb_controller.py +720 -0
  835. wandb/wandb_run.py +9 -0
  836. wandb/wandb_torch.py +550 -0
  837. wandb/xgboost/__init__.py +9 -0
  838. wandb-0.17.0rc1.dist-info/METADATA +219 -0
  839. wandb-0.17.0rc1.dist-info/RECORD +842 -0
  840. wandb-0.17.0rc1.dist-info/WHEEL +4 -0
  841. wandb-0.17.0rc1.dist-info/entry_points.txt +3 -0
  842. wandb-0.17.0rc1.dist-info/licenses/LICENSE +21 -0
wandb/util.py ADDED
@@ -0,0 +1,1925 @@
1
+ import colorsys
2
+ import contextlib
3
+ import dataclasses
4
+ import functools
5
+ import gzip
6
+ import importlib
7
+ import importlib.util
8
+ import itertools
9
+ import json
10
+ import logging
11
+ import math
12
+ import numbers
13
+ import os
14
+ import pathlib
15
+ import platform
16
+ import queue
17
+ import random
18
+ import re
19
+ import secrets
20
+ import shlex
21
+ import socket
22
+ import string
23
+ import sys
24
+ import tarfile
25
+ import tempfile
26
+ import threading
27
+ import time
28
+ import types
29
+ import urllib
30
+ from dataclasses import asdict, is_dataclass
31
+ from datetime import date, datetime, timedelta
32
+ from importlib import import_module
33
+ from sys import getsizeof
34
+ from types import ModuleType
35
+ from typing import (
36
+ IO,
37
+ TYPE_CHECKING,
38
+ Any,
39
+ Callable,
40
+ Dict,
41
+ Generator,
42
+ Iterable,
43
+ List,
44
+ Mapping,
45
+ Optional,
46
+ Sequence,
47
+ Set,
48
+ TextIO,
49
+ Tuple,
50
+ TypeVar,
51
+ Union,
52
+ )
53
+
54
+ import requests
55
+ import yaml
56
+
57
+ import wandb
58
+ import wandb.env
59
+ from wandb.errors import (
60
+ AuthenticationError,
61
+ CommError,
62
+ UsageError,
63
+ WandbCoreNotAvailableError,
64
+ term,
65
+ )
66
+ from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
67
+ from wandb.sdk.lib import filesystem, runid
68
+ from wandb.sdk.lib.json_util import dump, dumps
69
+ from wandb.sdk.lib.paths import FilePathStr, StrPath
70
+
71
+ if TYPE_CHECKING:
72
+ import packaging.version # type: ignore[import-not-found]
73
+
74
+ import wandb.sdk.internal.settings_static
75
+ import wandb.sdk.wandb_settings
76
+ from wandb.sdk.artifacts.artifact import Artifact
77
+
78
+ CheckRetryFnType = Callable[[Exception], Union[bool, timedelta]]
79
+ T = TypeVar("T")
80
+
81
+
82
+ logger = logging.getLogger(__name__)
83
+ _not_importable = set()
84
+
85
+ MAX_LINE_BYTES = (10 << 20) - (100 << 10) # imposed by back end
86
+ IS_GIT = os.path.exists(os.path.join(os.path.dirname(__file__), "..", ".git"))
87
+ RE_WINFNAMES = re.compile(r'[<>:"\\?*]')
88
+
89
+ # From https://docs.docker.com/engine/reference/commandline/tag/
90
+ # "Name components may contain lowercase letters, digits and separators.
91
+ # A separator is defined as a period, one or two underscores, or one or more dashes.
92
+ # A name component may not start or end with a separator."
93
+ DOCKER_IMAGE_NAME_SEPARATOR = "(?:__|[._]|[-]+)"
94
+ RE_DOCKER_IMAGE_NAME_SEPARATOR_START = re.compile("^" + DOCKER_IMAGE_NAME_SEPARATOR)
95
+ RE_DOCKER_IMAGE_NAME_SEPARATOR_END = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "$")
96
+ RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "{2,}")
97
+ RE_DOCKER_IMAGE_NAME_CHARS = re.compile(r"[^a-z0-9._\-]")
98
+
99
+ # these match the environments for gorilla
100
+ if IS_GIT:
101
+ SENTRY_ENV = "development"
102
+ else:
103
+ SENTRY_ENV = "production"
104
+
105
+
106
+ PLATFORM_WINDOWS = "windows"
107
+ PLATFORM_LINUX = "linux"
108
+ PLATFORM_BSD = "bsd"
109
+ PLATFORM_DARWIN = "darwin"
110
+ PLATFORM_UNKNOWN = "unknown"
111
+
112
+ LAUNCH_JOB_ARTIFACT_SLOT_NAME = "_wandb_job"
113
+
114
+
115
+ def get_platform_name() -> str:
116
+ if sys.platform.startswith("win"):
117
+ return PLATFORM_WINDOWS
118
+ elif sys.platform.startswith("darwin"):
119
+ return PLATFORM_DARWIN
120
+ elif sys.platform.startswith("linux"):
121
+ return PLATFORM_LINUX
122
+ elif sys.platform.startswith(
123
+ (
124
+ "dragonfly",
125
+ "freebsd",
126
+ "netbsd",
127
+ "openbsd",
128
+ )
129
+ ):
130
+ return PLATFORM_BSD
131
+ else:
132
+ return PLATFORM_UNKNOWN
133
+
134
+
135
+ POW_10_BYTES = [
136
+ ("B", 10**0),
137
+ ("KB", 10**3),
138
+ ("MB", 10**6),
139
+ ("GB", 10**9),
140
+ ("TB", 10**12),
141
+ ("PB", 10**15),
142
+ ("EB", 10**18),
143
+ ]
144
+
145
+ POW_2_BYTES = [
146
+ ("B", 2**0),
147
+ ("KiB", 2**10),
148
+ ("MiB", 2**20),
149
+ ("GiB", 2**30),
150
+ ("TiB", 2**40),
151
+ ("PiB", 2**50),
152
+ ("EiB", 2**60),
153
+ ]
154
+
155
+
156
+ def vendor_setup() -> Callable:
157
+ """Create a function that restores user paths after vendor imports.
158
+
159
+ This enables us to use the vendor directory for packages we don't depend on. Call
160
+ the returned function after imports are complete. If you don't you may modify the
161
+ user's path which is never good.
162
+
163
+ Usage:
164
+
165
+ ```python
166
+ reset_path = vendor_setup()
167
+ # do any vendor imports...
168
+ reset_path()
169
+ ```
170
+ """
171
+ original_path = [directory for directory in sys.path]
172
+
173
+ def reset_import_path() -> None:
174
+ sys.path = original_path
175
+
176
+ parent_dir = os.path.abspath(os.path.dirname(__file__))
177
+ vendor_dir = os.path.join(parent_dir, "vendor")
178
+ vendor_packages = (
179
+ "gql-0.2.0",
180
+ "graphql-core-1.1",
181
+ "watchdog_0_9_0",
182
+ "promise-2.3.0",
183
+ )
184
+ package_dirs = [os.path.join(vendor_dir, p) for p in vendor_packages]
185
+ for p in [vendor_dir] + package_dirs:
186
+ if p not in sys.path:
187
+ sys.path.insert(1, p)
188
+
189
+ return reset_import_path
190
+
191
+
192
+ def vendor_import(name: str) -> Any:
193
+ reset_path = vendor_setup()
194
+ module = import_module(name)
195
+ reset_path()
196
+ return module
197
+
198
+
199
+ class LazyModuleState:
200
+ def __init__(self, module: types.ModuleType) -> None:
201
+ self.module = module
202
+ self.load_started = False
203
+ self.lock = threading.RLock()
204
+
205
+ def load(self) -> None:
206
+ with self.lock:
207
+ if self.load_started:
208
+ return
209
+ self.load_started = True
210
+ assert self.module.__spec__ is not None
211
+ assert self.module.__spec__.loader is not None
212
+ self.module.__spec__.loader.exec_module(self.module)
213
+ self.module.__class__ = types.ModuleType
214
+
215
+
216
+ class LazyModule(types.ModuleType):
217
+ def __getattribute__(self, name: str) -> Any:
218
+ state = object.__getattribute__(self, "__lazy_module_state__")
219
+ state.load()
220
+ return object.__getattribute__(self, name)
221
+
222
+ def __setattr__(self, name: str, value: Any) -> None:
223
+ state = object.__getattribute__(self, "__lazy_module_state__")
224
+ state.load()
225
+ object.__setattr__(self, name, value)
226
+
227
+ def __delattr__(self, name: str) -> None:
228
+ state = object.__getattribute__(self, "__lazy_module_state__")
229
+ state.load()
230
+ object.__delattr__(self, name)
231
+
232
+
233
+ def import_module_lazy(name: str) -> types.ModuleType:
234
+ """Import a module lazily, only when it is used.
235
+
236
+ Inspired by importlib.util.LazyLoader, but improved so that the module loading is
237
+ thread-safe. Circular dependency between modules can lead to a deadlock if the two
238
+ modules are loaded from different threads.
239
+
240
+ :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
241
+ """
242
+ try:
243
+ return sys.modules[name]
244
+ except KeyError:
245
+ spec = importlib.util.find_spec(name)
246
+ if spec is None:
247
+ raise ModuleNotFoundError
248
+ module = importlib.util.module_from_spec(spec)
249
+ module.__lazy_module_state__ = LazyModuleState(module) # type: ignore
250
+ module.__class__ = LazyModule
251
+ sys.modules[name] = module
252
+ return module
253
+
254
+
255
+ def get_module(
256
+ name: str,
257
+ required: Optional[Union[str, bool]] = None,
258
+ lazy: bool = True,
259
+ ) -> Any:
260
+ """Return module or None. Absolute import is required.
261
+
262
+ :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
263
+ :param (str) required: A string to raise a ValueError if missing
264
+ :param (bool) lazy: If True, return a lazy loader for the module.
265
+ :return: (module|None) If import succeeds, the module will be returned.
266
+ """
267
+ if name not in _not_importable:
268
+ try:
269
+ if not lazy:
270
+ return import_module(name)
271
+ else:
272
+ return import_module_lazy(name)
273
+ except Exception:
274
+ _not_importable.add(name)
275
+ msg = f"Error importing optional module {name}"
276
+ if required:
277
+ logger.exception(msg)
278
+ if required and name in _not_importable:
279
+ raise wandb.Error(required)
280
+
281
+
282
+ def get_optional_module(name) -> Optional["importlib.ModuleInterface"]: # type: ignore
283
+ return get_module(name)
284
+
285
+
286
+ np = get_module("numpy")
287
+
288
+ pd_available = False
289
+ pandas_spec = importlib.util.find_spec("pandas")
290
+ if pandas_spec is not None:
291
+ pd_available = True
292
+
293
+ # TODO: Revisit these limits
294
+ VALUE_BYTES_LIMIT = 100000
295
+
296
+
297
+ def app_url(api_url: str) -> str:
298
+ """Return the frontend app url without a trailing slash."""
299
+ # TODO: move me to settings
300
+ app_url = wandb.env.get_app_url()
301
+ if app_url is not None:
302
+ return str(app_url.strip("/"))
303
+ if "://api.wandb.test" in api_url:
304
+ # dev mode
305
+ return api_url.replace("://api.", "://app.").strip("/")
306
+ elif "://api.wandb." in api_url:
307
+ # cloud
308
+ return api_url.replace("://api.", "://").strip("/")
309
+ elif "://api." in api_url:
310
+ # onprem cloud
311
+ return api_url.replace("://api.", "://app.").strip("/")
312
+ # wandb/local
313
+ return api_url
314
+
315
+
316
+ def get_full_typename(o: Any) -> Any:
317
+ """Determine types based on type names.
318
+
319
+ Avoids needing to to import (and therefore depend on) PyTorch, TensorFlow, etc.
320
+ """
321
+ instance_name = o.__class__.__module__ + "." + o.__class__.__name__
322
+ if instance_name in ["builtins.module", "__builtin__.module"]:
323
+ return o.__name__
324
+ else:
325
+ return instance_name
326
+
327
+
328
+ def get_h5_typename(o: Any) -> Any:
329
+ typename = get_full_typename(o)
330
+ if is_tf_tensor_typename(typename):
331
+ return "tensorflow.Tensor"
332
+ elif is_pytorch_tensor_typename(typename):
333
+ return "torch.Tensor"
334
+ else:
335
+ return o.__class__.__module__.split(".")[0] + "." + o.__class__.__name__
336
+
337
+
338
+ def is_uri(string: str) -> bool:
339
+ parsed_uri = urllib.parse.urlparse(string)
340
+ return len(parsed_uri.scheme) > 0
341
+
342
+
343
+ def local_file_uri_to_path(uri: str) -> str:
344
+ """Convert URI to local filesystem path.
345
+
346
+ No-op if the uri does not have the expected scheme.
347
+ """
348
+ path = urllib.parse.urlparse(uri).path if uri.startswith("file:") else uri
349
+ return urllib.request.url2pathname(path)
350
+
351
+
352
+ def get_local_path_or_none(path_or_uri: str) -> Optional[str]:
353
+ """Return path if local, None otherwise.
354
+
355
+ Return None if the argument is a local path (not a scheme or file:///). Otherwise
356
+ return `path_or_uri`.
357
+ """
358
+ parsed_uri = urllib.parse.urlparse(path_or_uri)
359
+ if (
360
+ len(parsed_uri.scheme) == 0
361
+ or parsed_uri.scheme == "file"
362
+ and len(parsed_uri.netloc) == 0
363
+ ):
364
+ return local_file_uri_to_path(path_or_uri)
365
+ else:
366
+ return None
367
+
368
+
369
+ def make_tarfile(
370
+ output_filename: str,
371
+ source_dir: str,
372
+ archive_name: str,
373
+ custom_filter: Optional[Callable] = None,
374
+ ) -> None:
375
+ # Helper for filtering out modification timestamps
376
+ def _filter_timestamps(tar_info: "tarfile.TarInfo") -> Optional["tarfile.TarInfo"]:
377
+ tar_info.mtime = 0
378
+ return tar_info if custom_filter is None else custom_filter(tar_info)
379
+
380
+ descriptor, unzipped_filename = tempfile.mkstemp()
381
+ try:
382
+ with tarfile.open(unzipped_filename, "w") as tar:
383
+ tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps)
384
+ # When gzipping the tar, don't include the tar's filename or modification time in the
385
+ # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile)
386
+ with gzip.GzipFile(
387
+ filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0
388
+ ) as gzipped_tar, open(unzipped_filename, "rb") as tar_file:
389
+ gzipped_tar.write(tar_file.read())
390
+ finally:
391
+ os.close(descriptor)
392
+ os.remove(unzipped_filename)
393
+
394
+
395
+ def is_tf_tensor(obj: Any) -> bool:
396
+ import tensorflow # type: ignore
397
+
398
+ return isinstance(obj, tensorflow.Tensor)
399
+
400
+
401
+ def is_tf_tensor_typename(typename: str) -> bool:
402
+ return typename.startswith("tensorflow.") and (
403
+ "Tensor" in typename or "Variable" in typename
404
+ )
405
+
406
+
407
+ def is_tf_eager_tensor_typename(typename: str) -> bool:
408
+ return typename.startswith("tensorflow.") and ("EagerTensor" in typename)
409
+
410
+
411
+ def is_pytorch_tensor(obj: Any) -> bool:
412
+ import torch # type: ignore
413
+
414
+ return isinstance(obj, torch.Tensor)
415
+
416
+
417
+ def is_pytorch_tensor_typename(typename: str) -> bool:
418
+ return typename.startswith("torch.") and (
419
+ "Tensor" in typename or "Variable" in typename
420
+ )
421
+
422
+
423
+ def is_jax_tensor_typename(typename: str) -> bool:
424
+ return typename.startswith("jaxlib.") and "Array" in typename
425
+
426
+
427
+ def get_jax_tensor(obj: Any) -> Optional[Any]:
428
+ import jax # type: ignore
429
+
430
+ return jax.device_get(obj)
431
+
432
+
433
+ def is_fastai_tensor_typename(typename: str) -> bool:
434
+ return typename.startswith("fastai.") and ("Tensor" in typename)
435
+
436
+
437
+ def is_pandas_data_frame_typename(typename: str) -> bool:
438
+ return typename.startswith("pandas.") and "DataFrame" in typename
439
+
440
+
441
+ def is_matplotlib_typename(typename: str) -> bool:
442
+ return typename.startswith("matplotlib.")
443
+
444
+
445
+ def is_plotly_typename(typename: str) -> bool:
446
+ return typename.startswith("plotly.")
447
+
448
+
449
+ def is_plotly_figure_typename(typename: str) -> bool:
450
+ return typename.startswith("plotly.") and typename.endswith(".Figure")
451
+
452
+
453
+ def is_numpy_array(obj: Any) -> bool:
454
+ return np and isinstance(obj, np.ndarray)
455
+
456
+
457
+ def is_pandas_data_frame(obj: Any) -> bool:
458
+ if pd_available:
459
+ import pandas as pd
460
+
461
+ return isinstance(obj, pd.DataFrame)
462
+ else:
463
+ return is_pandas_data_frame_typename(get_full_typename(obj))
464
+
465
+
466
+ def ensure_matplotlib_figure(obj: Any) -> Any:
467
+ """Extract the current figure from a matplotlib object.
468
+
469
+ Return the object itself if it's a figure.
470
+ Raises ValueError if the object can't be converted.
471
+ """
472
+ import matplotlib # type: ignore
473
+ from matplotlib.figure import Figure # type: ignore
474
+
475
+ # there are combinations of plotly and matplotlib versions that don't work well together,
476
+ # this patches matplotlib to add a removed method that plotly assumes exists
477
+ from matplotlib.spines import Spine # type: ignore
478
+
479
+ def is_frame_like(self: Any) -> bool:
480
+ """Return True if directly on axes frame.
481
+
482
+ This is useful for determining if a spine is the edge of an
483
+ old style MPL plot. If so, this function will return True.
484
+ """
485
+ position = self._position or ("outward", 0.0)
486
+ if isinstance(position, str):
487
+ if position == "center":
488
+ position = ("axes", 0.5)
489
+ elif position == "zero":
490
+ position = ("data", 0)
491
+ if len(position) != 2:
492
+ raise ValueError("position should be 2-tuple")
493
+ position_type, amount = position # type: ignore
494
+ if position_type == "outward" and amount == 0:
495
+ return True
496
+ else:
497
+ return False
498
+
499
+ Spine.is_frame_like = is_frame_like
500
+
501
+ if obj == matplotlib.pyplot:
502
+ obj = obj.gcf()
503
+ elif not isinstance(obj, Figure):
504
+ if hasattr(obj, "figure"):
505
+ obj = obj.figure
506
+ # Some matplotlib objects have a figure function
507
+ if not isinstance(obj, Figure):
508
+ raise ValueError(
509
+ "Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted."
510
+ )
511
+ return obj
512
+
513
+
514
+ def matplotlib_to_plotly(obj: Any) -> Any:
515
+ obj = ensure_matplotlib_figure(obj)
516
+ tools = get_module(
517
+ "plotly.tools",
518
+ required=(
519
+ "plotly is required to log interactive plots, install with: "
520
+ "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
521
+ ),
522
+ )
523
+ return tools.mpl_to_plotly(obj)
524
+
525
+
526
+ def matplotlib_contains_images(obj: Any) -> bool:
527
+ obj = ensure_matplotlib_figure(obj)
528
+ return any(len(ax.images) > 0 for ax in obj.axes)
529
+
530
+
531
+ def _numpy_generic_convert(obj: Any) -> Any:
532
+ obj = obj.item()
533
+ if isinstance(obj, float) and math.isnan(obj):
534
+ obj = None
535
+ elif isinstance(obj, np.generic) and (
536
+ obj.dtype.kind == "f" or obj.dtype == "bfloat16"
537
+ ):
538
+ # obj is a numpy float with precision greater than that of native python float
539
+ # (i.e., float96 or float128) or it is of custom type such as bfloat16.
540
+ # in these cases, obj.item() does not return a native
541
+ # python float (in the first case - to avoid loss of precision,
542
+ # so we need to explicitly cast this down to a 64bit float)
543
+ obj = float(obj)
544
+ return obj
545
+
546
+
547
+ def _find_all_matching_keys(
548
+ d: Dict,
549
+ match_fn: Callable[[Any], bool],
550
+ visited: Optional[Set[int]] = None,
551
+ key_path: Tuple[Any, ...] = (),
552
+ ) -> Generator[Tuple[Tuple[Any, ...], Any], None, None]:
553
+ """Recursively find all keys that satisfies a match function.
554
+
555
+ Args:
556
+ d: The dict to search.
557
+ match_fn: The function to determine if the key is a match.
558
+ visited: Keep track of visited nodes so we dont recurse forever.
559
+ key_path: Keep track of all the keys to get to the current node.
560
+
561
+ Yields:
562
+ (key_path, key): The location where the key was found, and the key
563
+ """
564
+ if visited is None:
565
+ visited = set()
566
+ me = id(d)
567
+ if me not in visited:
568
+ visited.add(me)
569
+ for key, value in d.items():
570
+ if match_fn(key):
571
+ yield key_path, key
572
+ if isinstance(value, dict):
573
+ yield from _find_all_matching_keys(
574
+ value,
575
+ match_fn,
576
+ visited=visited,
577
+ key_path=tuple(list(key_path) + [key]),
578
+ )
579
+
580
+
581
+ def _sanitize_numpy_keys(d: Dict) -> Tuple[Dict, bool]:
582
+ np_keys = list(_find_all_matching_keys(d, lambda k: isinstance(k, np.generic)))
583
+ if not np_keys:
584
+ return d, False
585
+ for key_path, key in np_keys:
586
+ ptr = d
587
+ for k in key_path:
588
+ ptr = ptr[k]
589
+ ptr[_numpy_generic_convert(key)] = ptr.pop(key)
590
+ return d, True
591
+
592
+
593
+ def json_friendly( # noqa: C901
594
+ obj: Any,
595
+ ) -> Union[Tuple[Any, bool], Tuple[Union[None, str, float], bool]]:
596
+ """Convert an object into something that's more becoming of JSON."""
597
+ converted = True
598
+ typename = get_full_typename(obj)
599
+
600
+ if is_tf_eager_tensor_typename(typename):
601
+ obj = obj.numpy()
602
+ elif is_tf_tensor_typename(typename):
603
+ try:
604
+ obj = obj.eval()
605
+ except RuntimeError:
606
+ obj = obj.numpy()
607
+ elif is_pytorch_tensor_typename(typename) or is_fastai_tensor_typename(typename):
608
+ try:
609
+ if obj.requires_grad:
610
+ obj = obj.detach()
611
+ except AttributeError:
612
+ pass # before 0.4 is only present on variables
613
+
614
+ try:
615
+ obj = obj.data
616
+ except RuntimeError:
617
+ pass # happens for Tensors before 0.4
618
+
619
+ if obj.size():
620
+ obj = obj.cpu().detach().numpy()
621
+ else:
622
+ return obj.item(), True
623
+ elif is_jax_tensor_typename(typename):
624
+ obj = get_jax_tensor(obj)
625
+
626
+ if is_numpy_array(obj):
627
+ if obj.size == 1:
628
+ obj = obj.flatten()[0]
629
+ elif obj.size <= 32:
630
+ obj = obj.tolist()
631
+ elif np and isinstance(obj, np.generic):
632
+ obj = _numpy_generic_convert(obj)
633
+ elif isinstance(obj, bytes):
634
+ obj = obj.decode("utf-8")
635
+ elif isinstance(obj, (datetime, date)):
636
+ obj = obj.isoformat()
637
+ elif callable(obj):
638
+ obj = (
639
+ f"{obj.__module__}.{obj.__qualname__}"
640
+ if hasattr(obj, "__qualname__") and hasattr(obj, "__module__")
641
+ else str(obj)
642
+ )
643
+ elif isinstance(obj, float) and math.isnan(obj):
644
+ obj = None
645
+ elif isinstance(obj, dict) and np:
646
+ obj, converted = _sanitize_numpy_keys(obj)
647
+ elif isinstance(obj, set):
648
+ # set is not json serializable, so we convert it to tuple
649
+ obj = tuple(obj)
650
+ else:
651
+ converted = False
652
+ if getsizeof(obj) > VALUE_BYTES_LIMIT:
653
+ wandb.termwarn(
654
+ "Serializing object of type {} that is {} bytes".format(
655
+ type(obj).__name__, getsizeof(obj)
656
+ )
657
+ )
658
+ return obj, converted
659
+
660
+
661
+ def json_friendly_val(val: Any) -> Any:
662
+ """Make any value (including dict, slice, sequence, dataclass) JSON friendly."""
663
+ converted: Union[dict, list]
664
+ if isinstance(val, dict):
665
+ converted = {}
666
+ for key, value in val.items():
667
+ converted[key] = json_friendly_val(value)
668
+ return converted
669
+ if isinstance(val, slice):
670
+ converted = dict(
671
+ slice_start=val.start, slice_step=val.step, slice_stop=val.stop
672
+ )
673
+ return converted
674
+ val, _ = json_friendly(val)
675
+ if isinstance(val, Sequence) and not isinstance(val, str):
676
+ converted = []
677
+ for value in val:
678
+ converted.append(json_friendly_val(value))
679
+ return converted
680
+ if is_dataclass(val) and not isinstance(val, type):
681
+ converted = asdict(val)
682
+ return converted
683
+ else:
684
+ if val.__class__.__module__ not in ("builtins", "__builtin__"):
685
+ val = str(val)
686
+ return val
687
+
688
+
689
+ def alias_is_version_index(alias: str) -> bool:
690
+ return len(alias) >= 2 and alias[0] == "v" and alias[1:].isnumeric()
691
+
692
+
693
+ def convert_plots(obj: Any) -> Any:
694
+ if is_matplotlib_typename(get_full_typename(obj)):
695
+ tools = get_module(
696
+ "plotly.tools",
697
+ required=(
698
+ "plotly is required to log interactive plots, install with: "
699
+ "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
700
+ ),
701
+ )
702
+ obj = tools.mpl_to_plotly(obj)
703
+
704
+ if is_plotly_typename(get_full_typename(obj)):
705
+ return {"_type": "plotly", "plot": obj.to_plotly_json()}
706
+ else:
707
+ return obj
708
+
709
+
710
+ def maybe_compress_history(obj: Any) -> Tuple[Any, bool]:
711
+ if np and isinstance(obj, np.ndarray) and obj.size > 32:
712
+ return wandb.Histogram(obj, num_bins=32).to_json(), True
713
+ else:
714
+ return obj, False
715
+
716
+
717
+ def maybe_compress_summary(obj: Any, h5_typename: str) -> Tuple[Any, bool]:
718
+ if np and isinstance(obj, np.ndarray) and obj.size > 32:
719
+ return (
720
+ {
721
+ "_type": h5_typename, # may not be ndarray
722
+ "var": np.var(obj).item(),
723
+ "mean": np.mean(obj).item(),
724
+ "min": np.amin(obj).item(),
725
+ "max": np.amax(obj).item(),
726
+ "10%": np.percentile(obj, 10),
727
+ "25%": np.percentile(obj, 25),
728
+ "75%": np.percentile(obj, 75),
729
+ "90%": np.percentile(obj, 90),
730
+ "size": obj.size,
731
+ },
732
+ True,
733
+ )
734
+ else:
735
+ return obj, False
736
+
737
+
738
+ def launch_browser(attempt_launch_browser: bool = True) -> bool:
739
+ """Decide if we should launch a browser."""
740
+ _display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"]
741
+ _webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"]
742
+
743
+ import webbrowser
744
+
745
+ launch_browser = attempt_launch_browser
746
+ if launch_browser:
747
+ if "linux" in sys.platform and not any(
748
+ os.getenv(var) for var in _display_variables
749
+ ):
750
+ launch_browser = False
751
+ try:
752
+ browser = webbrowser.get()
753
+ if hasattr(browser, "name") and browser.name in _webbrowser_names_blocklist:
754
+ launch_browser = False
755
+ except webbrowser.Error:
756
+ launch_browser = False
757
+
758
+ return launch_browser
759
+
760
+
761
+ def generate_id(length: int = 8) -> str:
762
+ # Do not use this; use wandb.sdk.lib.runid.generate_id instead.
763
+ # This is kept only for legacy code.
764
+ return runid.generate_id(length)
765
+
766
+
767
+ def parse_tfjob_config() -> Any:
768
+ """Attempt to parse TFJob config, returning False if it can't find it."""
769
+ if os.getenv("TF_CONFIG"):
770
+ try:
771
+ return json.loads(os.environ["TF_CONFIG"])
772
+ except ValueError:
773
+ return False
774
+ else:
775
+ return False
776
+
777
+
778
+ class WandBJSONEncoder(json.JSONEncoder):
779
+ """A JSON Encoder that handles some extra types."""
780
+
781
+ def default(self, obj: Any) -> Any:
782
+ if hasattr(obj, "json_encode"):
783
+ return obj.json_encode()
784
+ # if hasattr(obj, 'to_json'):
785
+ # return obj.to_json()
786
+ tmp_obj, converted = json_friendly(obj)
787
+ if converted:
788
+ return tmp_obj
789
+ return json.JSONEncoder.default(self, obj)
790
+
791
+
792
+ class WandBJSONEncoderOld(json.JSONEncoder):
793
+ """A JSON Encoder that handles some extra types."""
794
+
795
+ def default(self, obj: Any) -> Any:
796
+ tmp_obj, converted = json_friendly(obj)
797
+ tmp_obj, compressed = maybe_compress_summary(tmp_obj, get_h5_typename(obj))
798
+ if converted:
799
+ return tmp_obj
800
+ return json.JSONEncoder.default(self, tmp_obj)
801
+
802
+
803
+ class WandBHistoryJSONEncoder(json.JSONEncoder):
804
+ """A JSON Encoder that handles some extra types.
805
+
806
+ This encoder turns numpy like objects with a size > 32 into histograms.
807
+ """
808
+
809
+ def default(self, obj: Any) -> Any:
810
+ obj, converted = json_friendly(obj)
811
+ obj, compressed = maybe_compress_history(obj)
812
+ if converted:
813
+ return obj
814
+ return json.JSONEncoder.default(self, obj)
815
+
816
+
817
+ class JSONEncoderUncompressed(json.JSONEncoder):
818
+ """A JSON Encoder that handles some extra types.
819
+
820
+ This encoder turns numpy like objects with a size > 32 into histograms.
821
+ """
822
+
823
+ def default(self, obj: Any) -> Any:
824
+ if is_numpy_array(obj):
825
+ return obj.tolist()
826
+ elif np and isinstance(obj, np.generic):
827
+ obj = obj.item()
828
+ return json.JSONEncoder.default(self, obj)
829
+
830
+
831
+ def json_dump_safer(obj: Any, fp: IO[str], **kwargs: Any) -> None:
832
+ """Convert obj to json, with some extra encodable types."""
833
+ return dump(obj, fp, cls=WandBJSONEncoder, **kwargs)
834
+
835
+
836
+ def json_dumps_safer(obj: Any, **kwargs: Any) -> str:
837
+ """Convert obj to json, with some extra encodable types."""
838
+ return dumps(obj, cls=WandBJSONEncoder, **kwargs)
839
+
840
+
841
+ # This is used for dumping raw json into files
842
+ def json_dump_uncompressed(obj: Any, fp: IO[str], **kwargs: Any) -> None:
843
+ """Convert obj to json, with some extra encodable types."""
844
+ return dump(obj, fp, cls=JSONEncoderUncompressed, **kwargs)
845
+
846
+
847
+ def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str:
848
+ """Convert obj to json, with some extra encodable types, including histograms."""
849
+ return dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs)
850
+
851
+
852
+ def make_json_if_not_number(
853
+ v: Union[int, float, str, Mapping, Sequence],
854
+ ) -> Union[int, float, str]:
855
+ """If v is not a basic type convert it to json."""
856
+ if isinstance(v, (float, int)):
857
+ return v
858
+ return json_dumps_safer(v)
859
+
860
+
861
+ def make_safe_for_json(obj: Any) -> Any:
862
+ """Replace invalid json floats with strings. Also converts to lists and dicts."""
863
+ if isinstance(obj, Mapping):
864
+ return {k: make_safe_for_json(v) for k, v in obj.items()}
865
+ elif isinstance(obj, str):
866
+ # str's are Sequence, so we need to short-circuit
867
+ return obj
868
+ elif isinstance(obj, Sequence):
869
+ return [make_safe_for_json(v) for v in obj]
870
+ elif isinstance(obj, float):
871
+ # W&B backend and UI handle these strings
872
+ if obj != obj: # standard way to check for NaN
873
+ return "NaN"
874
+ elif obj == float("+inf"):
875
+ return "Infinity"
876
+ elif obj == float("-inf"):
877
+ return "-Infinity"
878
+ return obj
879
+
880
+
881
+ def no_retry_4xx(e: Exception) -> bool:
882
+ if not isinstance(e, requests.HTTPError):
883
+ return True
884
+ assert e.response is not None
885
+ if not (400 <= e.response.status_code < 500) or e.response.status_code == 429:
886
+ return True
887
+ body = json.loads(e.response.content)
888
+ raise UsageError(body["errors"][0]["message"])
889
+
890
+
891
+ def no_retry_auth(e: Any) -> bool:
892
+ if hasattr(e, "exception"):
893
+ e = e.exception
894
+ if not isinstance(e, requests.HTTPError):
895
+ return True
896
+ if e.response is None:
897
+ return True
898
+ # Don't retry bad request errors; raise immediately
899
+ if e.response.status_code in (400, 409):
900
+ return False
901
+ # Retry all non-forbidden/unauthorized/not-found errors.
902
+ if e.response.status_code not in (401, 403, 404):
903
+ return True
904
+ # Crash w/message on forbidden/unauthorized errors.
905
+ if e.response.status_code == 401:
906
+ raise AuthenticationError(
907
+ "The API key you provided is either invalid or missing. "
908
+ f"If the `{wandb.env.API_KEY}` environment variable is set, make sure it is correct. "
909
+ "Otherwise, to resolve this issue, you may try running the 'wandb login --relogin' command. "
910
+ "If you are using a local server, make sure that you're using the correct hostname. "
911
+ "If you're not sure, you can try logging in again using the 'wandb login --relogin --host [hostname]' command."
912
+ f"(Error {e.response.status_code}: {e.response.reason})"
913
+ )
914
+ elif wandb.run:
915
+ raise CommError(f"Permission denied to access {wandb.run.path}")
916
+ else:
917
+ raise CommError(
918
+ "It appears that you do not have permission to access the requested resource. "
919
+ "Please reach out to the project owner to grant you access. "
920
+ "If you have the correct permissions, verify that there are no issues with your networking setup."
921
+ f"(Error {e.response.status_code}: {e.response.reason})"
922
+ )
923
+
924
+
925
+ def check_retry_conflict(e: Any) -> Optional[bool]:
926
+ """Check if the exception is a conflict type so it can be retried.
927
+
928
+ Returns:
929
+ True - Should retry this operation
930
+ False - Should not retry this operation
931
+ None - No decision, let someone else decide
932
+ """
933
+ if hasattr(e, "exception"):
934
+ e = e.exception
935
+ if isinstance(e, requests.HTTPError) and e.response is not None:
936
+ if e.response.status_code == 409:
937
+ return True
938
+ return None
939
+
940
+
941
+ def check_retry_conflict_or_gone(e: Any) -> Optional[bool]:
942
+ """Check if the exception is a conflict or gone type, so it can be retried or not.
943
+
944
+ Returns:
945
+ True - Should retry this operation
946
+ False - Should not retry this operation
947
+ None - No decision, let someone else decide
948
+ """
949
+ if hasattr(e, "exception"):
950
+ e = e.exception
951
+ if isinstance(e, requests.HTTPError) and e.response is not None:
952
+ if e.response.status_code == 409:
953
+ return True
954
+ if e.response.status_code == 410:
955
+ return False
956
+ return None
957
+
958
+
959
+ def make_check_retry_fn(
960
+ fallback_retry_fn: CheckRetryFnType,
961
+ check_fn: Callable[[Exception], Optional[bool]],
962
+ check_timedelta: Optional[timedelta] = None,
963
+ ) -> CheckRetryFnType:
964
+ """Return a check_retry_fn which can be used by lib.Retry().
965
+
966
+ Arguments:
967
+ fallback_fn: Use this function if check_fn didn't decide if a retry should happen.
968
+ check_fn: Function which returns bool if retry should happen or None if unsure.
969
+ check_timedelta: Optional retry timeout if we check_fn matches the exception
970
+ """
971
+
972
+ def check_retry_fn(e: Exception) -> Union[bool, timedelta]:
973
+ check = check_fn(e)
974
+ if check is None:
975
+ return fallback_retry_fn(e)
976
+ if check is False:
977
+ return False
978
+ if check_timedelta:
979
+ return check_timedelta
980
+ return True
981
+
982
+ return check_retry_fn
983
+
984
+
985
+ def find_runner(program: str) -> Union[None, list, List[str]]:
986
+ """Return a command that will run program.
987
+
988
+ Arguments:
989
+ program: The string name of the program to try to run.
990
+
991
+ Returns:
992
+ commandline list of strings to run the program (eg. with subprocess.call()) or None
993
+ """
994
+ if os.path.isfile(program) and not os.access(program, os.X_OK):
995
+ # program is a path to a non-executable file
996
+ try:
997
+ opened = open(program)
998
+ except OSError: # PermissionError doesn't exist in 2.7
999
+ return None
1000
+ first_line = opened.readline().strip()
1001
+ if first_line.startswith("#!"):
1002
+ return shlex.split(first_line[2:])
1003
+ if program.endswith(".py"):
1004
+ return [sys.executable]
1005
+ return None
1006
+
1007
+
1008
+ def downsample(values: Sequence, target_length: int) -> list:
1009
+ """Downsample 1d values to target_length, including start and end.
1010
+
1011
+ Algorithm just rounds index down.
1012
+
1013
+ Values can be any sequence, including a generator.
1014
+ """
1015
+ if not target_length > 1:
1016
+ raise UsageError("target_length must be > 1")
1017
+ values = list(values)
1018
+ if len(values) < target_length:
1019
+ return values
1020
+ ratio = float(len(values) - 1) / (target_length - 1)
1021
+ result = []
1022
+ for i in range(target_length):
1023
+ result.append(values[int(i * ratio)])
1024
+ return result
1025
+
1026
+
1027
+ def has_num(dictionary: Mapping, key: Any) -> bool:
1028
+ return key in dictionary and isinstance(dictionary[key], numbers.Number)
1029
+
1030
+
1031
+ def get_log_file_path() -> str:
1032
+ """Log file path used in error messages.
1033
+
1034
+ It would probably be better if this pointed to a log file in a
1035
+ run directory.
1036
+ """
1037
+ # TODO(jhr, cvp): refactor
1038
+ if wandb.run is not None:
1039
+ return wandb.run._settings.log_internal
1040
+ return os.path.join("wandb", "debug-internal.log")
1041
+
1042
+
1043
+ def docker_image_regex(image: str) -> Any:
1044
+ """Regex match for valid docker image names."""
1045
+ if image:
1046
+ return re.match(
1047
+ r"^(?:(?=[^:\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![._-]))*)(?::(?![.-])[a-zA-Z0-9_.-]{1,128})?$",
1048
+ image,
1049
+ )
1050
+ return None
1051
+
1052
+
1053
+ def image_from_docker_args(args: List[str]) -> Optional[str]:
1054
+ """Scan docker run args and attempt to find the most likely docker image argument.
1055
+
1056
+ It excludes any arguments that start with a dash, and the argument after it if it
1057
+ isn't a boolean switch. This can be improved, we currently fallback gracefully when
1058
+ this fails.
1059
+ """
1060
+ bool_args = [
1061
+ "-t",
1062
+ "--tty",
1063
+ "--rm",
1064
+ "--privileged",
1065
+ "--oom-kill-disable",
1066
+ "--no-healthcheck",
1067
+ "-i",
1068
+ "--interactive",
1069
+ "--init",
1070
+ "--help",
1071
+ "--detach",
1072
+ "-d",
1073
+ "--sig-proxy",
1074
+ "-it",
1075
+ "-itd",
1076
+ ]
1077
+ last_flag = -2
1078
+ last_arg = ""
1079
+ possible_images = []
1080
+ if len(args) > 0 and args[0] == "run":
1081
+ args.pop(0)
1082
+ for i, arg in enumerate(args):
1083
+ if arg.startswith("-"):
1084
+ last_flag = i
1085
+ last_arg = arg
1086
+ elif "@sha256:" in arg:
1087
+ # Because our regex doesn't match digests
1088
+ possible_images.append(arg)
1089
+ elif docker_image_regex(arg):
1090
+ if last_flag == i - 2:
1091
+ possible_images.append(arg)
1092
+ elif "=" in last_arg:
1093
+ possible_images.append(arg)
1094
+ elif last_arg in bool_args and last_flag == i - 1:
1095
+ possible_images.append(arg)
1096
+ most_likely = None
1097
+ for img in possible_images:
1098
+ if ":" in img or "@" in img or "/" in img:
1099
+ most_likely = img
1100
+ break
1101
+ if most_likely is None and len(possible_images) > 0:
1102
+ most_likely = possible_images[0]
1103
+ return most_likely
1104
+
1105
+
1106
+ def load_yaml(file: Any) -> Any:
1107
+ return yaml.safe_load(file)
1108
+
1109
+
1110
+ def image_id_from_k8s() -> Optional[str]:
1111
+ """Ping the k8s metadata service for the image id.
1112
+
1113
+ Specify the KUBERNETES_NAMESPACE environment variable if your pods are not in the
1114
+ default namespace:
1115
+
1116
+ - name: KUBERNETES_NAMESPACE valueFrom:
1117
+ fieldRef:
1118
+ fieldPath: metadata.namespace
1119
+ """
1120
+ token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
1121
+
1122
+ if not os.path.exists(token_path):
1123
+ return None
1124
+
1125
+ try:
1126
+ with open(token_path) as token_file:
1127
+ token = token_file.read()
1128
+ except FileNotFoundError:
1129
+ logger.warning(f"Token file not found at {token_path}.")
1130
+ return None
1131
+ except PermissionError as e:
1132
+ current_uid = os.getuid()
1133
+ warning = (
1134
+ f"Unable to read the token file at {token_path} due to permission error ({e})."
1135
+ f"The current user id is {current_uid}. "
1136
+ "Consider changing the securityContext to run the container as the current user."
1137
+ )
1138
+ logger.warning(warning)
1139
+ wandb.termwarn(warning)
1140
+ return None
1141
+
1142
+ if not token:
1143
+ return None
1144
+
1145
+ k8s_server = "https://{}:{}/api/v1/namespaces/{}/pods/{}".format(
1146
+ os.getenv("KUBERNETES_SERVICE_HOST"),
1147
+ os.getenv("KUBERNETES_PORT_443_TCP_PORT"),
1148
+ os.getenv("KUBERNETES_NAMESPACE", "default"),
1149
+ os.getenv("HOSTNAME"),
1150
+ )
1151
+ try:
1152
+ res = requests.get(
1153
+ k8s_server,
1154
+ verify="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
1155
+ timeout=3,
1156
+ headers={"Authorization": f"Bearer {token}"},
1157
+ )
1158
+ res.raise_for_status()
1159
+ except requests.RequestException:
1160
+ return None
1161
+ try:
1162
+ return str( # noqa: B005
1163
+ res.json()["status"]["containerStatuses"][0]["imageID"]
1164
+ ).strip("docker-pullable://")
1165
+ except (ValueError, KeyError, IndexError):
1166
+ logger.exception("Error checking kubernetes for image id")
1167
+ return None
1168
+
1169
+
1170
+ def async_call(
1171
+ target: Callable, timeout: Optional[Union[int, float]] = None
1172
+ ) -> Callable:
1173
+ """Wrap a method to run in the background with an optional timeout.
1174
+
1175
+ Returns a new method that will call the original with any args, waiting for upto
1176
+ timeout seconds. This new method blocks on the original and returns the result or
1177
+ None if timeout was reached, along with the thread. You can check thread.is_alive()
1178
+ to determine if a timeout was reached. If an exception is thrown in the thread, we
1179
+ reraise it.
1180
+ """
1181
+ q: queue.Queue = queue.Queue()
1182
+
1183
+ def wrapped_target(q: "queue.Queue", *args: Any, **kwargs: Any) -> Any:
1184
+ try:
1185
+ q.put(target(*args, **kwargs))
1186
+ except Exception as e:
1187
+ q.put(e)
1188
+
1189
+ def wrapper(
1190
+ *args: Any, **kwargs: Any
1191
+ ) -> Union[Tuple[Exception, "threading.Thread"], Tuple[None, "threading.Thread"]]:
1192
+ thread = threading.Thread(
1193
+ target=wrapped_target, args=(q,) + args, kwargs=kwargs
1194
+ )
1195
+ thread.daemon = True
1196
+ thread.start()
1197
+ try:
1198
+ result = q.get(True, timeout)
1199
+ if isinstance(result, Exception):
1200
+ raise result.with_traceback(sys.exc_info()[2])
1201
+ return result, thread
1202
+ except queue.Empty:
1203
+ return None, thread
1204
+
1205
+ return wrapper
1206
+
1207
+
1208
+ def read_many_from_queue(
1209
+ q: "queue.Queue", max_items: int, queue_timeout: Union[int, float]
1210
+ ) -> list:
1211
+ try:
1212
+ item = q.get(True, queue_timeout)
1213
+ except queue.Empty:
1214
+ return []
1215
+ items = [item]
1216
+ for _ in range(max_items):
1217
+ try:
1218
+ item = q.get_nowait()
1219
+ except queue.Empty:
1220
+ return items
1221
+ items.append(item)
1222
+ return items
1223
+
1224
+
1225
+ def stopwatch_now() -> float:
1226
+ """Get a time value for interval comparisons.
1227
+
1228
+ When possible it is a monotonic clock to prevent backwards time issues.
1229
+ """
1230
+ return time.monotonic()
1231
+
1232
+
1233
+ def class_colors(class_count: int) -> List[List[int]]:
1234
+ # make class 0 black, and the rest equally spaced fully saturated hues
1235
+ return [[0, 0, 0]] + [
1236
+ colorsys.hsv_to_rgb(i / (class_count - 1.0), 1.0, 1.0) # type: ignore
1237
+ for i in range(class_count - 1)
1238
+ ]
1239
+
1240
+
1241
+ def _prompt_choice(
1242
+ input_timeout: Union[int, float, None] = None,
1243
+ jupyter: bool = False,
1244
+ ) -> str:
1245
+ input_fn: Callable = input
1246
+ prompt = term.LOG_STRING
1247
+ if input_timeout is not None:
1248
+ # delayed import to mitigate risk of timed_input complexity
1249
+ from wandb.sdk.lib import timed_input
1250
+
1251
+ input_fn = functools.partial(timed_input.timed_input, timeout=input_timeout)
1252
+ # timed_input doesn't handle enhanced prompts
1253
+ if platform.system() == "Windows":
1254
+ prompt = "wandb"
1255
+
1256
+ text = f"{prompt}: Enter your choice: "
1257
+ if input_fn == input:
1258
+ choice = input_fn(text)
1259
+ else:
1260
+ choice = input_fn(text, jupyter=jupyter)
1261
+ return choice # type: ignore
1262
+
1263
+
1264
+ def prompt_choices(
1265
+ choices: Sequence[str],
1266
+ input_timeout: Union[int, float, None] = None,
1267
+ jupyter: bool = False,
1268
+ ) -> str:
1269
+ """Allow a user to choose from a list of options."""
1270
+ for i, choice in enumerate(choices):
1271
+ wandb.termlog(f"({i+1}) {choice}")
1272
+
1273
+ idx = -1
1274
+ while idx < 0 or idx > len(choices) - 1:
1275
+ choice = _prompt_choice(input_timeout=input_timeout, jupyter=jupyter)
1276
+ if not choice:
1277
+ continue
1278
+ idx = -1
1279
+ try:
1280
+ idx = int(choice) - 1
1281
+ except ValueError:
1282
+ pass
1283
+ if idx < 0 or idx > len(choices) - 1:
1284
+ wandb.termwarn("Invalid choice")
1285
+ result = choices[idx]
1286
+ wandb.termlog(f"You chose {result!r}")
1287
+ return result
1288
+
1289
+
1290
+ def guess_data_type(shape: Sequence[int], risky: bool = False) -> Optional[str]:
1291
+ """Infer the type of data based on the shape of the tensors.
1292
+
1293
+ Arguments:
1294
+ shape (Sequence[int]): The shape of the data
1295
+ risky(bool): some guesses are more likely to be wrong.
1296
+ """
1297
+ # (samples,) or (samples,logits)
1298
+ if len(shape) in (1, 2):
1299
+ return "label"
1300
+ # Assume image mask like fashion mnist: (no color channel)
1301
+ # This is risky because RNNs often have 3 dim tensors: batch, time, channels
1302
+ if risky and len(shape) == 3:
1303
+ return "image"
1304
+ if len(shape) == 4:
1305
+ if shape[-1] in (1, 3, 4):
1306
+ # (samples, height, width, Y \ RGB \ RGBA)
1307
+ return "image"
1308
+ else:
1309
+ # (samples, height, width, logits)
1310
+ return "segmentation_mask"
1311
+ return None
1312
+
1313
+
1314
+ def download_file_from_url(
1315
+ dest_path: str, source_url: str, api_key: Optional[str] = None
1316
+ ) -> None:
1317
+ auth = None
1318
+ if not _thread_local_api_settings.cookies:
1319
+ auth = ("api", api_key or "")
1320
+ response = requests.get(
1321
+ source_url,
1322
+ auth=auth,
1323
+ headers=_thread_local_api_settings.headers,
1324
+ cookies=_thread_local_api_settings.cookies,
1325
+ stream=True,
1326
+ timeout=5,
1327
+ )
1328
+ response.raise_for_status()
1329
+
1330
+ if os.sep in dest_path:
1331
+ filesystem.mkdir_exists_ok(os.path.dirname(dest_path))
1332
+ with fsync_open(dest_path, "wb") as file:
1333
+ for data in response.iter_content(chunk_size=1024):
1334
+ file.write(data)
1335
+
1336
+
1337
+ def download_file_into_memory(source_url: str, api_key: Optional[str] = None) -> bytes:
1338
+ auth = None
1339
+ if not _thread_local_api_settings.cookies:
1340
+ auth = ("api", api_key or "")
1341
+ response = requests.get(
1342
+ source_url,
1343
+ auth=auth,
1344
+ headers=_thread_local_api_settings.headers,
1345
+ cookies=_thread_local_api_settings.cookies,
1346
+ stream=True,
1347
+ timeout=5,
1348
+ )
1349
+ response.raise_for_status()
1350
+ return response.content
1351
+
1352
+
1353
+ def isatty(ob: IO) -> bool:
1354
+ return hasattr(ob, "isatty") and ob.isatty()
1355
+
1356
+
1357
+ def to_human_size(size: int, units: Optional[List[Tuple[str, Any]]] = None) -> str:
1358
+ units = units or POW_10_BYTES
1359
+ unit, value = units[0]
1360
+ factor = round(float(size) / value, 1)
1361
+ return (
1362
+ f"{factor}{unit}"
1363
+ if factor < 1024 or len(units) == 1
1364
+ else to_human_size(size, units[1:])
1365
+ )
1366
+
1367
+
1368
+ def from_human_size(size: str, units: Optional[List[Tuple[str, Any]]] = None) -> int:
1369
+ units = units or POW_10_BYTES
1370
+ units_dict = {unit.upper(): value for (unit, value) in units}
1371
+ regex = re.compile(
1372
+ r"(\d+\.?\d*)\s*({})?".format("|".join(units_dict.keys())), re.IGNORECASE
1373
+ )
1374
+ match = re.match(regex, size)
1375
+ if not match:
1376
+ raise ValueError("size must be of the form `10`, `10B` or `10 B`.")
1377
+ factor, unit = (
1378
+ float(match.group(1)),
1379
+ units_dict[match.group(2).upper()] if match.group(2) else 1,
1380
+ )
1381
+ return int(factor * unit)
1382
+
1383
+
1384
+ def auto_project_name(program: Optional[str]) -> str:
1385
+ # if we're in git, set project name to git repo name + relative path within repo
1386
+ from wandb.sdk.lib.gitlib import GitRepo
1387
+
1388
+ root_dir = GitRepo().root_dir
1389
+ if root_dir is None:
1390
+ return "uncategorized"
1391
+ # On windows, GitRepo returns paths in unix style, but os.path is windows
1392
+ # style. Coerce here.
1393
+ root_dir = to_native_slash_path(root_dir)
1394
+ repo_name = os.path.basename(root_dir)
1395
+ if program is None:
1396
+ return str(repo_name)
1397
+ if not os.path.isabs(program):
1398
+ program = os.path.join(os.curdir, program)
1399
+ prog_dir = os.path.dirname(os.path.abspath(program))
1400
+ if not prog_dir.startswith(root_dir):
1401
+ return str(repo_name)
1402
+ project = repo_name
1403
+ sub_path = os.path.relpath(prog_dir, root_dir)
1404
+ if sub_path != ".":
1405
+ project += "-" + sub_path
1406
+ return str(project.replace(os.sep, "_"))
1407
+
1408
+
1409
+ # TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py
1410
+ def to_forward_slash_path(path: str) -> str:
1411
+ if platform.system() == "Windows":
1412
+ path = path.replace("\\", "/")
1413
+ return path
1414
+
1415
+
1416
+ # TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py
1417
+ def to_native_slash_path(path: str) -> FilePathStr:
1418
+ return FilePathStr(path.replace("/", os.sep))
1419
+
1420
+
1421
+ def check_and_warn_old(files: List[str]) -> bool:
1422
+ if "wandb-metadata.json" in files:
1423
+ wandb.termwarn("These runs were logged with a previous version of wandb.")
1424
+ wandb.termwarn(
1425
+ "Run pip install wandb<0.10.0 to get the old library and sync your runs."
1426
+ )
1427
+ return True
1428
+ return False
1429
+
1430
+
1431
+ class ImportMetaHook:
1432
+ def __init__(self) -> None:
1433
+ self.modules: Dict[str, ModuleType] = dict()
1434
+ self.on_import: Dict[str, list] = dict()
1435
+
1436
+ def add(self, fullname: str, on_import: Callable) -> None:
1437
+ self.on_import.setdefault(fullname, []).append(on_import)
1438
+
1439
+ def install(self) -> None:
1440
+ sys.meta_path.insert(0, self) # type: ignore
1441
+
1442
+ def uninstall(self) -> None:
1443
+ sys.meta_path.remove(self) # type: ignore
1444
+
1445
+ def find_module(
1446
+ self, fullname: str, path: Optional[str] = None
1447
+ ) -> Optional["ImportMetaHook"]:
1448
+ if fullname in self.on_import:
1449
+ return self
1450
+ return None
1451
+
1452
+ def load_module(self, fullname: str) -> ModuleType:
1453
+ self.uninstall()
1454
+ mod = importlib.import_module(fullname)
1455
+ self.install()
1456
+ self.modules[fullname] = mod
1457
+ on_imports = self.on_import.get(fullname)
1458
+ if on_imports:
1459
+ for f in on_imports:
1460
+ f()
1461
+ return mod
1462
+
1463
+ def get_modules(self) -> Tuple[str, ...]:
1464
+ return tuple(self.modules)
1465
+
1466
+ def get_module(self, module: str) -> ModuleType:
1467
+ return self.modules[module]
1468
+
1469
+
1470
+ _import_hook: Optional[ImportMetaHook] = None
1471
+
1472
+
1473
+ def add_import_hook(fullname: str, on_import: Callable) -> None:
1474
+ global _import_hook
1475
+ if _import_hook is None:
1476
+ _import_hook = ImportMetaHook()
1477
+ _import_hook.install()
1478
+ _import_hook.add(fullname, on_import)
1479
+
1480
+
1481
+ def host_from_path(path: Optional[str]) -> str:
1482
+ """Return the host of the path."""
1483
+ url = urllib.parse.urlparse(path)
1484
+ return str(url.netloc)
1485
+
1486
+
1487
+ def uri_from_path(path: Optional[str]) -> str:
1488
+ """Return the URI of the path."""
1489
+ url = urllib.parse.urlparse(path)
1490
+ uri = url.path if url.path[0] != "/" else url.path[1:]
1491
+ return str(uri)
1492
+
1493
+
1494
+ def is_unicode_safe(stream: TextIO) -> bool:
1495
+ """Return True if the stream supports UTF-8."""
1496
+ encoding = getattr(stream, "encoding", None)
1497
+ return encoding.lower() in {"utf-8", "utf_8"} if encoding else False
1498
+
1499
+
1500
+ def _has_internet() -> bool:
1501
+ """Attempt to open a DNS connection to Googles root servers."""
1502
+ try:
1503
+ s = socket.create_connection(("8.8.8.8", 53), 0.5)
1504
+ s.close()
1505
+ return True
1506
+ except OSError:
1507
+ return False
1508
+
1509
+
1510
+ def rand_alphanumeric(
1511
+ length: int = 8, rand: Optional[Union[ModuleType, random.Random]] = None
1512
+ ) -> str:
1513
+ wandb.termerror("rand_alphanumeric is deprecated, use 'secrets.token_hex'")
1514
+ rand = rand or random
1515
+ return "".join(rand.choice("0123456789ABCDEF") for _ in range(length))
1516
+
1517
+
1518
+ @contextlib.contextmanager
1519
+ def fsync_open(
1520
+ path: StrPath, mode: str = "w", encoding: Optional[str] = None
1521
+ ) -> Generator[IO[Any], None, None]:
1522
+ """Open a path for I/O and guarantee that the file is flushed and synced."""
1523
+ with open(path, mode, encoding=encoding) as f:
1524
+ yield f
1525
+
1526
+ f.flush()
1527
+ os.fsync(f.fileno())
1528
+
1529
+
1530
+ def _is_kaggle() -> bool:
1531
+ return (
1532
+ os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None
1533
+ or "kaggle_environments" in sys.modules
1534
+ )
1535
+
1536
+
1537
+ def _is_likely_kaggle() -> bool:
1538
+ # Telemetry to mark first runs from Kagglers.
1539
+ return (
1540
+ _is_kaggle()
1541
+ or os.path.exists(
1542
+ os.path.expanduser(os.path.join("~", ".kaggle", "kaggle.json"))
1543
+ )
1544
+ or "kaggle" in sys.modules
1545
+ )
1546
+
1547
+
1548
+ def _is_databricks() -> bool:
1549
+ # check if we are running inside a databricks notebook by
1550
+ # inspecting sys.modules, searching for dbutils and verifying that
1551
+ # it has the appropriate structure
1552
+
1553
+ if "dbutils" in sys.modules:
1554
+ dbutils = sys.modules["dbutils"]
1555
+ if hasattr(dbutils, "shell"):
1556
+ shell = dbutils.shell
1557
+ if hasattr(shell, "sc"):
1558
+ sc = shell.sc
1559
+ if hasattr(sc, "appName"):
1560
+ return bool(sc.appName == "Databricks Shell")
1561
+ return False
1562
+
1563
+
1564
+ def _is_py_or_dockerfile(path: str) -> bool:
1565
+ file = os.path.basename(path)
1566
+ return file.endswith(".py") or file.startswith("Dockerfile")
1567
+
1568
+
1569
+ def check_windows_valid_filename(path: Union[int, str]) -> bool:
1570
+ return not bool(re.search(RE_WINFNAMES, path)) # type: ignore
1571
+
1572
+
1573
+ def artifact_to_json(artifact: "Artifact") -> Dict[str, Any]:
1574
+ return {
1575
+ "_type": "artifactVersion",
1576
+ "_version": "v0",
1577
+ "id": artifact.id,
1578
+ "version": artifact.source_version,
1579
+ "sequenceName": artifact.source_name.split(":")[0],
1580
+ "usedAs": artifact.use_as,
1581
+ }
1582
+
1583
+
1584
+ def check_dict_contains_nested_artifact(d: dict, nested: bool = False) -> bool:
1585
+ for item in d.values():
1586
+ if isinstance(item, dict):
1587
+ contains_artifacts = check_dict_contains_nested_artifact(item, True)
1588
+ if contains_artifacts:
1589
+ return True
1590
+ elif (isinstance(item, wandb.Artifact) or _is_artifact_string(item)) and nested:
1591
+ return True
1592
+ return False
1593
+
1594
+
1595
+ def load_json_yaml_dict(config: str) -> Any:
1596
+ ext = os.path.splitext(config)[-1]
1597
+ if ext == ".json":
1598
+ with open(config) as f:
1599
+ return json.load(f)
1600
+ elif ext == ".yaml":
1601
+ with open(config) as f:
1602
+ return yaml.safe_load(f)
1603
+ else:
1604
+ try:
1605
+ return json.loads(config)
1606
+ except ValueError:
1607
+ return None
1608
+
1609
+
1610
+ def _parse_entity_project_item(path: str) -> tuple:
1611
+ """Parse paths with the following formats: {item}, {project}/{item}, & {entity}/{project}/{item}.
1612
+
1613
+ Args:
1614
+ path: `str`, input path; must be between 0 and 3 in length.
1615
+
1616
+ Returns:
1617
+ tuple of length 3 - (item, project, entity)
1618
+
1619
+ Example:
1620
+ alias, project, entity = _parse_entity_project_item("myproj/mymodel:best")
1621
+
1622
+ assert entity == ""
1623
+ assert project == "myproj"
1624
+ assert alias == "mymodel:best"
1625
+
1626
+ """
1627
+ words = path.split("/")
1628
+ if len(words) > 3:
1629
+ raise ValueError(
1630
+ "Invalid path: must be str the form {item}, {project}/{item}, or {entity}/{project}/{item}"
1631
+ )
1632
+ padded_words = [""] * (3 - len(words)) + words
1633
+ return tuple(reversed(padded_words))
1634
+
1635
+
1636
+ def _resolve_aliases(aliases: Optional[Union[str, Iterable[str]]]) -> List[str]:
1637
+ """Add the 'latest' alias and ensure that all aliases are unique.
1638
+
1639
+ Takes in `aliases` which can be None, str, or List[str] and returns List[str].
1640
+ Ensures that "latest" is always present in the returned list.
1641
+
1642
+ Args:
1643
+ aliases: `Optional[Union[str, List[str]]]`
1644
+
1645
+ Returns:
1646
+ List[str], with "latest" always present.
1647
+
1648
+ Usage:
1649
+
1650
+ ```python
1651
+ aliases = _resolve_aliases(["best", "dev"])
1652
+ assert aliases == ["best", "dev", "latest"]
1653
+
1654
+ aliases = _resolve_aliases("boom")
1655
+ assert aliases == ["boom", "latest"]
1656
+ ```
1657
+ """
1658
+ aliases = aliases or ["latest"]
1659
+
1660
+ if isinstance(aliases, str):
1661
+ aliases = [aliases]
1662
+
1663
+ try:
1664
+ return list(set(aliases) | {"latest"})
1665
+ except TypeError as exc:
1666
+ raise ValueError("`aliases` must be Iterable or None") from exc
1667
+
1668
+
1669
+ def _is_artifact_object(v: Any) -> bool:
1670
+ return isinstance(v, wandb.Artifact)
1671
+
1672
+
1673
+ def _is_artifact_string(v: Any) -> bool:
1674
+ return isinstance(v, str) and v.startswith("wandb-artifact://")
1675
+
1676
+
1677
+ def _is_artifact_version_weave_dict(v: Any) -> bool:
1678
+ return isinstance(v, dict) and v.get("_type") == "artifactVersion"
1679
+
1680
+
1681
+ def _is_artifact_representation(v: Any) -> bool:
1682
+ return (
1683
+ _is_artifact_object(v)
1684
+ or _is_artifact_string(v)
1685
+ or _is_artifact_version_weave_dict(v)
1686
+ )
1687
+
1688
+
1689
+ def parse_artifact_string(v: str) -> Tuple[str, Optional[str], bool]:
1690
+ if not v.startswith("wandb-artifact://"):
1691
+ raise ValueError(f"Invalid artifact string: {v}")
1692
+ parsed_v = v[len("wandb-artifact://") :]
1693
+ base_uri = None
1694
+ url_info = urllib.parse.urlparse(parsed_v)
1695
+ if url_info.scheme != "":
1696
+ base_uri = f"{url_info.scheme}://{url_info.netloc}"
1697
+ parts = url_info.path.split("/")[1:]
1698
+ else:
1699
+ parts = parsed_v.split("/")
1700
+ if parts[0] == "_id":
1701
+ # for now can't fetch paths but this will be supported in the future
1702
+ # when we allow passing typed media objects, this can be extended
1703
+ # to include paths
1704
+ return parts[1], base_uri, True
1705
+
1706
+ if len(parts) < 3:
1707
+ raise ValueError(f"Invalid artifact string: {v}")
1708
+
1709
+ # for now can't fetch paths but this will be supported in the future
1710
+ # when we allow passing typed media objects, this can be extended
1711
+ # to include paths
1712
+ entity, project, name_and_alias_or_version = parts[:3]
1713
+ return f"{entity}/{project}/{name_and_alias_or_version}", base_uri, False
1714
+
1715
+
1716
+ def _get_max_cli_version() -> Union[str, None]:
1717
+ max_cli_version = wandb.api.max_cli_version()
1718
+ return str(max_cli_version) if max_cli_version is not None else None
1719
+
1720
+
1721
+ def _is_offline() -> bool:
1722
+ return ( # type: ignore[no-any-return]
1723
+ wandb.run is not None and wandb.run.settings._offline
1724
+ ) or wandb.setup().settings._offline # type: ignore
1725
+
1726
+
1727
+ def ensure_text(
1728
+ string: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
1729
+ ) -> str:
1730
+ """Coerce s to str."""
1731
+ if isinstance(string, bytes):
1732
+ return string.decode(encoding, errors)
1733
+ elif isinstance(string, str):
1734
+ return string
1735
+ else:
1736
+ raise TypeError(f"not expecting type {type(string)!r}")
1737
+
1738
+
1739
+ def make_artifact_name_safe(name: str) -> str:
1740
+ """Make an artifact name safe for use in artifacts."""
1741
+ # artifact names may only contain alphanumeric characters, dashes, underscores, and dots.
1742
+ cleaned = re.sub(r"[^a-zA-Z0-9_\-.]", "_", name)
1743
+ if len(cleaned) <= 128:
1744
+ return cleaned
1745
+ # truncate with dots in the middle using regex
1746
+ return re.sub(r"(^.{63}).*(.{63}$)", r"\g<1>..\g<2>", cleaned)
1747
+
1748
+
1749
+ def make_docker_image_name_safe(name: str) -> str:
1750
+ """Make a docker image name safe for use in artifacts."""
1751
+ safe_chars = RE_DOCKER_IMAGE_NAME_CHARS.sub("__", name.lower())
1752
+ deduped = RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub("__", safe_chars)
1753
+ trimmed_start = RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub("", deduped)
1754
+ trimmed = RE_DOCKER_IMAGE_NAME_SEPARATOR_END.sub("", trimmed_start)
1755
+ return trimmed if trimmed else "image"
1756
+
1757
+
1758
+ def merge_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
1759
+ """Recursively merge two dictionaries."""
1760
+ for key, value in source.items():
1761
+ if isinstance(value, dict):
1762
+ # get node or create one
1763
+ node = destination.setdefault(key, {})
1764
+ merge_dicts(value, node)
1765
+ else:
1766
+ if isinstance(value, list):
1767
+ if key in destination:
1768
+ destination[key].extend(value)
1769
+ else:
1770
+ destination[key] = value
1771
+ else:
1772
+ destination[key] = value
1773
+ return destination
1774
+
1775
+
1776
+ def coalesce(*arg: Any) -> Any:
1777
+ """Return the first non-none value in the list of arguments.
1778
+
1779
+ Similar to ?? in C#.
1780
+ """
1781
+ return next((a for a in arg if a is not None), None)
1782
+
1783
+
1784
+ def recursive_cast_dictlike_to_dict(d: Dict[str, Any]) -> Dict[str, Any]:
1785
+ for k, v in d.items():
1786
+ if isinstance(v, dict):
1787
+ recursive_cast_dictlike_to_dict(v)
1788
+ elif hasattr(v, "keys"):
1789
+ d[k] = dict(v)
1790
+ recursive_cast_dictlike_to_dict(d[k])
1791
+ return d
1792
+
1793
+
1794
+ def remove_keys_with_none_values(
1795
+ d: Union[Dict[str, Any], Any],
1796
+ ) -> Union[Dict[str, Any], Any]:
1797
+ # otherwise iterrows will create a bunch of ugly charts
1798
+ if not isinstance(d, dict):
1799
+ return d
1800
+
1801
+ if isinstance(d, dict):
1802
+ new_dict = {}
1803
+ for k, v in d.items():
1804
+ new_v = remove_keys_with_none_values(v)
1805
+ if new_v is not None and not (isinstance(new_v, dict) and len(new_v) == 0):
1806
+ new_dict[k] = new_v
1807
+ return new_dict if new_dict else None
1808
+
1809
+
1810
+ def batched(n: int, iterable: Iterable[T]) -> Generator[List[T], None, None]:
1811
+ i = iter(iterable)
1812
+ batch = list(itertools.islice(i, n))
1813
+ while batch:
1814
+ yield batch
1815
+ batch = list(itertools.islice(i, n))
1816
+
1817
+
1818
+ def random_string(length: int = 12) -> str:
1819
+ """Generate a random string of a given length.
1820
+
1821
+ :param length: Length of the string to generate.
1822
+ :return: Random string.
1823
+ """
1824
+ return "".join(
1825
+ secrets.choice(string.ascii_lowercase + string.digits) for _ in range(length)
1826
+ )
1827
+
1828
+
1829
+ def sample_with_exponential_decay_weights(
1830
+ xs: Union[Iterable, Iterable[Iterable]],
1831
+ ys: Iterable[Iterable],
1832
+ keys: Optional[Iterable] = None,
1833
+ sample_size: int = 1500,
1834
+ ) -> Tuple[List, List, Optional[List]]:
1835
+ """Sample from a list of lists with weights that decay exponentially.
1836
+
1837
+ May be used with the wandb.plot.line_series function.
1838
+ """
1839
+ xs_array = np.array(xs)
1840
+ ys_array = np.array(ys)
1841
+ keys_array = np.array(keys) if keys else None
1842
+ weights = np.exp(-np.arange(len(xs_array)) / len(xs_array))
1843
+ weights /= np.sum(weights)
1844
+ sampled_indices = np.random.choice(len(xs_array), size=sample_size, p=weights)
1845
+ sampled_xs = xs_array[sampled_indices].tolist()
1846
+ sampled_ys = ys_array[sampled_indices].tolist()
1847
+ sampled_keys = keys_array[sampled_indices].tolist() if keys else None
1848
+
1849
+ return sampled_xs, sampled_ys, sampled_keys
1850
+
1851
+
1852
+ @dataclasses.dataclass(frozen=True)
1853
+ class InstalledDistribution:
1854
+ """An installed distribution.
1855
+
1856
+ Attributes:
1857
+ key: The distribution name as it would be imported.
1858
+ version: The distribution's version string.
1859
+ """
1860
+
1861
+ key: str
1862
+ version: str
1863
+
1864
+
1865
+ def working_set() -> Iterable[InstalledDistribution]:
1866
+ """Return the working set of installed distributions.
1867
+
1868
+ Uses importlib.metadata in Python versions above 3.7, and importlib_metadata otherwise.
1869
+ """
1870
+ try:
1871
+ from importlib.metadata import distributions
1872
+ except ImportError:
1873
+ from importlib_metadata import distributions # type: ignore
1874
+
1875
+ for d in distributions():
1876
+ yield InstalledDistribution(key=d.metadata["Name"], version=d.version)
1877
+
1878
+
1879
+ def parse_version(version: str) -> "packaging.version.Version":
1880
+ """Parse a version string into a version object.
1881
+
1882
+ This function is a wrapper around the `packaging.version.parse` function, which
1883
+ is used to parse version strings into version objects. If the `packaging` library
1884
+ is not installed, it falls back to the `pkg_resources` library.
1885
+ """
1886
+ try:
1887
+ from packaging.version import parse as parse_version # type: ignore
1888
+ except ImportError:
1889
+ from pkg_resources import parse_version # type: ignore[assignment]
1890
+
1891
+ return parse_version(version)
1892
+
1893
+
1894
+ def get_core_path() -> str:
1895
+ """Returns the path to the wandb-core binary.
1896
+
1897
+ The path can be set explicitly via the _WANDB_CORE_PATH environment
1898
+ variable. Otherwise, the path to the binary in the current package
1899
+ is returned.
1900
+
1901
+ Returns:
1902
+ str: The path to the wandb-core package.
1903
+
1904
+ Raises:
1905
+ WandbCoreNotAvailableError: If wandb-core was not built for the current system.
1906
+ """
1907
+ # NOTE: Environment variable _WANDB_CORE_PATH is a temporary development feature
1908
+ # to assist in running the core service from a live development directory.
1909
+ path_from_env: str = os.environ.get("_WANDB_CORE_PATH", "")
1910
+ if path_from_env:
1911
+ wandb.termwarn(
1912
+ f"Using wandb-core from path `_WANDB_CORE_PATH={path_from_env}`. "
1913
+ "This is a development feature and may not work as expected."
1914
+ )
1915
+ return path_from_env
1916
+
1917
+ bin_path = pathlib.Path(__file__).parent / "bin" / "wandb-core"
1918
+ if not bin_path.exists():
1919
+ raise WandbCoreNotAvailableError(
1920
+ f"Looks like wandb-core is not compiled for your system ({platform.platform()}):"
1921
+ " Please contact support at support@wandb.com to request `wandb-core`"
1922
+ " support for your system."
1923
+ )
1924
+
1925
+ return str(bin_path)