wandb 0.19.1__py3-none-musllinux_1_2_aarch64.whl

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