wandb 0.17.0__py3-none-win32.whl

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