wandb 0.21.2__py3-none-macosx_12_0_arm64.whl

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