wandb 0.18.0__py3-none-macosx_10_13_x86_64.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 +89 -0
  2. wandb/__init__.py +245 -0
  3. wandb/__init__.pyi +1084 -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 +266 -0
  10. wandb/apis/__init__.py +48 -0
  11. wandb/apis/attrs.py +40 -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 +99 -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 +229 -0
  20. wandb/apis/normalize.py +89 -0
  21. wandb/apis/paginator.py +81 -0
  22. wandb/apis/public/__init__.py +34 -0
  23. wandb/apis/public/api.py +1179 -0
  24. wandb/apis/public/artifacts.py +1086 -0
  25. wandb/apis/public/const.py +4 -0
  26. wandb/apis/public/files.py +195 -0
  27. wandb/apis/public/history.py +149 -0
  28. wandb/apis/public/jobs.py +651 -0
  29. wandb/apis/public/projects.py +154 -0
  30. wandb/apis/public/query_generator.py +166 -0
  31. wandb/apis/public/reports.py +469 -0
  32. wandb/apis/public/runs.py +901 -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/reports/__init__.py +1 -0
  37. wandb/apis/reports/v1/__init__.py +8 -0
  38. wandb/apis/reports/v2/__init__.py +8 -0
  39. wandb/apis/workspaces/__init__.py +8 -0
  40. wandb/beta/workflows.py +288 -0
  41. wandb/bin/wandb-core +0 -0
  42. wandb/cli/__init__.py +0 -0
  43. wandb/cli/cli.py +3009 -0
  44. wandb/data_types.py +2073 -0
  45. wandb/docker/__init__.py +342 -0
  46. wandb/docker/auth.py +436 -0
  47. wandb/docker/wandb-entrypoint.sh +33 -0
  48. wandb/docker/www_authenticate.py +94 -0
  49. wandb/env.py +519 -0
  50. wandb/errors/__init__.py +46 -0
  51. wandb/errors/term.py +103 -0
  52. wandb/errors/util.py +57 -0
  53. wandb/filesync/__init__.py +0 -0
  54. wandb/filesync/dir_watcher.py +403 -0
  55. wandb/filesync/stats.py +100 -0
  56. wandb/filesync/step_checksum.py +142 -0
  57. wandb/filesync/step_prepare.py +179 -0
  58. wandb/filesync/step_upload.py +290 -0
  59. wandb/filesync/upload_job.py +142 -0
  60. wandb/integration/__init__.py +0 -0
  61. wandb/integration/catboost/__init__.py +5 -0
  62. wandb/integration/catboost/catboost.py +178 -0
  63. wandb/integration/cohere/__init__.py +3 -0
  64. wandb/integration/cohere/cohere.py +21 -0
  65. wandb/integration/cohere/resolver.py +347 -0
  66. wandb/integration/diffusers/__init__.py +3 -0
  67. wandb/integration/diffusers/autologger.py +76 -0
  68. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  69. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  70. wandb/integration/diffusers/resolvers/multimodal.py +882 -0
  71. wandb/integration/diffusers/resolvers/utils.py +102 -0
  72. wandb/integration/fastai/__init__.py +249 -0
  73. wandb/integration/gym/__init__.py +105 -0
  74. wandb/integration/huggingface/__init__.py +3 -0
  75. wandb/integration/huggingface/huggingface.py +18 -0
  76. wandb/integration/huggingface/resolver.py +213 -0
  77. wandb/integration/keras/__init__.py +11 -0
  78. wandb/integration/keras/callbacks/__init__.py +5 -0
  79. wandb/integration/keras/callbacks/metrics_logger.py +136 -0
  80. wandb/integration/keras/callbacks/model_checkpoint.py +195 -0
  81. wandb/integration/keras/callbacks/tables_builder.py +226 -0
  82. wandb/integration/keras/keras.py +1091 -0
  83. wandb/integration/kfp/__init__.py +6 -0
  84. wandb/integration/kfp/helpers.py +28 -0
  85. wandb/integration/kfp/kfp_patch.py +324 -0
  86. wandb/integration/kfp/wandb_logging.py +182 -0
  87. wandb/integration/langchain/__init__.py +3 -0
  88. wandb/integration/langchain/wandb_tracer.py +48 -0
  89. wandb/integration/lightgbm/__init__.py +239 -0
  90. wandb/integration/lightning/__init__.py +0 -0
  91. wandb/integration/lightning/fabric/__init__.py +3 -0
  92. wandb/integration/lightning/fabric/logger.py +762 -0
  93. wandb/integration/magic.py +556 -0
  94. wandb/integration/metaflow/__init__.py +3 -0
  95. wandb/integration/metaflow/metaflow.py +383 -0
  96. wandb/integration/openai/__init__.py +3 -0
  97. wandb/integration/openai/fine_tuning.py +480 -0
  98. wandb/integration/openai/openai.py +22 -0
  99. wandb/integration/openai/resolver.py +240 -0
  100. wandb/integration/prodigy/__init__.py +3 -0
  101. wandb/integration/prodigy/prodigy.py +299 -0
  102. wandb/integration/sacred/__init__.py +117 -0
  103. wandb/integration/sagemaker/__init__.py +12 -0
  104. wandb/integration/sagemaker/auth.py +28 -0
  105. wandb/integration/sagemaker/config.py +49 -0
  106. wandb/integration/sagemaker/files.py +3 -0
  107. wandb/integration/sagemaker/resources.py +34 -0
  108. wandb/integration/sb3/__init__.py +3 -0
  109. wandb/integration/sb3/sb3.py +153 -0
  110. wandb/integration/tensorboard/__init__.py +10 -0
  111. wandb/integration/tensorboard/log.py +355 -0
  112. wandb/integration/tensorboard/monkeypatch.py +185 -0
  113. wandb/integration/tensorflow/__init__.py +5 -0
  114. wandb/integration/tensorflow/estimator_hook.py +54 -0
  115. wandb/integration/torch/__init__.py +0 -0
  116. wandb/integration/ultralytics/__init__.py +11 -0
  117. wandb/integration/ultralytics/bbox_utils.py +208 -0
  118. wandb/integration/ultralytics/callback.py +524 -0
  119. wandb/integration/ultralytics/classification_utils.py +83 -0
  120. wandb/integration/ultralytics/mask_utils.py +202 -0
  121. wandb/integration/ultralytics/pose_utils.py +103 -0
  122. wandb/integration/xgboost/__init__.py +11 -0
  123. wandb/integration/xgboost/xgboost.py +189 -0
  124. wandb/integration/yolov8/__init__.py +0 -0
  125. wandb/integration/yolov8/yolov8.py +284 -0
  126. wandb/jupyter.py +515 -0
  127. wandb/magic.py +3 -0
  128. wandb/mpmain/__init__.py +0 -0
  129. wandb/mpmain/__main__.py +1 -0
  130. wandb/old/__init__.py +0 -0
  131. wandb/old/core.py +131 -0
  132. wandb/old/settings.py +173 -0
  133. wandb/old/summary.py +440 -0
  134. wandb/plot/__init__.py +19 -0
  135. wandb/plot/bar.py +42 -0
  136. wandb/plot/confusion_matrix.py +99 -0
  137. wandb/plot/histogram.py +36 -0
  138. wandb/plot/line.py +40 -0
  139. wandb/plot/line_series.py +88 -0
  140. wandb/plot/pr_curve.py +136 -0
  141. wandb/plot/roc_curve.py +118 -0
  142. wandb/plot/scatter.py +32 -0
  143. wandb/plot/utils.py +183 -0
  144. wandb/proto/__init__.py +0 -0
  145. wandb/proto/v3/__init__.py +0 -0
  146. wandb/proto/v3/wandb_base_pb2.py +54 -0
  147. wandb/proto/v3/wandb_internal_pb2.py +1607 -0
  148. wandb/proto/v3/wandb_server_pb2.py +207 -0
  149. wandb/proto/v3/wandb_settings_pb2.py +111 -0
  150. wandb/proto/v3/wandb_telemetry_pb2.py +105 -0
  151. wandb/proto/v4/__init__.py +0 -0
  152. wandb/proto/v4/wandb_base_pb2.py +29 -0
  153. wandb/proto/v4/wandb_internal_pb2.py +359 -0
  154. wandb/proto/v4/wandb_server_pb2.py +62 -0
  155. wandb/proto/v4/wandb_settings_pb2.py +44 -0
  156. wandb/proto/v4/wandb_telemetry_pb2.py +40 -0
  157. wandb/proto/v5/wandb_base_pb2.py +30 -0
  158. wandb/proto/v5/wandb_internal_pb2.py +360 -0
  159. wandb/proto/v5/wandb_server_pb2.py +63 -0
  160. wandb/proto/v5/wandb_settings_pb2.py +45 -0
  161. wandb/proto/v5/wandb_telemetry_pb2.py +41 -0
  162. wandb/proto/wandb_base_pb2.py +10 -0
  163. wandb/proto/wandb_deprecated.py +53 -0
  164. wandb/proto/wandb_generate_deprecated.py +34 -0
  165. wandb/proto/wandb_generate_proto.py +49 -0
  166. wandb/proto/wandb_internal_pb2.py +16 -0
  167. wandb/proto/wandb_server_pb2.py +10 -0
  168. wandb/proto/wandb_settings_pb2.py +10 -0
  169. wandb/proto/wandb_telemetry_pb2.py +10 -0
  170. wandb/py.typed +0 -0
  171. wandb/sdk/__init__.py +37 -0
  172. wandb/sdk/artifacts/__init__.py +0 -0
  173. wandb/sdk/artifacts/_validators.py +45 -0
  174. wandb/sdk/artifacts/artifact.py +2415 -0
  175. wandb/sdk/artifacts/artifact_download_logger.py +43 -0
  176. wandb/sdk/artifacts/artifact_file_cache.py +251 -0
  177. wandb/sdk/artifacts/artifact_instance_cache.py +15 -0
  178. wandb/sdk/artifacts/artifact_manifest.py +72 -0
  179. wandb/sdk/artifacts/artifact_manifest_entry.py +247 -0
  180. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  181. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +90 -0
  182. wandb/sdk/artifacts/artifact_saver.py +267 -0
  183. wandb/sdk/artifacts/artifact_state.py +11 -0
  184. wandb/sdk/artifacts/artifact_ttl.py +7 -0
  185. wandb/sdk/artifacts/exceptions.py +56 -0
  186. wandb/sdk/artifacts/staging.py +25 -0
  187. wandb/sdk/artifacts/storage_handler.py +60 -0
  188. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  189. wandb/sdk/artifacts/storage_handlers/azure_handler.py +206 -0
  190. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +226 -0
  191. wandb/sdk/artifacts/storage_handlers/http_handler.py +113 -0
  192. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +139 -0
  193. wandb/sdk/artifacts/storage_handlers/multi_handler.py +54 -0
  194. wandb/sdk/artifacts/storage_handlers/s3_handler.py +300 -0
  195. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +70 -0
  196. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +133 -0
  197. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +72 -0
  198. wandb/sdk/artifacts/storage_layout.py +6 -0
  199. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  200. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  201. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +376 -0
  202. wandb/sdk/artifacts/storage_policy.py +72 -0
  203. wandb/sdk/backend/__init__.py +0 -0
  204. wandb/sdk/backend/backend.py +240 -0
  205. wandb/sdk/data_types/__init__.py +0 -0
  206. wandb/sdk/data_types/_dtypes.py +914 -0
  207. wandb/sdk/data_types/_private.py +10 -0
  208. wandb/sdk/data_types/base_types/__init__.py +0 -0
  209. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  210. wandb/sdk/data_types/base_types/media.py +315 -0
  211. wandb/sdk/data_types/base_types/wb_value.py +274 -0
  212. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  213. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +295 -0
  214. wandb/sdk/data_types/helper_types/classes.py +159 -0
  215. wandb/sdk/data_types/helper_types/image_mask.py +235 -0
  216. wandb/sdk/data_types/histogram.py +96 -0
  217. wandb/sdk/data_types/html.py +115 -0
  218. wandb/sdk/data_types/image.py +689 -0
  219. wandb/sdk/data_types/molecule.py +241 -0
  220. wandb/sdk/data_types/object_3d.py +474 -0
  221. wandb/sdk/data_types/plotly.py +82 -0
  222. wandb/sdk/data_types/saved_model.py +446 -0
  223. wandb/sdk/data_types/trace_tree.py +438 -0
  224. wandb/sdk/data_types/utils.py +180 -0
  225. wandb/sdk/data_types/video.py +247 -0
  226. wandb/sdk/integration_utils/__init__.py +0 -0
  227. wandb/sdk/integration_utils/auto_logging.py +239 -0
  228. wandb/sdk/integration_utils/data_logging.py +475 -0
  229. wandb/sdk/interface/__init__.py +0 -0
  230. wandb/sdk/interface/constants.py +4 -0
  231. wandb/sdk/interface/interface.py +996 -0
  232. wandb/sdk/interface/interface_queue.py +59 -0
  233. wandb/sdk/interface/interface_relay.py +53 -0
  234. wandb/sdk/interface/interface_shared.py +549 -0
  235. wandb/sdk/interface/interface_sock.py +61 -0
  236. wandb/sdk/interface/message_future.py +27 -0
  237. wandb/sdk/interface/message_future_poll.py +50 -0
  238. wandb/sdk/interface/router.py +118 -0
  239. wandb/sdk/interface/router_queue.py +44 -0
  240. wandb/sdk/interface/router_relay.py +39 -0
  241. wandb/sdk/interface/router_sock.py +36 -0
  242. wandb/sdk/interface/summary_record.py +67 -0
  243. wandb/sdk/internal/__init__.py +0 -0
  244. wandb/sdk/internal/context.py +89 -0
  245. wandb/sdk/internal/datastore.py +297 -0
  246. wandb/sdk/internal/file_pusher.py +181 -0
  247. wandb/sdk/internal/file_stream.py +695 -0
  248. wandb/sdk/internal/flow_control.py +263 -0
  249. wandb/sdk/internal/handler.py +911 -0
  250. wandb/sdk/internal/internal.py +417 -0
  251. wandb/sdk/internal/internal_api.py +4287 -0
  252. wandb/sdk/internal/internal_util.py +100 -0
  253. wandb/sdk/internal/job_builder.py +629 -0
  254. wandb/sdk/internal/profiler.py +78 -0
  255. wandb/sdk/internal/progress.py +83 -0
  256. wandb/sdk/internal/run.py +25 -0
  257. wandb/sdk/internal/sample.py +70 -0
  258. wandb/sdk/internal/sender.py +1729 -0
  259. wandb/sdk/internal/sender_config.py +197 -0
  260. wandb/sdk/internal/settings_static.py +90 -0
  261. wandb/sdk/internal/system/__init__.py +0 -0
  262. wandb/sdk/internal/system/assets/__init__.py +27 -0
  263. wandb/sdk/internal/system/assets/aggregators.py +37 -0
  264. wandb/sdk/internal/system/assets/asset_registry.py +20 -0
  265. wandb/sdk/internal/system/assets/cpu.py +163 -0
  266. wandb/sdk/internal/system/assets/disk.py +210 -0
  267. wandb/sdk/internal/system/assets/gpu.py +416 -0
  268. wandb/sdk/internal/system/assets/gpu_amd.py +239 -0
  269. wandb/sdk/internal/system/assets/gpu_apple.py +177 -0
  270. wandb/sdk/internal/system/assets/interfaces.py +207 -0
  271. wandb/sdk/internal/system/assets/ipu.py +177 -0
  272. wandb/sdk/internal/system/assets/memory.py +166 -0
  273. wandb/sdk/internal/system/assets/network.py +125 -0
  274. wandb/sdk/internal/system/assets/open_metrics.py +299 -0
  275. wandb/sdk/internal/system/assets/tpu.py +154 -0
  276. wandb/sdk/internal/system/assets/trainium.py +399 -0
  277. wandb/sdk/internal/system/env_probe_helpers.py +13 -0
  278. wandb/sdk/internal/system/system_info.py +249 -0
  279. wandb/sdk/internal/system/system_monitor.py +229 -0
  280. wandb/sdk/internal/tb_watcher.py +518 -0
  281. wandb/sdk/internal/thread_local_settings.py +18 -0
  282. wandb/sdk/internal/update.py +113 -0
  283. wandb/sdk/internal/writer.py +206 -0
  284. wandb/sdk/launch/__init__.py +14 -0
  285. wandb/sdk/launch/_launch.py +330 -0
  286. wandb/sdk/launch/_launch_add.py +255 -0
  287. wandb/sdk/launch/_project_spec.py +566 -0
  288. wandb/sdk/launch/agent/__init__.py +5 -0
  289. wandb/sdk/launch/agent/agent.py +924 -0
  290. wandb/sdk/launch/agent/config.py +296 -0
  291. wandb/sdk/launch/agent/job_status_tracker.py +53 -0
  292. wandb/sdk/launch/agent/run_queue_item_file_saver.py +45 -0
  293. wandb/sdk/launch/builder/__init__.py +0 -0
  294. wandb/sdk/launch/builder/abstract.py +156 -0
  295. wandb/sdk/launch/builder/build.py +297 -0
  296. wandb/sdk/launch/builder/context_manager.py +235 -0
  297. wandb/sdk/launch/builder/docker_builder.py +177 -0
  298. wandb/sdk/launch/builder/kaniko_builder.py +595 -0
  299. wandb/sdk/launch/builder/noop.py +58 -0
  300. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +188 -0
  301. wandb/sdk/launch/builder/templates/dockerfile.py +92 -0
  302. wandb/sdk/launch/create_job.py +528 -0
  303. wandb/sdk/launch/environment/abstract.py +29 -0
  304. wandb/sdk/launch/environment/aws_environment.py +322 -0
  305. wandb/sdk/launch/environment/azure_environment.py +105 -0
  306. wandb/sdk/launch/environment/gcp_environment.py +335 -0
  307. wandb/sdk/launch/environment/local_environment.py +66 -0
  308. wandb/sdk/launch/errors.py +19 -0
  309. wandb/sdk/launch/git_reference.py +109 -0
  310. wandb/sdk/launch/inputs/files.py +148 -0
  311. wandb/sdk/launch/inputs/internal.py +315 -0
  312. wandb/sdk/launch/inputs/manage.py +113 -0
  313. wandb/sdk/launch/inputs/schema.py +39 -0
  314. wandb/sdk/launch/loader.py +249 -0
  315. wandb/sdk/launch/registry/abstract.py +48 -0
  316. wandb/sdk/launch/registry/anon.py +29 -0
  317. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  318. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  319. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  320. wandb/sdk/launch/registry/local_registry.py +67 -0
  321. wandb/sdk/launch/runner/__init__.py +0 -0
  322. wandb/sdk/launch/runner/abstract.py +195 -0
  323. wandb/sdk/launch/runner/kubernetes_monitor.py +474 -0
  324. wandb/sdk/launch/runner/kubernetes_runner.py +963 -0
  325. wandb/sdk/launch/runner/local_container.py +301 -0
  326. wandb/sdk/launch/runner/local_process.py +78 -0
  327. wandb/sdk/launch/runner/sagemaker_runner.py +426 -0
  328. wandb/sdk/launch/runner/vertex_runner.py +230 -0
  329. wandb/sdk/launch/sweeps/__init__.py +39 -0
  330. wandb/sdk/launch/sweeps/scheduler.py +742 -0
  331. wandb/sdk/launch/sweeps/scheduler_sweep.py +91 -0
  332. wandb/sdk/launch/sweeps/utils.py +316 -0
  333. wandb/sdk/launch/utils.py +746 -0
  334. wandb/sdk/launch/wandb_reference.py +138 -0
  335. wandb/sdk/lib/__init__.py +5 -0
  336. wandb/sdk/lib/_settings_toposort_generate.py +159 -0
  337. wandb/sdk/lib/_settings_toposort_generated.py +249 -0
  338. wandb/sdk/lib/_wburls_generate.py +25 -0
  339. wandb/sdk/lib/_wburls_generated.py +22 -0
  340. wandb/sdk/lib/apikey.py +273 -0
  341. wandb/sdk/lib/capped_dict.py +26 -0
  342. wandb/sdk/lib/config_util.py +101 -0
  343. wandb/sdk/lib/console.py +39 -0
  344. wandb/sdk/lib/credentials.py +141 -0
  345. wandb/sdk/lib/deprecate.py +42 -0
  346. wandb/sdk/lib/disabled.py +29 -0
  347. wandb/sdk/lib/exit_hooks.py +54 -0
  348. wandb/sdk/lib/file_stream_utils.py +118 -0
  349. wandb/sdk/lib/filenames.py +64 -0
  350. wandb/sdk/lib/filesystem.py +372 -0
  351. wandb/sdk/lib/fsm.py +174 -0
  352. wandb/sdk/lib/gitlib.py +239 -0
  353. wandb/sdk/lib/gql_request.py +65 -0
  354. wandb/sdk/lib/handler_util.py +21 -0
  355. wandb/sdk/lib/hashutil.py +62 -0
  356. wandb/sdk/lib/import_hooks.py +275 -0
  357. wandb/sdk/lib/ipython.py +146 -0
  358. wandb/sdk/lib/json_util.py +80 -0
  359. wandb/sdk/lib/lazyloader.py +63 -0
  360. wandb/sdk/lib/mailbox.py +460 -0
  361. wandb/sdk/lib/module.py +69 -0
  362. wandb/sdk/lib/paths.py +106 -0
  363. wandb/sdk/lib/preinit.py +42 -0
  364. wandb/sdk/lib/printer.py +313 -0
  365. wandb/sdk/lib/proto_util.py +90 -0
  366. wandb/sdk/lib/redirect.py +845 -0
  367. wandb/sdk/lib/reporting.py +99 -0
  368. wandb/sdk/lib/retry.py +289 -0
  369. wandb/sdk/lib/run_moment.py +78 -0
  370. wandb/sdk/lib/runid.py +12 -0
  371. wandb/sdk/lib/server.py +52 -0
  372. wandb/sdk/lib/sock_client.py +291 -0
  373. wandb/sdk/lib/sparkline.py +45 -0
  374. wandb/sdk/lib/telemetry.py +100 -0
  375. wandb/sdk/lib/timed_input.py +133 -0
  376. wandb/sdk/lib/timer.py +19 -0
  377. wandb/sdk/lib/tracelog.py +255 -0
  378. wandb/sdk/lib/viz.py +123 -0
  379. wandb/sdk/lib/wburls.py +46 -0
  380. wandb/sdk/service/__init__.py +0 -0
  381. wandb/sdk/service/_startup_debug.py +22 -0
  382. wandb/sdk/service/port_file.py +53 -0
  383. wandb/sdk/service/server.py +119 -0
  384. wandb/sdk/service/server_sock.py +276 -0
  385. wandb/sdk/service/service.py +271 -0
  386. wandb/sdk/service/service_base.py +50 -0
  387. wandb/sdk/service/service_sock.py +70 -0
  388. wandb/sdk/service/streams.py +424 -0
  389. wandb/sdk/verify/__init__.py +0 -0
  390. wandb/sdk/verify/verify.py +501 -0
  391. wandb/sdk/wandb_alerts.py +12 -0
  392. wandb/sdk/wandb_config.py +322 -0
  393. wandb/sdk/wandb_helper.py +54 -0
  394. wandb/sdk/wandb_init.py +1249 -0
  395. wandb/sdk/wandb_login.py +349 -0
  396. wandb/sdk/wandb_manager.py +232 -0
  397. wandb/sdk/wandb_metric.py +110 -0
  398. wandb/sdk/wandb_require.py +97 -0
  399. wandb/sdk/wandb_require_helpers.py +44 -0
  400. wandb/sdk/wandb_run.py +4377 -0
  401. wandb/sdk/wandb_settings.py +1999 -0
  402. wandb/sdk/wandb_setup.py +400 -0
  403. wandb/sdk/wandb_summary.py +150 -0
  404. wandb/sdk/wandb_sweep.py +119 -0
  405. wandb/sdk/wandb_sync.py +75 -0
  406. wandb/sdk/wandb_watch.py +128 -0
  407. wandb/sklearn/__init__.py +37 -0
  408. wandb/sklearn/calculate/__init__.py +32 -0
  409. wandb/sklearn/calculate/calibration_curves.py +125 -0
  410. wandb/sklearn/calculate/class_proportions.py +68 -0
  411. wandb/sklearn/calculate/confusion_matrix.py +92 -0
  412. wandb/sklearn/calculate/decision_boundaries.py +40 -0
  413. wandb/sklearn/calculate/elbow_curve.py +55 -0
  414. wandb/sklearn/calculate/feature_importances.py +67 -0
  415. wandb/sklearn/calculate/learning_curve.py +64 -0
  416. wandb/sklearn/calculate/outlier_candidates.py +69 -0
  417. wandb/sklearn/calculate/residuals.py +86 -0
  418. wandb/sklearn/calculate/silhouette.py +118 -0
  419. wandb/sklearn/calculate/summary_metrics.py +62 -0
  420. wandb/sklearn/plot/__init__.py +35 -0
  421. wandb/sklearn/plot/classifier.py +329 -0
  422. wandb/sklearn/plot/clusterer.py +142 -0
  423. wandb/sklearn/plot/regressor.py +121 -0
  424. wandb/sklearn/plot/shared.py +91 -0
  425. wandb/sklearn/utils.py +183 -0
  426. wandb/sync/__init__.py +3 -0
  427. wandb/sync/sync.py +443 -0
  428. wandb/trigger.py +29 -0
  429. wandb/util.py +1945 -0
  430. wandb/vendor/__init__.py +0 -0
  431. wandb/vendor/gql-0.2.0/setup.py +40 -0
  432. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  433. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  434. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  435. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  436. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  437. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  438. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  439. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  440. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  441. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  442. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  443. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  444. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  445. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  446. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  447. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  448. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  449. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  450. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  451. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  452. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  453. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  454. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  455. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  456. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  457. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  458. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  459. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  460. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  461. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  462. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  463. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  464. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  465. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  466. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  467. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  468. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  469. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  470. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  471. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  472. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  473. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  474. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  475. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  476. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  477. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  478. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  479. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  480. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  481. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  482. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  483. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  484. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  485. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  486. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  487. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  488. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  489. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  490. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  491. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  492. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  493. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  494. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  495. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  496. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  497. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  498. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  499. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  500. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  501. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  502. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  503. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  504. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  505. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  506. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  507. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  508. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  509. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  510. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  511. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  512. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  513. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  514. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  515. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  516. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  517. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  518. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  519. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  520. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  521. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  522. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  523. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  524. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  525. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  526. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  527. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  528. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  529. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  530. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  531. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  532. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  533. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  534. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  535. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  549. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  550. wandb/vendor/promise-2.3.0/setup.py +64 -0
  551. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  552. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  553. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  554. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  555. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  556. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  557. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  558. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  559. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  560. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  561. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  562. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  563. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  564. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  565. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  566. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  567. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  568. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  569. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  570. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  571. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  572. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  573. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  574. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  575. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  576. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  577. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  578. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  579. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  580. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  581. wandb/vendor/pygments/__init__.py +90 -0
  582. wandb/vendor/pygments/cmdline.py +568 -0
  583. wandb/vendor/pygments/console.py +74 -0
  584. wandb/vendor/pygments/filter.py +74 -0
  585. wandb/vendor/pygments/filters/__init__.py +350 -0
  586. wandb/vendor/pygments/formatter.py +95 -0
  587. wandb/vendor/pygments/formatters/__init__.py +153 -0
  588. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  589. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  590. wandb/vendor/pygments/formatters/html.py +851 -0
  591. wandb/vendor/pygments/formatters/img.py +600 -0
  592. wandb/vendor/pygments/formatters/irc.py +182 -0
  593. wandb/vendor/pygments/formatters/latex.py +482 -0
  594. wandb/vendor/pygments/formatters/other.py +160 -0
  595. wandb/vendor/pygments/formatters/rtf.py +147 -0
  596. wandb/vendor/pygments/formatters/svg.py +153 -0
  597. wandb/vendor/pygments/formatters/terminal.py +136 -0
  598. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  599. wandb/vendor/pygments/lexer.py +871 -0
  600. wandb/vendor/pygments/lexers/__init__.py +329 -0
  601. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  602. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  603. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  604. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  605. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  606. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  607. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  608. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  609. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  610. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  611. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  612. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  613. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  614. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  615. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  616. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  617. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  618. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  619. wandb/vendor/pygments/lexers/agile.py +24 -0
  620. wandb/vendor/pygments/lexers/algebra.py +221 -0
  621. wandb/vendor/pygments/lexers/ambient.py +76 -0
  622. wandb/vendor/pygments/lexers/ampl.py +87 -0
  623. wandb/vendor/pygments/lexers/apl.py +101 -0
  624. wandb/vendor/pygments/lexers/archetype.py +318 -0
  625. wandb/vendor/pygments/lexers/asm.py +641 -0
  626. wandb/vendor/pygments/lexers/automation.py +374 -0
  627. wandb/vendor/pygments/lexers/basic.py +500 -0
  628. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  629. wandb/vendor/pygments/lexers/business.py +612 -0
  630. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  631. wandb/vendor/pygments/lexers/c_like.py +541 -0
  632. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  633. wandb/vendor/pygments/lexers/chapel.py +102 -0
  634. wandb/vendor/pygments/lexers/clean.py +288 -0
  635. wandb/vendor/pygments/lexers/compiled.py +34 -0
  636. wandb/vendor/pygments/lexers/configs.py +833 -0
  637. wandb/vendor/pygments/lexers/console.py +114 -0
  638. wandb/vendor/pygments/lexers/crystal.py +393 -0
  639. wandb/vendor/pygments/lexers/csound.py +366 -0
  640. wandb/vendor/pygments/lexers/css.py +689 -0
  641. wandb/vendor/pygments/lexers/d.py +251 -0
  642. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  643. wandb/vendor/pygments/lexers/data.py +555 -0
  644. wandb/vendor/pygments/lexers/diff.py +165 -0
  645. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  646. wandb/vendor/pygments/lexers/dsls.py +878 -0
  647. wandb/vendor/pygments/lexers/dylan.py +289 -0
  648. wandb/vendor/pygments/lexers/ecl.py +125 -0
  649. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  650. wandb/vendor/pygments/lexers/elm.py +121 -0
  651. wandb/vendor/pygments/lexers/erlang.py +533 -0
  652. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  653. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  654. wandb/vendor/pygments/lexers/factor.py +344 -0
  655. wandb/vendor/pygments/lexers/fantom.py +250 -0
  656. wandb/vendor/pygments/lexers/felix.py +273 -0
  657. wandb/vendor/pygments/lexers/forth.py +177 -0
  658. wandb/vendor/pygments/lexers/fortran.py +205 -0
  659. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  660. wandb/vendor/pygments/lexers/functional.py +21 -0
  661. wandb/vendor/pygments/lexers/go.py +101 -0
  662. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  663. wandb/vendor/pygments/lexers/graph.py +80 -0
  664. wandb/vendor/pygments/lexers/graphics.py +553 -0
  665. wandb/vendor/pygments/lexers/haskell.py +843 -0
  666. wandb/vendor/pygments/lexers/haxe.py +936 -0
  667. wandb/vendor/pygments/lexers/hdl.py +382 -0
  668. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  669. wandb/vendor/pygments/lexers/html.py +602 -0
  670. wandb/vendor/pygments/lexers/idl.py +270 -0
  671. wandb/vendor/pygments/lexers/igor.py +288 -0
  672. wandb/vendor/pygments/lexers/inferno.py +96 -0
  673. wandb/vendor/pygments/lexers/installers.py +322 -0
  674. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  675. wandb/vendor/pygments/lexers/iolang.py +63 -0
  676. wandb/vendor/pygments/lexers/j.py +146 -0
  677. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  678. wandb/vendor/pygments/lexers/julia.py +333 -0
  679. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  680. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  681. wandb/vendor/pygments/lexers/make.py +202 -0
  682. wandb/vendor/pygments/lexers/markup.py +595 -0
  683. wandb/vendor/pygments/lexers/math.py +21 -0
  684. wandb/vendor/pygments/lexers/matlab.py +663 -0
  685. wandb/vendor/pygments/lexers/ml.py +769 -0
  686. wandb/vendor/pygments/lexers/modeling.py +358 -0
  687. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  688. wandb/vendor/pygments/lexers/monte.py +204 -0
  689. wandb/vendor/pygments/lexers/ncl.py +894 -0
  690. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  691. wandb/vendor/pygments/lexers/nit.py +64 -0
  692. wandb/vendor/pygments/lexers/nix.py +136 -0
  693. wandb/vendor/pygments/lexers/oberon.py +105 -0
  694. wandb/vendor/pygments/lexers/objective.py +504 -0
  695. wandb/vendor/pygments/lexers/ooc.py +85 -0
  696. wandb/vendor/pygments/lexers/other.py +41 -0
  697. wandb/vendor/pygments/lexers/parasail.py +79 -0
  698. wandb/vendor/pygments/lexers/parsers.py +835 -0
  699. wandb/vendor/pygments/lexers/pascal.py +644 -0
  700. wandb/vendor/pygments/lexers/pawn.py +199 -0
  701. wandb/vendor/pygments/lexers/perl.py +620 -0
  702. wandb/vendor/pygments/lexers/php.py +267 -0
  703. wandb/vendor/pygments/lexers/praat.py +294 -0
  704. wandb/vendor/pygments/lexers/prolog.py +306 -0
  705. wandb/vendor/pygments/lexers/python.py +939 -0
  706. wandb/vendor/pygments/lexers/qvt.py +152 -0
  707. wandb/vendor/pygments/lexers/r.py +453 -0
  708. wandb/vendor/pygments/lexers/rdf.py +270 -0
  709. wandb/vendor/pygments/lexers/rebol.py +431 -0
  710. wandb/vendor/pygments/lexers/resource.py +85 -0
  711. wandb/vendor/pygments/lexers/rnc.py +67 -0
  712. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  713. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  714. wandb/vendor/pygments/lexers/ruby.py +519 -0
  715. wandb/vendor/pygments/lexers/rust.py +220 -0
  716. wandb/vendor/pygments/lexers/sas.py +228 -0
  717. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  718. wandb/vendor/pygments/lexers/shell.py +794 -0
  719. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  720. wandb/vendor/pygments/lexers/smv.py +79 -0
  721. wandb/vendor/pygments/lexers/snobol.py +83 -0
  722. wandb/vendor/pygments/lexers/special.py +103 -0
  723. wandb/vendor/pygments/lexers/sql.py +681 -0
  724. wandb/vendor/pygments/lexers/stata.py +108 -0
  725. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  726. wandb/vendor/pygments/lexers/tcl.py +145 -0
  727. wandb/vendor/pygments/lexers/templates.py +2283 -0
  728. wandb/vendor/pygments/lexers/testing.py +207 -0
  729. wandb/vendor/pygments/lexers/text.py +25 -0
  730. wandb/vendor/pygments/lexers/textedit.py +169 -0
  731. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  732. wandb/vendor/pygments/lexers/theorem.py +458 -0
  733. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  734. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  735. wandb/vendor/pygments/lexers/urbi.py +133 -0
  736. wandb/vendor/pygments/lexers/varnish.py +190 -0
  737. wandb/vendor/pygments/lexers/verification.py +111 -0
  738. wandb/vendor/pygments/lexers/web.py +24 -0
  739. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  740. wandb/vendor/pygments/lexers/whiley.py +116 -0
  741. wandb/vendor/pygments/lexers/x10.py +69 -0
  742. wandb/vendor/pygments/modeline.py +44 -0
  743. wandb/vendor/pygments/plugin.py +68 -0
  744. wandb/vendor/pygments/regexopt.py +92 -0
  745. wandb/vendor/pygments/scanner.py +105 -0
  746. wandb/vendor/pygments/sphinxext.py +158 -0
  747. wandb/vendor/pygments/style.py +155 -0
  748. wandb/vendor/pygments/styles/__init__.py +80 -0
  749. wandb/vendor/pygments/styles/abap.py +29 -0
  750. wandb/vendor/pygments/styles/algol.py +63 -0
  751. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  752. wandb/vendor/pygments/styles/arduino.py +98 -0
  753. wandb/vendor/pygments/styles/autumn.py +65 -0
  754. wandb/vendor/pygments/styles/borland.py +51 -0
  755. wandb/vendor/pygments/styles/bw.py +49 -0
  756. wandb/vendor/pygments/styles/colorful.py +81 -0
  757. wandb/vendor/pygments/styles/default.py +73 -0
  758. wandb/vendor/pygments/styles/emacs.py +72 -0
  759. wandb/vendor/pygments/styles/friendly.py +72 -0
  760. wandb/vendor/pygments/styles/fruity.py +42 -0
  761. wandb/vendor/pygments/styles/igor.py +29 -0
  762. wandb/vendor/pygments/styles/lovelace.py +97 -0
  763. wandb/vendor/pygments/styles/manni.py +75 -0
  764. wandb/vendor/pygments/styles/monokai.py +106 -0
  765. wandb/vendor/pygments/styles/murphy.py +80 -0
  766. wandb/vendor/pygments/styles/native.py +65 -0
  767. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  768. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  769. wandb/vendor/pygments/styles/pastie.py +75 -0
  770. wandb/vendor/pygments/styles/perldoc.py +69 -0
  771. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  772. wandb/vendor/pygments/styles/rrt.py +33 -0
  773. wandb/vendor/pygments/styles/sas.py +44 -0
  774. wandb/vendor/pygments/styles/stata.py +40 -0
  775. wandb/vendor/pygments/styles/tango.py +141 -0
  776. wandb/vendor/pygments/styles/trac.py +63 -0
  777. wandb/vendor/pygments/styles/vim.py +63 -0
  778. wandb/vendor/pygments/styles/vs.py +38 -0
  779. wandb/vendor/pygments/styles/xcode.py +51 -0
  780. wandb/vendor/pygments/token.py +213 -0
  781. wandb/vendor/pygments/unistring.py +217 -0
  782. wandb/vendor/pygments/util.py +388 -0
  783. wandb/vendor/pynvml/__init__.py +0 -0
  784. wandb/vendor/pynvml/pynvml.py +4779 -0
  785. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  786. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  787. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  788. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  789. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  790. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  791. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  792. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  793. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  794. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  795. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  796. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  797. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  798. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  799. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  800. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  801. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  802. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  803. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  804. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  805. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  806. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  807. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  808. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  809. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  810. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  811. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  812. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  813. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  814. wandb/wandb_agent.py +588 -0
  815. wandb/wandb_controller.py +721 -0
  816. wandb/wandb_run.py +9 -0
  817. wandb/wandb_torch.py +550 -0
  818. wandb-0.18.0.dist-info/METADATA +212 -0
  819. wandb-0.18.0.dist-info/RECORD +822 -0
  820. wandb-0.18.0.dist-info/WHEEL +4 -0
  821. wandb-0.18.0.dist-info/entry_points.txt +3 -0
  822. wandb-0.18.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,4287 @@
1
+ import ast
2
+ import base64
3
+ import datetime
4
+ import functools
5
+ import http.client
6
+ import json
7
+ import logging
8
+ import os
9
+ import re
10
+ import socket
11
+ import sys
12
+ import threading
13
+ from copy import deepcopy
14
+ from pathlib import Path
15
+ from typing import (
16
+ IO,
17
+ TYPE_CHECKING,
18
+ Any,
19
+ Callable,
20
+ Dict,
21
+ Iterable,
22
+ List,
23
+ Mapping,
24
+ MutableMapping,
25
+ Optional,
26
+ Sequence,
27
+ TextIO,
28
+ Tuple,
29
+ Union,
30
+ )
31
+
32
+ import click
33
+ import requests
34
+ import yaml
35
+ from wandb_gql import Client, gql
36
+ from wandb_gql.client import RetryError
37
+
38
+ import wandb
39
+ from wandb import env, util
40
+ from wandb.apis.normalize import normalize_exceptions, parse_backend_error_messages
41
+ from wandb.errors import AuthenticationError, CommError, UnsupportedError, UsageError
42
+ from wandb.integration.sagemaker import parse_sm_secrets
43
+ from wandb.old.settings import Settings
44
+ from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
45
+ from wandb.sdk.lib.gql_request import GraphQLSession
46
+ from wandb.sdk.lib.hashutil import B64MD5, md5_file_b64
47
+
48
+ from ..lib import credentials, retry
49
+ from ..lib.filenames import DIFF_FNAME, METADATA_FNAME
50
+ from ..lib.gitlib import GitRepo
51
+ from . import context
52
+ from .progress import Progress
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+ if TYPE_CHECKING:
57
+ if sys.version_info >= (3, 8):
58
+ from typing import Literal, TypedDict
59
+ else:
60
+ from typing_extensions import Literal, TypedDict
61
+
62
+ from .progress import ProgressFn
63
+
64
+ class CreateArtifactFileSpecInput(TypedDict, total=False):
65
+ """Corresponds to `type CreateArtifactFileSpecInput` in schema.graphql."""
66
+
67
+ artifactID: str # noqa: N815
68
+ name: str
69
+ md5: str
70
+ mimetype: Optional[str]
71
+ artifactManifestID: Optional[str] # noqa: N815
72
+ uploadPartsInput: Optional[List[Dict[str, object]]] # noqa: N815
73
+
74
+ class CreateArtifactFilesResponseFile(TypedDict):
75
+ id: str
76
+ name: str
77
+ displayName: str # noqa: N815
78
+ uploadUrl: Optional[str] # noqa: N815
79
+ uploadHeaders: Sequence[str] # noqa: N815
80
+ uploadMultipartUrls: "UploadPartsResponse" # noqa: N815
81
+ storagePath: str # noqa: N815
82
+ artifact: "CreateArtifactFilesResponseFileNode"
83
+
84
+ class CreateArtifactFilesResponseFileNode(TypedDict):
85
+ id: str
86
+
87
+ class UploadPartsResponse(TypedDict):
88
+ uploadUrlParts: List["UploadUrlParts"] # noqa: N815
89
+ uploadID: str # noqa: N815
90
+
91
+ class UploadUrlParts(TypedDict):
92
+ partNumber: int # noqa: N815
93
+ uploadUrl: str # noqa: N815
94
+
95
+ class CompleteMultipartUploadArtifactInput(TypedDict):
96
+ """Corresponds to `type CompleteMultipartUploadArtifactInput` in schema.graphql."""
97
+
98
+ completeMultipartAction: str # noqa: N815
99
+ completedParts: Dict[int, str] # noqa: N815
100
+ artifactID: str # noqa: N815
101
+ storagePath: str # noqa: N815
102
+ uploadID: str # noqa: N815
103
+ md5: str
104
+
105
+ class CompleteMultipartUploadArtifactResponse(TypedDict):
106
+ digest: str
107
+
108
+ class DefaultSettings(TypedDict):
109
+ section: str
110
+ git_remote: str
111
+ ignore_globs: Optional[List[str]]
112
+ base_url: Optional[str]
113
+ root_dir: Optional[str]
114
+ api_key: Optional[str]
115
+ entity: Optional[str]
116
+ project: Optional[str]
117
+ _extra_http_headers: Optional[Mapping[str, str]]
118
+ _proxies: Optional[Mapping[str, str]]
119
+
120
+ _Response = MutableMapping
121
+ SweepState = Literal["RUNNING", "PAUSED", "CANCELED", "FINISHED"]
122
+ Number = Union[int, float]
123
+
124
+ # class _MappingSupportsCopy(Protocol):
125
+ # def copy(self) -> "_MappingSupportsCopy": ...
126
+ # def keys(self) -> Iterable: ...
127
+ # def __getitem__(self, name: str) -> Any: ...
128
+
129
+ httpclient_logger = logging.getLogger("http.client")
130
+ if os.environ.get("WANDB_DEBUG"):
131
+ httpclient_logger.setLevel(logging.DEBUG)
132
+
133
+
134
+ def check_httpclient_logger_handler() -> None:
135
+ # Only enable http.client logging if WANDB_DEBUG is set
136
+ if not os.environ.get("WANDB_DEBUG"):
137
+ return
138
+ if httpclient_logger.handlers:
139
+ return
140
+
141
+ # Enable HTTPConnection debug logging to the logging framework
142
+ level = logging.DEBUG
143
+
144
+ def httpclient_log(*args: Any) -> None:
145
+ httpclient_logger.log(level, " ".join(args))
146
+
147
+ # mask the print() built-in in the http.client module to use logging instead
148
+ http.client.print = httpclient_log # type: ignore[attr-defined]
149
+ # enable debugging
150
+ http.client.HTTPConnection.debuglevel = 1
151
+
152
+ root_logger = logging.getLogger("wandb")
153
+ if root_logger.handlers:
154
+ httpclient_logger.addHandler(root_logger.handlers[0])
155
+
156
+
157
+ class _ThreadLocalData(threading.local):
158
+ context: Optional[context.Context]
159
+
160
+ def __init__(self) -> None:
161
+ self.context = None
162
+
163
+
164
+ class Api:
165
+ """W&B Internal Api wrapper.
166
+
167
+ Note:
168
+ Settings are automatically overridden by looking for
169
+ a `wandb/settings` file in the current working directory or its parent
170
+ directory. If none can be found, we look in the current user's home
171
+ directory.
172
+
173
+ Arguments:
174
+ default_settings(dict, optional): If you aren't using a settings
175
+ file, or you wish to override the section to use in the settings file
176
+ Override the settings here.
177
+ """
178
+
179
+ HTTP_TIMEOUT = env.get_http_timeout(20)
180
+ FILE_PUSHER_TIMEOUT = env.get_file_pusher_timeout()
181
+ _global_context: context.Context
182
+ _local_data: _ThreadLocalData
183
+
184
+ def __init__(
185
+ self,
186
+ default_settings: Optional[
187
+ Union[
188
+ "wandb.sdk.wandb_settings.Settings",
189
+ "wandb.sdk.internal.settings_static.SettingsStatic",
190
+ Settings,
191
+ dict,
192
+ ]
193
+ ] = None,
194
+ load_settings: bool = True,
195
+ retry_timedelta: datetime.timedelta = datetime.timedelta( # noqa: B008 # okay because it's immutable
196
+ days=7
197
+ ),
198
+ environ: MutableMapping = os.environ,
199
+ retry_callback: Optional[Callable[[int, str], Any]] = None,
200
+ ) -> None:
201
+ self._environ = environ
202
+ self._global_context = context.Context()
203
+ self._local_data = _ThreadLocalData()
204
+ self.default_settings: DefaultSettings = {
205
+ "section": "default",
206
+ "git_remote": "origin",
207
+ "ignore_globs": [],
208
+ "base_url": "https://api.wandb.ai",
209
+ "root_dir": None,
210
+ "api_key": None,
211
+ "entity": None,
212
+ "project": None,
213
+ "_extra_http_headers": None,
214
+ "_proxies": None,
215
+ }
216
+ self.retry_timedelta = retry_timedelta
217
+ # todo: Old Settings do not follow the SupportsKeysAndGetItem Protocol
218
+ default_settings = default_settings or {}
219
+ self.default_settings.update(default_settings) # type: ignore
220
+ self.retry_uploads = 10
221
+ self._settings = Settings(
222
+ load_settings=load_settings,
223
+ root_dir=self.default_settings.get("root_dir"),
224
+ )
225
+ self.git = GitRepo(remote=self.settings("git_remote"))
226
+ # Mutable settings set by the _file_stream_api
227
+ self.dynamic_settings = {
228
+ "system_sample_seconds": 2,
229
+ "system_samples": 15,
230
+ "heartbeat_seconds": 30,
231
+ }
232
+
233
+ # todo: remove these hacky hacks after settings refactor is complete
234
+ # keeping this code here to limit scope and so that it is easy to remove later
235
+ self._extra_http_headers = self.settings("_extra_http_headers") or json.loads(
236
+ self._environ.get("WANDB__EXTRA_HTTP_HEADERS", "{}")
237
+ )
238
+ self._extra_http_headers.update(_thread_local_api_settings.headers or {})
239
+
240
+ auth = None
241
+ if self.access_token is not None:
242
+ self._extra_http_headers["Authorization"] = f"Bearer {self.access_token}"
243
+ elif _thread_local_api_settings.cookies is None:
244
+ auth = ("api", self.api_key or "")
245
+
246
+ proxies = self.settings("_proxies") or json.loads(
247
+ self._environ.get("WANDB__PROXIES", "{}")
248
+ )
249
+
250
+ self.client = Client(
251
+ transport=GraphQLSession(
252
+ headers={
253
+ "User-Agent": self.user_agent,
254
+ "X-WANDB-USERNAME": env.get_username(env=self._environ),
255
+ "X-WANDB-USER-EMAIL": env.get_user_email(env=self._environ),
256
+ **self._extra_http_headers,
257
+ },
258
+ use_json=True,
259
+ # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s
260
+ # https://bugs.python.org/issue22889
261
+ timeout=self.HTTP_TIMEOUT,
262
+ auth=auth,
263
+ url=f"{self.settings('base_url')}/graphql",
264
+ cookies=_thread_local_api_settings.cookies,
265
+ proxies=proxies,
266
+ )
267
+ )
268
+
269
+ self.retry_callback = retry_callback
270
+ self._retry_gql = retry.Retry(
271
+ self.execute,
272
+ retry_timedelta=retry_timedelta,
273
+ check_retry_fn=util.no_retry_auth,
274
+ retryable_exceptions=(RetryError, requests.RequestException),
275
+ retry_callback=retry_callback,
276
+ )
277
+ self._current_run_id: Optional[str] = None
278
+ self._file_stream_api = None
279
+ self._upload_file_session = requests.Session()
280
+ if self.FILE_PUSHER_TIMEOUT:
281
+ self._upload_file_session.put = functools.partial( # type: ignore
282
+ self._upload_file_session.put,
283
+ timeout=self.FILE_PUSHER_TIMEOUT,
284
+ )
285
+ if proxies:
286
+ self._upload_file_session.proxies.update(proxies)
287
+ # This Retry class is initialized once for each Api instance, so this
288
+ # defaults to retrying 1 million times per process or 7 days
289
+ self.upload_file_retry = normalize_exceptions(
290
+ retry.retriable(retry_timedelta=retry_timedelta)(self.upload_file)
291
+ )
292
+ self.upload_multipart_file_chunk_retry = normalize_exceptions(
293
+ retry.retriable(retry_timedelta=retry_timedelta)(
294
+ self.upload_multipart_file_chunk
295
+ )
296
+ )
297
+ self._client_id_mapping: Dict[str, str] = {}
298
+ # Large file uploads to azure can optionally use their SDK
299
+ self._azure_blob_module = util.get_module("azure.storage.blob")
300
+
301
+ self.query_types: Optional[List[str]] = None
302
+ self.mutation_types: Optional[List[str]] = None
303
+ self.server_info_types: Optional[List[str]] = None
304
+ self.server_use_artifact_input_info: Optional[List[str]] = None
305
+ self.server_create_artifact_input_info: Optional[List[str]] = None
306
+ self.server_artifact_fields_info: Optional[List[str]] = None
307
+ self._max_cli_version: Optional[str] = None
308
+ self._server_settings_type: Optional[List[str]] = None
309
+ self.fail_run_queue_item_input_info: Optional[List[str]] = None
310
+ self.create_launch_agent_input_info: Optional[List[str]] = None
311
+ self.server_create_run_queue_supports_drc: Optional[bool] = None
312
+ self.server_create_run_queue_supports_priority: Optional[bool] = None
313
+ self.server_supports_template_variables: Optional[bool] = None
314
+ self.server_push_to_run_queue_supports_priority: Optional[bool] = None
315
+
316
+ def gql(self, *args: Any, **kwargs: Any) -> Any:
317
+ ret = self._retry_gql(
318
+ *args,
319
+ retry_cancel_event=self.context.cancel_event,
320
+ **kwargs,
321
+ )
322
+ return ret
323
+
324
+ def set_local_context(self, api_context: Optional[context.Context]) -> None:
325
+ self._local_data.context = api_context
326
+
327
+ def clear_local_context(self) -> None:
328
+ self._local_data.context = None
329
+
330
+ @property
331
+ def context(self) -> context.Context:
332
+ return self._local_data.context or self._global_context
333
+
334
+ def reauth(self) -> None:
335
+ """Ensure the current api key is set in the transport."""
336
+ self.client.transport.session.auth = ("api", self.api_key or "")
337
+
338
+ def relocate(self) -> None:
339
+ """Ensure the current api points to the right server."""
340
+ self.client.transport.url = "{}/graphql".format(self.settings("base_url"))
341
+
342
+ def execute(self, *args: Any, **kwargs: Any) -> "_Response":
343
+ """Wrapper around execute that logs in cases of failure."""
344
+ try:
345
+ return self.client.execute(*args, **kwargs) # type: ignore
346
+ except requests.exceptions.HTTPError as err:
347
+ response = err.response
348
+ assert response is not None
349
+ logger.error(f"{response.status_code} response executing GraphQL.")
350
+ logger.error(response.text)
351
+ for error in parse_backend_error_messages(response):
352
+ wandb.termerror(f"Error while calling W&B API: {error} ({response})")
353
+ raise
354
+
355
+ def disabled(self) -> Union[str, bool]:
356
+ return self._settings.get(Settings.DEFAULT_SECTION, "disabled", fallback=False) # type: ignore
357
+
358
+ def set_current_run_id(self, run_id: str) -> None:
359
+ self._current_run_id = run_id
360
+
361
+ @property
362
+ def current_run_id(self) -> Optional[str]:
363
+ return self._current_run_id
364
+
365
+ @property
366
+ def user_agent(self) -> str:
367
+ return f"W&B Internal Client {wandb.__version__}"
368
+
369
+ @property
370
+ def api_key(self) -> Optional[str]:
371
+ if _thread_local_api_settings.api_key:
372
+ return _thread_local_api_settings.api_key
373
+ auth = requests.utils.get_netrc_auth(self.api_url)
374
+ key = None
375
+ if auth:
376
+ key = auth[-1]
377
+
378
+ # Environment should take precedence
379
+ env_key: Optional[str] = self._environ.get(env.API_KEY)
380
+ sagemaker_key: Optional[str] = parse_sm_secrets().get(env.API_KEY)
381
+ default_key: Optional[str] = self.default_settings.get("api_key")
382
+ return env_key or key or sagemaker_key or default_key
383
+
384
+ @property
385
+ def access_token(self) -> Optional[str]:
386
+ """Retrieves an access token for authentication.
387
+
388
+ This function attempts to exchange an identity token for a temporary
389
+ access token from the server, and save it to the credentials file.
390
+ It uses the path to the identity token as defined in the environment
391
+ variables. If the environment variable is not set, it returns None.
392
+
393
+ Returns:
394
+ Optional[str]: The access token if available, otherwise None if
395
+ no identity token is supplied.
396
+ Raises:
397
+ AuthenticationError: If the path to the identity token is not found.
398
+ """
399
+ token_file_str = self._environ.get(env.IDENTITY_TOKEN_FILE)
400
+ if not token_file_str:
401
+ return None
402
+
403
+ token_file = Path(token_file_str)
404
+ if not token_file.exists():
405
+ raise AuthenticationError(f"Identity token file not found: {token_file}")
406
+
407
+ base_url = self.settings("base_url")
408
+ credentials_file = env.get_credentials_file(
409
+ str(credentials.DEFAULT_WANDB_CREDENTIALS_FILE), self._environ
410
+ )
411
+ return credentials.access_token(base_url, token_file, credentials_file)
412
+
413
+ @property
414
+ def api_url(self) -> str:
415
+ return self.settings("base_url") # type: ignore
416
+
417
+ @property
418
+ def app_url(self) -> str:
419
+ return wandb.util.app_url(self.api_url)
420
+
421
+ @property
422
+ def default_entity(self) -> str:
423
+ return self.viewer().get("entity") # type: ignore
424
+
425
+ def settings(self, key: Optional[str] = None, section: Optional[str] = None) -> Any:
426
+ """The settings overridden from the wandb/settings file.
427
+
428
+ Arguments:
429
+ key (str, optional): If provided only this setting is returned
430
+ section (str, optional): If provided this section of the setting file is
431
+ used, defaults to "default"
432
+
433
+ Returns:
434
+ A dict with the current settings
435
+
436
+ {
437
+ "entity": "models",
438
+ "base_url": "https://api.wandb.ai",
439
+ "project": None
440
+ }
441
+ """
442
+ result = self.default_settings.copy()
443
+ result.update(self._settings.items(section=section)) # type: ignore
444
+ result.update(
445
+ {
446
+ "entity": env.get_entity(
447
+ self._settings.get(
448
+ Settings.DEFAULT_SECTION,
449
+ "entity",
450
+ fallback=result.get("entity"),
451
+ ),
452
+ env=self._environ,
453
+ ),
454
+ "project": env.get_project(
455
+ self._settings.get(
456
+ Settings.DEFAULT_SECTION,
457
+ "project",
458
+ fallback=result.get("project"),
459
+ ),
460
+ env=self._environ,
461
+ ),
462
+ "base_url": env.get_base_url(
463
+ self._settings.get(
464
+ Settings.DEFAULT_SECTION,
465
+ "base_url",
466
+ fallback=result.get("base_url"),
467
+ ),
468
+ env=self._environ,
469
+ ),
470
+ "ignore_globs": env.get_ignore(
471
+ self._settings.get(
472
+ Settings.DEFAULT_SECTION,
473
+ "ignore_globs",
474
+ fallback=result.get("ignore_globs"),
475
+ ),
476
+ env=self._environ,
477
+ ),
478
+ }
479
+ )
480
+
481
+ return result if key is None else result[key] # type: ignore
482
+
483
+ def clear_setting(
484
+ self, key: str, globally: bool = False, persist: bool = False
485
+ ) -> None:
486
+ self._settings.clear(
487
+ Settings.DEFAULT_SECTION, key, globally=globally, persist=persist
488
+ )
489
+
490
+ def set_setting(
491
+ self, key: str, value: Any, globally: bool = False, persist: bool = False
492
+ ) -> None:
493
+ self._settings.set(
494
+ Settings.DEFAULT_SECTION, key, value, globally=globally, persist=persist
495
+ )
496
+ if key == "entity":
497
+ env.set_entity(value, env=self._environ)
498
+ elif key == "project":
499
+ env.set_project(value, env=self._environ)
500
+ elif key == "base_url":
501
+ self.relocate()
502
+
503
+ def parse_slug(
504
+ self, slug: str, project: Optional[str] = None, run: Optional[str] = None
505
+ ) -> Tuple[str, str]:
506
+ """Parse a slug into a project and run.
507
+
508
+ Arguments:
509
+ slug (str): The slug to parse
510
+ project (str, optional): The project to use, if not provided it will be
511
+ inferred from the slug
512
+ run (str, optional): The run to use, if not provided it will be inferred
513
+ from the slug
514
+
515
+ Returns:
516
+ A dict with the project and run
517
+ """
518
+ if slug and "/" in slug:
519
+ parts = slug.split("/")
520
+ project = parts[0]
521
+ run = parts[1]
522
+ else:
523
+ project = project or self.settings().get("project")
524
+ if project is None:
525
+ raise CommError("No default project configured.")
526
+ run = run or slug or self.current_run_id or env.get_run(env=self._environ)
527
+ assert run, "run must be specified"
528
+ return project, run
529
+
530
+ @normalize_exceptions
531
+ def server_info_introspection(self) -> Tuple[List[str], List[str], List[str]]:
532
+ query_string = """
533
+ query ProbeServerCapabilities {
534
+ QueryType: __type(name: "Query") {
535
+ ...fieldData
536
+ }
537
+ MutationType: __type(name: "Mutation") {
538
+ ...fieldData
539
+ }
540
+ ServerInfoType: __type(name: "ServerInfo") {
541
+ ...fieldData
542
+ }
543
+ }
544
+
545
+ fragment fieldData on __Type {
546
+ fields {
547
+ name
548
+ }
549
+ }
550
+ """
551
+ if (
552
+ self.query_types is None
553
+ or self.mutation_types is None
554
+ or self.server_info_types is None
555
+ ):
556
+ query = gql(query_string)
557
+ res = self.gql(query)
558
+
559
+ self.query_types = [
560
+ field.get("name", "")
561
+ for field in res.get("QueryType", {}).get("fields", [{}])
562
+ ]
563
+ self.mutation_types = [
564
+ field.get("name", "")
565
+ for field in res.get("MutationType", {}).get("fields", [{}])
566
+ ]
567
+ self.server_info_types = [
568
+ field.get("name", "")
569
+ for field in res.get("ServerInfoType", {}).get("fields", [{}])
570
+ ]
571
+ return self.query_types, self.server_info_types, self.mutation_types
572
+
573
+ @normalize_exceptions
574
+ def server_settings_introspection(self) -> None:
575
+ query_string = """
576
+ query ProbeServerSettings {
577
+ ServerSettingsType: __type(name: "ServerSettings") {
578
+ ...fieldData
579
+ }
580
+ }
581
+
582
+ fragment fieldData on __Type {
583
+ fields {
584
+ name
585
+ }
586
+ }
587
+ """
588
+ if self._server_settings_type is None:
589
+ query = gql(query_string)
590
+ res = self.gql(query)
591
+ self._server_settings_type = (
592
+ [
593
+ field.get("name", "")
594
+ for field in res.get("ServerSettingsType", {}).get("fields", [{}])
595
+ ]
596
+ if res
597
+ else []
598
+ )
599
+
600
+ def server_use_artifact_input_introspection(self) -> List:
601
+ query_string = """
602
+ query ProbeServerUseArtifactInput {
603
+ UseArtifactInputInfoType: __type(name: "UseArtifactInput") {
604
+ name
605
+ inputFields {
606
+ name
607
+ }
608
+ }
609
+ }
610
+ """
611
+
612
+ if self.server_use_artifact_input_info is None:
613
+ query = gql(query_string)
614
+ res = self.gql(query)
615
+ self.server_use_artifact_input_info = [
616
+ field.get("name", "")
617
+ for field in res.get("UseArtifactInputInfoType", {}).get(
618
+ "inputFields", [{}]
619
+ )
620
+ ]
621
+ return self.server_use_artifact_input_info
622
+
623
+ @normalize_exceptions
624
+ def launch_agent_introspection(self) -> Optional[str]:
625
+ query = gql(
626
+ """
627
+ query LaunchAgentIntrospection {
628
+ LaunchAgentType: __type(name: "LaunchAgent") {
629
+ name
630
+ }
631
+ }
632
+ """
633
+ )
634
+
635
+ res = self.gql(query)
636
+ return res.get("LaunchAgentType") or None
637
+
638
+ @normalize_exceptions
639
+ def create_run_queue_introspection(self) -> Tuple[bool, bool, bool]:
640
+ _, _, mutations = self.server_info_introspection()
641
+ query_string = """
642
+ query ProbeCreateRunQueueInput {
643
+ CreateRunQueueInputType: __type(name: "CreateRunQueueInput") {
644
+ name
645
+ inputFields {
646
+ name
647
+ }
648
+ }
649
+ }
650
+ """
651
+ if (
652
+ self.server_create_run_queue_supports_drc is None
653
+ or self.server_create_run_queue_supports_priority is None
654
+ ):
655
+ query = gql(query_string)
656
+ res = self.gql(query)
657
+ if res is None:
658
+ raise CommError("Could not get CreateRunQueue input from GQL.")
659
+ self.server_create_run_queue_supports_drc = "defaultResourceConfigID" in [
660
+ x["name"]
661
+ for x in (
662
+ res.get("CreateRunQueueInputType", {}).get("inputFields", [{}])
663
+ )
664
+ ]
665
+ self.server_create_run_queue_supports_priority = "prioritizationMode" in [
666
+ x["name"]
667
+ for x in (
668
+ res.get("CreateRunQueueInputType", {}).get("inputFields", [{}])
669
+ )
670
+ ]
671
+ return (
672
+ "createRunQueue" in mutations,
673
+ self.server_create_run_queue_supports_drc,
674
+ self.server_create_run_queue_supports_priority,
675
+ )
676
+
677
+ @normalize_exceptions
678
+ def push_to_run_queue_introspection(self) -> Tuple[bool, bool]:
679
+ query_string = """
680
+ query ProbePushToRunQueueInput {
681
+ PushToRunQueueInputType: __type(name: "PushToRunQueueInput") {
682
+ name
683
+ inputFields {
684
+ name
685
+ }
686
+ }
687
+ }
688
+ """
689
+
690
+ if (
691
+ self.server_supports_template_variables is None
692
+ or self.server_push_to_run_queue_supports_priority is None
693
+ ):
694
+ query = gql(query_string)
695
+ res = self.gql(query)
696
+ self.server_supports_template_variables = "templateVariableValues" in [
697
+ x["name"]
698
+ for x in (
699
+ res.get("PushToRunQueueInputType", {}).get("inputFields", [{}])
700
+ )
701
+ ]
702
+ self.server_push_to_run_queue_supports_priority = "priority" in [
703
+ x["name"]
704
+ for x in (
705
+ res.get("PushToRunQueueInputType", {}).get("inputFields", [{}])
706
+ )
707
+ ]
708
+
709
+ return (
710
+ self.server_supports_template_variables,
711
+ self.server_push_to_run_queue_supports_priority,
712
+ )
713
+
714
+ @normalize_exceptions
715
+ def create_default_resource_config_introspection(self) -> bool:
716
+ _, _, mutations = self.server_info_introspection()
717
+ return "createDefaultResourceConfig" in mutations
718
+
719
+ @normalize_exceptions
720
+ def fail_run_queue_item_introspection(self) -> bool:
721
+ _, _, mutations = self.server_info_introspection()
722
+ return "failRunQueueItem" in mutations
723
+
724
+ @normalize_exceptions
725
+ def fail_run_queue_item_fields_introspection(self) -> List:
726
+ if self.fail_run_queue_item_input_info:
727
+ return self.fail_run_queue_item_input_info
728
+ query_string = """
729
+ query ProbeServerFailRunQueueItemInput {
730
+ FailRunQueueItemInputInfoType: __type(name:"FailRunQueueItemInput") {
731
+ inputFields{
732
+ name
733
+ }
734
+ }
735
+ }
736
+ """
737
+
738
+ query = gql(query_string)
739
+ res = self.gql(query)
740
+
741
+ self.fail_run_queue_item_input_info = [
742
+ field.get("name", "")
743
+ for field in res.get("FailRunQueueItemInputInfoType", {}).get(
744
+ "inputFields", [{}]
745
+ )
746
+ ]
747
+ return self.fail_run_queue_item_input_info
748
+
749
+ @normalize_exceptions
750
+ def fail_run_queue_item(
751
+ self,
752
+ run_queue_item_id: str,
753
+ message: str,
754
+ stage: str,
755
+ file_paths: Optional[List[str]] = None,
756
+ ) -> bool:
757
+ if not self.fail_run_queue_item_introspection():
758
+ return False
759
+ variable_values: Dict[str, Union[str, Optional[List[str]]]] = {
760
+ "runQueueItemId": run_queue_item_id,
761
+ }
762
+ if "message" in self.fail_run_queue_item_fields_introspection():
763
+ variable_values.update({"message": message, "stage": stage})
764
+ if file_paths is not None:
765
+ variable_values["filePaths"] = file_paths
766
+ mutation_string = """
767
+ mutation failRunQueueItem($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
768
+ failRunQueueItem(
769
+ input: {
770
+ runQueueItemId: $runQueueItemId
771
+ message: $message
772
+ stage: $stage
773
+ filePaths: $filePaths
774
+ }
775
+ ) {
776
+ success
777
+ }
778
+ }
779
+ """
780
+ else:
781
+ mutation_string = """
782
+ mutation failRunQueueItem($runQueueItemId: ID!) {
783
+ failRunQueueItem(
784
+ input: {
785
+ runQueueItemId: $runQueueItemId
786
+ }
787
+ ) {
788
+ success
789
+ }
790
+ }
791
+ """
792
+
793
+ mutation = gql(mutation_string)
794
+ response = self.gql(mutation, variable_values=variable_values)
795
+ result: bool = response["failRunQueueItem"]["success"]
796
+ return result
797
+
798
+ @normalize_exceptions
799
+ def update_run_queue_item_warning_introspection(self) -> bool:
800
+ _, _, mutations = self.server_info_introspection()
801
+ return "updateRunQueueItemWarning" in mutations
802
+
803
+ @normalize_exceptions
804
+ def update_run_queue_item_warning(
805
+ self,
806
+ run_queue_item_id: str,
807
+ message: str,
808
+ stage: str,
809
+ file_paths: Optional[List[str]] = None,
810
+ ) -> bool:
811
+ if not self.update_run_queue_item_warning_introspection():
812
+ return False
813
+ mutation = gql(
814
+ """
815
+ mutation updateRunQueueItemWarning($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
816
+ updateRunQueueItemWarning(
817
+ input: {
818
+ runQueueItemId: $runQueueItemId
819
+ message: $message
820
+ stage: $stage
821
+ filePaths: $filePaths
822
+ }
823
+ ) {
824
+ success
825
+ }
826
+ }
827
+ """
828
+ )
829
+ response = self.gql(
830
+ mutation,
831
+ variable_values={
832
+ "runQueueItemId": run_queue_item_id,
833
+ "message": message,
834
+ "stage": stage,
835
+ "filePaths": file_paths,
836
+ },
837
+ )
838
+ result: bool = response["updateRunQueueItemWarning"]["success"]
839
+ return result
840
+
841
+ @normalize_exceptions
842
+ def viewer(self) -> Dict[str, Any]:
843
+ query = gql(
844
+ """
845
+ query Viewer{
846
+ viewer {
847
+ id
848
+ entity
849
+ username
850
+ flags
851
+ teams {
852
+ edges {
853
+ node {
854
+ name
855
+ }
856
+ }
857
+ }
858
+ }
859
+ }
860
+ """
861
+ )
862
+ res = self.gql(query)
863
+ return res.get("viewer") or {}
864
+
865
+ @normalize_exceptions
866
+ def max_cli_version(self) -> Optional[str]:
867
+ if self._max_cli_version is not None:
868
+ return self._max_cli_version
869
+
870
+ query_types, server_info_types, _ = self.server_info_introspection()
871
+ cli_version_exists = (
872
+ "serverInfo" in query_types and "cliVersionInfo" in server_info_types
873
+ )
874
+ if not cli_version_exists:
875
+ return None
876
+
877
+ _, server_info = self.viewer_server_info()
878
+ self._max_cli_version = server_info.get("cliVersionInfo", {}).get(
879
+ "max_cli_version"
880
+ )
881
+ return self._max_cli_version
882
+
883
+ @normalize_exceptions
884
+ def viewer_server_info(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
885
+ local_query = """
886
+ latestLocalVersionInfo {
887
+ outOfDate
888
+ latestVersionString
889
+ versionOnThisInstanceString
890
+ }
891
+ """
892
+ cli_query = """
893
+ serverInfo {
894
+ cliVersionInfo
895
+ _LOCAL_QUERY_
896
+ }
897
+ """
898
+ query_template = """
899
+ query Viewer{
900
+ viewer {
901
+ id
902
+ entity
903
+ username
904
+ email
905
+ flags
906
+ teams {
907
+ edges {
908
+ node {
909
+ name
910
+ }
911
+ }
912
+ }
913
+ }
914
+ _CLI_QUERY_
915
+ }
916
+ """
917
+ query_types, server_info_types, _ = self.server_info_introspection()
918
+
919
+ cli_version_exists = (
920
+ "serverInfo" in query_types and "cliVersionInfo" in server_info_types
921
+ )
922
+
923
+ local_version_exists = (
924
+ "serverInfo" in query_types
925
+ and "latestLocalVersionInfo" in server_info_types
926
+ )
927
+
928
+ cli_query_string = "" if not cli_version_exists else cli_query
929
+ local_query_string = "" if not local_version_exists else local_query
930
+
931
+ query_string = query_template.replace("_CLI_QUERY_", cli_query_string).replace(
932
+ "_LOCAL_QUERY_", local_query_string
933
+ )
934
+ query = gql(query_string)
935
+ res = self.gql(query)
936
+ return res.get("viewer") or {}, res.get("serverInfo") or {}
937
+
938
+ @normalize_exceptions
939
+ def list_projects(self, entity: Optional[str] = None) -> List[Dict[str, str]]:
940
+ """List projects in W&B scoped by entity.
941
+
942
+ Arguments:
943
+ entity (str, optional): The entity to scope this project to.
944
+
945
+ Returns:
946
+ [{"id","name","description"}]
947
+ """
948
+ query = gql(
949
+ """
950
+ query EntityProjects($entity: String) {
951
+ models(first: 10, entityName: $entity) {
952
+ edges {
953
+ node {
954
+ id
955
+ name
956
+ description
957
+ }
958
+ }
959
+ }
960
+ }
961
+ """
962
+ )
963
+ project_list: List[Dict[str, str]] = self._flatten_edges(
964
+ self.gql(
965
+ query, variable_values={"entity": entity or self.settings("entity")}
966
+ )["models"]
967
+ )
968
+ return project_list
969
+
970
+ @normalize_exceptions
971
+ def project(self, project: str, entity: Optional[str] = None) -> "_Response":
972
+ """Retrieve project.
973
+
974
+ Arguments:
975
+ project (str): The project to get details for
976
+ entity (str, optional): The entity to scope this project to.
977
+
978
+ Returns:
979
+ [{"id","name","repo","dockerImage","description"}]
980
+ """
981
+ query = gql(
982
+ """
983
+ query ProjectDetails($entity: String, $project: String) {
984
+ model(name: $project, entityName: $entity) {
985
+ id
986
+ name
987
+ repo
988
+ dockerImage
989
+ description
990
+ }
991
+ }
992
+ """
993
+ )
994
+ response: _Response = self.gql(
995
+ query, variable_values={"entity": entity, "project": project}
996
+ )["model"]
997
+ return response
998
+
999
+ @normalize_exceptions
1000
+ def sweep(
1001
+ self,
1002
+ sweep: str,
1003
+ specs: str,
1004
+ project: Optional[str] = None,
1005
+ entity: Optional[str] = None,
1006
+ ) -> Dict[str, Any]:
1007
+ """Retrieve sweep.
1008
+
1009
+ Arguments:
1010
+ sweep (str): The sweep to get details for
1011
+ specs (str): history specs
1012
+ project (str, optional): The project to scope this sweep to.
1013
+ entity (str, optional): The entity to scope this sweep to.
1014
+
1015
+ Returns:
1016
+ [{"id","name","repo","dockerImage","description"}]
1017
+ """
1018
+ query = gql(
1019
+ """
1020
+ query SweepWithRuns($entity: String, $project: String, $sweep: String!, $specs: [JSONString!]!) {
1021
+ project(name: $project, entityName: $entity) {
1022
+ sweep(sweepName: $sweep) {
1023
+ id
1024
+ name
1025
+ method
1026
+ state
1027
+ description
1028
+ config
1029
+ createdAt
1030
+ heartbeatAt
1031
+ updatedAt
1032
+ earlyStopJobRunning
1033
+ bestLoss
1034
+ controller
1035
+ scheduler
1036
+ runs {
1037
+ edges {
1038
+ node {
1039
+ name
1040
+ state
1041
+ config
1042
+ exitcode
1043
+ heartbeatAt
1044
+ shouldStop
1045
+ failed
1046
+ stopped
1047
+ running
1048
+ summaryMetrics
1049
+ sampledHistory(specs: $specs)
1050
+ }
1051
+ }
1052
+ }
1053
+ }
1054
+ }
1055
+ }
1056
+ """
1057
+ )
1058
+ entity = entity or self.settings("entity")
1059
+ project = project or self.settings("project")
1060
+ response = self.gql(
1061
+ query,
1062
+ variable_values={
1063
+ "entity": entity,
1064
+ "project": project,
1065
+ "sweep": sweep,
1066
+ "specs": specs,
1067
+ },
1068
+ )
1069
+ if response["project"] is None or response["project"]["sweep"] is None:
1070
+ raise ValueError(f"Sweep {entity}/{project}/{sweep} not found")
1071
+ data: Dict[str, Any] = response["project"]["sweep"]
1072
+ if data:
1073
+ data["runs"] = self._flatten_edges(data["runs"])
1074
+ return data
1075
+
1076
+ @normalize_exceptions
1077
+ def list_runs(
1078
+ self, project: str, entity: Optional[str] = None
1079
+ ) -> List[Dict[str, str]]:
1080
+ """List runs in W&B scoped by project.
1081
+
1082
+ Arguments:
1083
+ project (str): The project to scope the runs to
1084
+ entity (str, optional): The entity to scope this project to. Defaults to public models
1085
+
1086
+ Returns:
1087
+ [{"id","name","description"}]
1088
+ """
1089
+ query = gql(
1090
+ """
1091
+ query ProjectRuns($model: String!, $entity: String) {
1092
+ model(name: $model, entityName: $entity) {
1093
+ buckets(first: 10) {
1094
+ edges {
1095
+ node {
1096
+ id
1097
+ name
1098
+ displayName
1099
+ description
1100
+ }
1101
+ }
1102
+ }
1103
+ }
1104
+ }
1105
+ """
1106
+ )
1107
+ return self._flatten_edges(
1108
+ self.gql(
1109
+ query,
1110
+ variable_values={
1111
+ "entity": entity or self.settings("entity"),
1112
+ "model": project or self.settings("project"),
1113
+ },
1114
+ )["model"]["buckets"]
1115
+ )
1116
+
1117
+ @normalize_exceptions
1118
+ def run_config(
1119
+ self, project: str, run: Optional[str] = None, entity: Optional[str] = None
1120
+ ) -> Tuple[str, Dict[str, Any], Optional[str], Dict[str, Any]]:
1121
+ """Get the relevant configs for a run.
1122
+
1123
+ Arguments:
1124
+ project (str): The project to download, (can include bucket)
1125
+ run (str, optional): The run to download
1126
+ entity (str, optional): The entity to scope this project to.
1127
+ """
1128
+ check_httpclient_logger_handler()
1129
+
1130
+ query = gql(
1131
+ """
1132
+ query RunConfigs(
1133
+ $name: String!,
1134
+ $entity: String,
1135
+ $run: String!,
1136
+ $pattern: String!,
1137
+ $includeConfig: Boolean!,
1138
+ ) {
1139
+ model(name: $name, entityName: $entity) {
1140
+ bucket(name: $run) {
1141
+ config @include(if: $includeConfig)
1142
+ commit @include(if: $includeConfig)
1143
+ files(pattern: $pattern) {
1144
+ pageInfo {
1145
+ hasNextPage
1146
+ endCursor
1147
+ }
1148
+ edges {
1149
+ node {
1150
+ name
1151
+ directUrl
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+ }
1157
+ }
1158
+ """
1159
+ )
1160
+
1161
+ variable_values = {
1162
+ "name": project,
1163
+ "run": run,
1164
+ "entity": entity,
1165
+ "includeConfig": True,
1166
+ }
1167
+
1168
+ commit: str = ""
1169
+ config: Dict[str, Any] = {}
1170
+ patch: Optional[str] = None
1171
+ metadata: Dict[str, Any] = {}
1172
+
1173
+ # If we use the `names` parameter on the `files` node, then the server
1174
+ # will helpfully give us and 'open' file handle to the files that don't
1175
+ # exist. This is so that we can upload data to it. However, in this
1176
+ # case, we just want to download that file and not upload to it, so
1177
+ # let's instead query for the files that do exist using `pattern`
1178
+ # (with no wildcards).
1179
+ #
1180
+ # Unfortunately we're unable to construct a single pattern that matches
1181
+ # our 2 files, we would need something like regex for that.
1182
+ for filename in [DIFF_FNAME, METADATA_FNAME]:
1183
+ variable_values["pattern"] = filename
1184
+ response = self.gql(query, variable_values=variable_values)
1185
+ if response["model"] is None:
1186
+ raise CommError(f"Run {entity}/{project}/{run} not found")
1187
+ run_obj: Dict = response["model"]["bucket"]
1188
+ # we only need to fetch this config once
1189
+ if variable_values["includeConfig"]:
1190
+ commit = run_obj["commit"]
1191
+ config = json.loads(run_obj["config"] or "{}")
1192
+ variable_values["includeConfig"] = False
1193
+ if run_obj["files"] is not None:
1194
+ for file_edge in run_obj["files"]["edges"]:
1195
+ name = file_edge["node"]["name"]
1196
+ url = file_edge["node"]["directUrl"]
1197
+ res = requests.get(url)
1198
+ res.raise_for_status()
1199
+ if name == METADATA_FNAME:
1200
+ metadata = res.json()
1201
+ elif name == DIFF_FNAME:
1202
+ patch = res.text
1203
+
1204
+ return commit, config, patch, metadata
1205
+
1206
+ @normalize_exceptions
1207
+ def run_resume_status(
1208
+ self, entity: str, project_name: str, name: str
1209
+ ) -> Optional[Dict[str, Any]]:
1210
+ """Check if a run exists and get resume information.
1211
+
1212
+ Arguments:
1213
+ entity (str): The entity to scope this project to.
1214
+ project_name (str): The project to download, (can include bucket)
1215
+ name (str): The run to download
1216
+ """
1217
+ # Pulling wandbConfig.start_time is required so that we can determine if a run has actually started
1218
+ query = gql(
1219
+ """
1220
+ query RunResumeStatus($project: String, $entity: String, $name: String!) {
1221
+ model(name: $project, entityName: $entity) {
1222
+ id
1223
+ name
1224
+ entity {
1225
+ id
1226
+ name
1227
+ }
1228
+
1229
+ bucket(name: $name, missingOk: true) {
1230
+ id
1231
+ name
1232
+ summaryMetrics
1233
+ displayName
1234
+ logLineCount
1235
+ historyLineCount
1236
+ eventsLineCount
1237
+ historyTail
1238
+ eventsTail
1239
+ config
1240
+ tags
1241
+ wandbConfig(keys: ["t"])
1242
+ }
1243
+ }
1244
+ }
1245
+ """
1246
+ )
1247
+
1248
+ response = self.gql(
1249
+ query,
1250
+ variable_values={
1251
+ "entity": entity,
1252
+ "project": project_name,
1253
+ "name": name,
1254
+ },
1255
+ )
1256
+
1257
+ if "model" not in response or "bucket" not in (response["model"] or {}):
1258
+ return None
1259
+
1260
+ project = response["model"]
1261
+ self.set_setting("project", project_name)
1262
+ if "entity" in project:
1263
+ self.set_setting("entity", project["entity"]["name"])
1264
+
1265
+ result: Dict[str, Any] = project["bucket"]
1266
+
1267
+ return result
1268
+
1269
+ @normalize_exceptions
1270
+ def check_stop_requested(
1271
+ self, project_name: str, entity_name: str, run_id: str
1272
+ ) -> bool:
1273
+ query = gql(
1274
+ """
1275
+ query RunStoppedStatus($projectName: String, $entityName: String, $runId: String!) {
1276
+ project(name:$projectName, entityName:$entityName) {
1277
+ run(name:$runId) {
1278
+ stopped
1279
+ }
1280
+ }
1281
+ }
1282
+ """
1283
+ )
1284
+
1285
+ response = self.gql(
1286
+ query,
1287
+ variable_values={
1288
+ "projectName": project_name,
1289
+ "entityName": entity_name,
1290
+ "runId": run_id,
1291
+ },
1292
+ )
1293
+
1294
+ project = response.get("project", None)
1295
+ if not project:
1296
+ return False
1297
+ run = project.get("run", None)
1298
+ if not run:
1299
+ return False
1300
+
1301
+ status: bool = run["stopped"]
1302
+ return status
1303
+
1304
+ def format_project(self, project: str) -> str:
1305
+ return re.sub(r"\W+", "-", project.lower()).strip("-_")
1306
+
1307
+ @normalize_exceptions
1308
+ def upsert_project(
1309
+ self,
1310
+ project: str,
1311
+ id: Optional[str] = None,
1312
+ description: Optional[str] = None,
1313
+ entity: Optional[str] = None,
1314
+ ) -> Dict[str, Any]:
1315
+ """Create a new project.
1316
+
1317
+ Arguments:
1318
+ project (str): The project to create
1319
+ description (str, optional): A description of this project
1320
+ entity (str, optional): The entity to scope this project to.
1321
+ """
1322
+ mutation = gql(
1323
+ """
1324
+ mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String) {
1325
+ upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) {
1326
+ model {
1327
+ name
1328
+ description
1329
+ }
1330
+ }
1331
+ }
1332
+ """
1333
+ )
1334
+ response = self.gql(
1335
+ mutation,
1336
+ variable_values={
1337
+ "name": self.format_project(project),
1338
+ "entity": entity or self.settings("entity"),
1339
+ "description": description,
1340
+ "id": id,
1341
+ },
1342
+ )
1343
+ # TODO(jhr): Commenting out 'repo' field for cling, add back
1344
+ # 'description': description, 'repo': self.git.remote_url, 'id': id})
1345
+ result: Dict[str, Any] = response["upsertModel"]["model"]
1346
+ return result
1347
+
1348
+ @normalize_exceptions
1349
+ def entity_is_team(self, entity: str) -> bool:
1350
+ query = gql(
1351
+ """
1352
+ query EntityIsTeam($entity: String!) {
1353
+ entity(name: $entity) {
1354
+ id
1355
+ isTeam
1356
+ }
1357
+ }
1358
+ """
1359
+ )
1360
+ variable_values = {
1361
+ "entity": entity,
1362
+ }
1363
+
1364
+ res = self.gql(query, variable_values)
1365
+ if res.get("entity") is None:
1366
+ raise Exception(
1367
+ f"Error fetching entity {entity} "
1368
+ "check that you have access to this entity"
1369
+ )
1370
+
1371
+ is_team: bool = res["entity"]["isTeam"]
1372
+ return is_team
1373
+
1374
+ @normalize_exceptions
1375
+ def get_project_run_queues(self, entity: str, project: str) -> List[Dict[str, str]]:
1376
+ query = gql(
1377
+ """
1378
+ query ProjectRunQueues($entity: String!, $projectName: String!){
1379
+ project(entityName: $entity, name: $projectName) {
1380
+ runQueues {
1381
+ id
1382
+ name
1383
+ createdBy
1384
+ access
1385
+ }
1386
+ }
1387
+ }
1388
+ """
1389
+ )
1390
+ variable_values = {
1391
+ "projectName": project,
1392
+ "entity": entity,
1393
+ }
1394
+
1395
+ res = self.gql(query, variable_values)
1396
+ if res.get("project") is None:
1397
+ # circular dependency: (LAUNCH_DEFAULT_PROJECT = model-registry)
1398
+ if project == "model-registry":
1399
+ msg = (
1400
+ f"Error fetching run queues for {entity} "
1401
+ "check that you have access to this entity and project"
1402
+ )
1403
+ else:
1404
+ msg = (
1405
+ f"Error fetching run queues for {entity}/{project} "
1406
+ "check that you have access to this entity and project"
1407
+ )
1408
+
1409
+ raise Exception(msg)
1410
+
1411
+ project_run_queues: List[Dict[str, str]] = res["project"]["runQueues"]
1412
+ return project_run_queues
1413
+
1414
+ @normalize_exceptions
1415
+ def create_default_resource_config(
1416
+ self,
1417
+ entity: str,
1418
+ resource: str,
1419
+ config: str,
1420
+ template_variables: Optional[Dict[str, Union[float, int, str]]],
1421
+ ) -> Optional[Dict[str, Any]]:
1422
+ if not self.create_default_resource_config_introspection():
1423
+ raise Exception()
1424
+ supports_template_vars, _ = self.push_to_run_queue_introspection()
1425
+
1426
+ mutation_params = """
1427
+ $entityName: String!,
1428
+ $resource: String!,
1429
+ $config: JSONString!
1430
+ """
1431
+ mutation_inputs = """
1432
+ entityName: $entityName,
1433
+ resource: $resource,
1434
+ config: $config
1435
+ """
1436
+
1437
+ if supports_template_vars:
1438
+ mutation_params += ", $templateVariables: JSONString"
1439
+ mutation_inputs += ", templateVariables: $templateVariables"
1440
+ else:
1441
+ if template_variables is not None:
1442
+ raise UnsupportedError(
1443
+ "server does not support template variables, please update server instance to >=0.46"
1444
+ )
1445
+
1446
+ variable_values = {
1447
+ "entityName": entity,
1448
+ "resource": resource,
1449
+ "config": config,
1450
+ }
1451
+ if supports_template_vars:
1452
+ if template_variables is not None:
1453
+ variable_values["templateVariables"] = json.dumps(template_variables)
1454
+ else:
1455
+ variable_values["templateVariables"] = "{}"
1456
+
1457
+ query = gql(
1458
+ f"""
1459
+ mutation createDefaultResourceConfig(
1460
+ {mutation_params}
1461
+ ) {{
1462
+ createDefaultResourceConfig(
1463
+ input: {{
1464
+ {mutation_inputs}
1465
+ }}
1466
+ ) {{
1467
+ defaultResourceConfigID
1468
+ success
1469
+ }}
1470
+ }}
1471
+ """
1472
+ )
1473
+
1474
+ result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[
1475
+ "createDefaultResourceConfig"
1476
+ ]
1477
+ return result
1478
+
1479
+ @normalize_exceptions
1480
+ def create_run_queue(
1481
+ self,
1482
+ entity: str,
1483
+ project: str,
1484
+ queue_name: str,
1485
+ access: str,
1486
+ prioritization_mode: Optional[str] = None,
1487
+ config_id: Optional[str] = None,
1488
+ ) -> Optional[Dict[str, Any]]:
1489
+ (
1490
+ create_run_queue,
1491
+ supports_drc,
1492
+ supports_prioritization,
1493
+ ) = self.create_run_queue_introspection()
1494
+ if not create_run_queue:
1495
+ raise UnsupportedError(
1496
+ "run queue creation is not supported by this version of "
1497
+ "wandb server. Consider updating to the latest version."
1498
+ )
1499
+ if not supports_drc and config_id is not None:
1500
+ raise UnsupportedError(
1501
+ "default resource configurations are not supported by this version "
1502
+ "of wandb server. Consider updating to the latest version."
1503
+ )
1504
+ if not supports_prioritization and prioritization_mode is not None:
1505
+ raise UnsupportedError(
1506
+ "launch prioritization is not supported by this version of "
1507
+ "wandb server. Consider updating to the latest version."
1508
+ )
1509
+
1510
+ if supports_prioritization:
1511
+ query = gql(
1512
+ """
1513
+ mutation createRunQueue(
1514
+ $entity: String!,
1515
+ $project: String!,
1516
+ $queueName: String!,
1517
+ $access: RunQueueAccessType!,
1518
+ $prioritizationMode: RunQueuePrioritizationMode,
1519
+ $defaultResourceConfigID: ID,
1520
+ ) {
1521
+ createRunQueue(
1522
+ input: {
1523
+ entityName: $entity,
1524
+ projectName: $project,
1525
+ queueName: $queueName,
1526
+ access: $access,
1527
+ prioritizationMode: $prioritizationMode
1528
+ defaultResourceConfigID: $defaultResourceConfigID
1529
+ }
1530
+ ) {
1531
+ success
1532
+ queueID
1533
+ }
1534
+ }
1535
+ """
1536
+ )
1537
+ variable_values = {
1538
+ "entity": entity,
1539
+ "project": project,
1540
+ "queueName": queue_name,
1541
+ "access": access,
1542
+ "prioritizationMode": prioritization_mode,
1543
+ "defaultResourceConfigID": config_id,
1544
+ }
1545
+ else:
1546
+ query = gql(
1547
+ """
1548
+ mutation createRunQueue(
1549
+ $entity: String!,
1550
+ $project: String!,
1551
+ $queueName: String!,
1552
+ $access: RunQueueAccessType!,
1553
+ $defaultResourceConfigID: ID,
1554
+ ) {
1555
+ createRunQueue(
1556
+ input: {
1557
+ entityName: $entity,
1558
+ projectName: $project,
1559
+ queueName: $queueName,
1560
+ access: $access,
1561
+ defaultResourceConfigID: $defaultResourceConfigID
1562
+ }
1563
+ ) {
1564
+ success
1565
+ queueID
1566
+ }
1567
+ }
1568
+ """
1569
+ )
1570
+ variable_values = {
1571
+ "entity": entity,
1572
+ "project": project,
1573
+ "queueName": queue_name,
1574
+ "access": access,
1575
+ "defaultResourceConfigID": config_id,
1576
+ }
1577
+
1578
+ result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[
1579
+ "createRunQueue"
1580
+ ]
1581
+ return result
1582
+
1583
+ @normalize_exceptions
1584
+ def push_to_run_queue_by_name(
1585
+ self,
1586
+ entity: str,
1587
+ project: str,
1588
+ queue_name: str,
1589
+ run_spec: str,
1590
+ template_variables: Optional[Dict[str, Union[int, float, str]]],
1591
+ priority: Optional[int] = None,
1592
+ ) -> Optional[Dict[str, Any]]:
1593
+ self.push_to_run_queue_introspection()
1594
+ """Queryless mutation, should be used before legacy fallback method."""
1595
+
1596
+ mutation_params = """
1597
+ $entityName: String!,
1598
+ $projectName: String!,
1599
+ $queueName: String!,
1600
+ $runSpec: JSONString!
1601
+ """
1602
+
1603
+ mutation_input = """
1604
+ entityName: $entityName,
1605
+ projectName: $projectName,
1606
+ queueName: $queueName,
1607
+ runSpec: $runSpec
1608
+ """
1609
+
1610
+ variables: Dict[str, Any] = {
1611
+ "entityName": entity,
1612
+ "projectName": project,
1613
+ "queueName": queue_name,
1614
+ "runSpec": run_spec,
1615
+ }
1616
+ if self.server_push_to_run_queue_supports_priority:
1617
+ if priority is not None:
1618
+ variables["priority"] = priority
1619
+ mutation_params += ", $priority: Int"
1620
+ mutation_input += ", priority: $priority"
1621
+ else:
1622
+ if priority is not None:
1623
+ raise UnsupportedError(
1624
+ "server does not support priority, please update server instance to >=0.46"
1625
+ )
1626
+
1627
+ if self.server_supports_template_variables:
1628
+ if template_variables is not None:
1629
+ variables.update(
1630
+ {"templateVariableValues": json.dumps(template_variables)}
1631
+ )
1632
+ mutation_params += ", $templateVariableValues: JSONString"
1633
+ mutation_input += ", templateVariableValues: $templateVariableValues"
1634
+ else:
1635
+ if template_variables is not None:
1636
+ raise UnsupportedError(
1637
+ "server does not support template variables, please update server instance to >=0.46"
1638
+ )
1639
+
1640
+ mutation = gql(
1641
+ f"""
1642
+ mutation pushToRunQueueByName(
1643
+ {mutation_params}
1644
+ ) {{
1645
+ pushToRunQueueByName(
1646
+ input: {{
1647
+ {mutation_input}
1648
+ }}
1649
+ ) {{
1650
+ runQueueItemId
1651
+ runSpec
1652
+ }}
1653
+ }}
1654
+ """
1655
+ )
1656
+
1657
+ try:
1658
+ result: Optional[Dict[str, Any]] = self.gql(
1659
+ mutation, variables, check_retry_fn=util.no_retry_4xx
1660
+ ).get("pushToRunQueueByName")
1661
+ if not result:
1662
+ return None
1663
+
1664
+ if result.get("runSpec"):
1665
+ run_spec = json.loads(str(result["runSpec"]))
1666
+ result["runSpec"] = run_spec
1667
+
1668
+ return result
1669
+ except Exception as e:
1670
+ if (
1671
+ 'Cannot query field "runSpec" on type "PushToRunQueueByNamePayload"'
1672
+ not in str(e)
1673
+ ):
1674
+ return None
1675
+
1676
+ mutation_no_runspec = gql(
1677
+ """
1678
+ mutation pushToRunQueueByName(
1679
+ $entityName: String!,
1680
+ $projectName: String!,
1681
+ $queueName: String!,
1682
+ $runSpec: JSONString!,
1683
+ ) {
1684
+ pushToRunQueueByName(
1685
+ input: {
1686
+ entityName: $entityName,
1687
+ projectName: $projectName,
1688
+ queueName: $queueName,
1689
+ runSpec: $runSpec
1690
+ }
1691
+ ) {
1692
+ runQueueItemId
1693
+ }
1694
+ }
1695
+ """
1696
+ )
1697
+
1698
+ try:
1699
+ result = self.gql(
1700
+ mutation_no_runspec, variables, check_retry_fn=util.no_retry_4xx
1701
+ ).get("pushToRunQueueByName")
1702
+ except Exception:
1703
+ result = None
1704
+
1705
+ return result
1706
+
1707
+ @normalize_exceptions
1708
+ def push_to_run_queue(
1709
+ self,
1710
+ queue_name: str,
1711
+ launch_spec: Dict[str, str],
1712
+ template_variables: Optional[dict],
1713
+ project_queue: str,
1714
+ priority: Optional[int] = None,
1715
+ ) -> Optional[Dict[str, Any]]:
1716
+ self.push_to_run_queue_introspection()
1717
+ entity = launch_spec.get("queue_entity") or launch_spec["entity"]
1718
+ run_spec = json.dumps(launch_spec)
1719
+
1720
+ push_result = self.push_to_run_queue_by_name(
1721
+ entity, project_queue, queue_name, run_spec, template_variables, priority
1722
+ )
1723
+
1724
+ if push_result:
1725
+ return push_result
1726
+
1727
+ if priority is not None:
1728
+ # Cannot proceed with legacy method if priority is set
1729
+ return None
1730
+
1731
+ """ Legacy Method """
1732
+ queues_found = self.get_project_run_queues(entity, project_queue)
1733
+ matching_queues = [
1734
+ q
1735
+ for q in queues_found
1736
+ if q["name"] == queue_name
1737
+ # ensure user has access to queue
1738
+ and (
1739
+ # TODO: User created queues in the UI have USER access
1740
+ q["access"] in ["PROJECT", "USER"]
1741
+ or q["createdBy"] == self.default_entity
1742
+ )
1743
+ ]
1744
+ if not matching_queues:
1745
+ # in the case of a missing default queue. create it
1746
+ if queue_name == "default":
1747
+ wandb.termlog(
1748
+ f"No default queue existing for entity: {entity} in project: {project_queue}, creating one."
1749
+ )
1750
+ res = self.create_run_queue(
1751
+ launch_spec["entity"],
1752
+ project_queue,
1753
+ queue_name,
1754
+ access="PROJECT",
1755
+ )
1756
+
1757
+ if res is None or res.get("queueID") is None:
1758
+ wandb.termerror(
1759
+ f"Unable to create default queue for entity: {entity} on project: {project_queue}. Run could not be added to a queue"
1760
+ )
1761
+ return None
1762
+ queue_id = res["queueID"]
1763
+
1764
+ else:
1765
+ if project_queue == "model-registry":
1766
+ _msg = f"Unable to push to run queue {queue_name}. Queue not found."
1767
+ else:
1768
+ _msg = f"Unable to push to run queue {project_queue}/{queue_name}. Queue not found."
1769
+ wandb.termwarn(_msg)
1770
+ return None
1771
+ elif len(matching_queues) > 1:
1772
+ wandb.termerror(
1773
+ f"Unable to push to run queue {queue_name}. More than one queue found with this name."
1774
+ )
1775
+ return None
1776
+ else:
1777
+ queue_id = matching_queues[0]["id"]
1778
+ spec_json = json.dumps(launch_spec)
1779
+ variables = {"queueID": queue_id, "runSpec": spec_json}
1780
+
1781
+ mutation_params = """
1782
+ $queueID: ID!,
1783
+ $runSpec: JSONString!
1784
+ """
1785
+ mutation_input = """
1786
+ queueID: $queueID,
1787
+ runSpec: $runSpec
1788
+ """
1789
+ if self.server_supports_template_variables:
1790
+ if template_variables is not None:
1791
+ mutation_params += ", $templateVariableValues: JSONString"
1792
+ mutation_input += ", templateVariableValues: $templateVariableValues"
1793
+ variables.update(
1794
+ {"templateVariableValues": json.dumps(template_variables)}
1795
+ )
1796
+ else:
1797
+ if template_variables is not None:
1798
+ raise UnsupportedError(
1799
+ "server does not support template variables, please update server instance to >=0.46"
1800
+ )
1801
+
1802
+ mutation = gql(
1803
+ f"""
1804
+ mutation pushToRunQueue(
1805
+ {mutation_params}
1806
+ ) {{
1807
+ pushToRunQueue(
1808
+ input: {{{mutation_input}}}
1809
+ ) {{
1810
+ runQueueItemId
1811
+ }}
1812
+ }}
1813
+ """
1814
+ )
1815
+
1816
+ response = self.gql(mutation, variable_values=variables)
1817
+ if not response.get("pushToRunQueue"):
1818
+ raise CommError(f"Error pushing run queue item to queue {queue_name}.")
1819
+
1820
+ result: Optional[Dict[str, Any]] = response["pushToRunQueue"]
1821
+ return result
1822
+
1823
+ @normalize_exceptions
1824
+ def pop_from_run_queue(
1825
+ self,
1826
+ queue_name: str,
1827
+ entity: Optional[str] = None,
1828
+ project: Optional[str] = None,
1829
+ agent_id: Optional[str] = None,
1830
+ ) -> Optional[Dict[str, Any]]:
1831
+ mutation = gql(
1832
+ """
1833
+ mutation popFromRunQueue($entity: String!, $project: String!, $queueName: String!, $launchAgentId: ID) {
1834
+ popFromRunQueue(input: {
1835
+ entityName: $entity,
1836
+ projectName: $project,
1837
+ queueName: $queueName,
1838
+ launchAgentId: $launchAgentId
1839
+ }) {
1840
+ runQueueItemId
1841
+ runSpec
1842
+ }
1843
+ }
1844
+ """
1845
+ )
1846
+ response = self.gql(
1847
+ mutation,
1848
+ variable_values={
1849
+ "entity": entity,
1850
+ "project": project,
1851
+ "queueName": queue_name,
1852
+ "launchAgentId": agent_id,
1853
+ },
1854
+ )
1855
+ result: Optional[Dict[str, Any]] = response["popFromRunQueue"]
1856
+ return result
1857
+
1858
+ @normalize_exceptions
1859
+ def ack_run_queue_item(self, item_id: str, run_id: Optional[str] = None) -> bool:
1860
+ mutation = gql(
1861
+ """
1862
+ mutation ackRunQueueItem($itemId: ID!, $runId: String!) {
1863
+ ackRunQueueItem(input: { runQueueItemId: $itemId, runName: $runId }) {
1864
+ success
1865
+ }
1866
+ }
1867
+ """
1868
+ )
1869
+ response = self.gql(
1870
+ mutation, variable_values={"itemId": item_id, "runId": str(run_id)}
1871
+ )
1872
+ if not response["ackRunQueueItem"]["success"]:
1873
+ raise CommError(
1874
+ "Error acking run queue item. Item may have already been acknowledged by another process"
1875
+ )
1876
+ result: bool = response["ackRunQueueItem"]["success"]
1877
+ return result
1878
+
1879
+ @normalize_exceptions
1880
+ def create_launch_agent_fields_introspection(self) -> List:
1881
+ if self.create_launch_agent_input_info:
1882
+ return self.create_launch_agent_input_info
1883
+ query_string = """
1884
+ query ProbeServerCreateLaunchAgentInput {
1885
+ CreateLaunchAgentInputInfoType: __type(name:"CreateLaunchAgentInput") {
1886
+ inputFields{
1887
+ name
1888
+ }
1889
+ }
1890
+ }
1891
+ """
1892
+
1893
+ query = gql(query_string)
1894
+ res = self.gql(query)
1895
+
1896
+ self.create_launch_agent_input_info = [
1897
+ field.get("name", "")
1898
+ for field in res.get("CreateLaunchAgentInputInfoType", {}).get(
1899
+ "inputFields", [{}]
1900
+ )
1901
+ ]
1902
+ return self.create_launch_agent_input_info
1903
+
1904
+ @normalize_exceptions
1905
+ def create_launch_agent(
1906
+ self,
1907
+ entity: str,
1908
+ project: str,
1909
+ queues: List[str],
1910
+ agent_config: Dict[str, Any],
1911
+ version: str,
1912
+ gorilla_agent_support: bool,
1913
+ ) -> dict:
1914
+ project_queues = self.get_project_run_queues(entity, project)
1915
+ if not project_queues:
1916
+ # create default queue if it doesn't already exist
1917
+ default = self.create_run_queue(
1918
+ entity, project, "default", access="PROJECT"
1919
+ )
1920
+ if default is None or default.get("queueID") is None:
1921
+ raise CommError(
1922
+ "Unable to create default queue for {}/{}. No queues for agent to poll".format(
1923
+ entity, project
1924
+ )
1925
+ )
1926
+ project_queues = [{"id": default["queueID"], "name": "default"}]
1927
+ polling_queue_ids = [
1928
+ q["id"] for q in project_queues if q["name"] in queues
1929
+ ] # filter to poll specified queues
1930
+ if len(polling_queue_ids) != len(queues):
1931
+ raise CommError(
1932
+ f"Could not start launch agent: Not all of requested queues ({', '.join(queues)}) found. "
1933
+ f"Available queues for this project: {','.join([q['name'] for q in project_queues])}"
1934
+ )
1935
+
1936
+ if not gorilla_agent_support:
1937
+ # if gorilla doesn't support launch agents, return a client-generated id
1938
+ return {
1939
+ "success": True,
1940
+ "launchAgentId": None,
1941
+ }
1942
+
1943
+ hostname = socket.gethostname()
1944
+
1945
+ variable_values = {
1946
+ "entity": entity,
1947
+ "project": project,
1948
+ "queues": polling_queue_ids,
1949
+ "hostname": hostname,
1950
+ }
1951
+
1952
+ mutation_params = """
1953
+ $entity: String!,
1954
+ $project: String!,
1955
+ $queues: [ID!]!,
1956
+ $hostname: String!
1957
+ """
1958
+
1959
+ mutation_input = """
1960
+ entityName: $entity,
1961
+ projectName: $project,
1962
+ runQueues: $queues,
1963
+ hostname: $hostname
1964
+ """
1965
+
1966
+ if "agentConfig" in self.create_launch_agent_fields_introspection():
1967
+ variable_values["agentConfig"] = json.dumps(agent_config)
1968
+ mutation_params += ", $agentConfig: JSONString"
1969
+ mutation_input += ", agentConfig: $agentConfig"
1970
+ if "version" in self.create_launch_agent_fields_introspection():
1971
+ variable_values["version"] = version
1972
+ mutation_params += ", $version: String"
1973
+ mutation_input += ", version: $version"
1974
+
1975
+ mutation = gql(
1976
+ f"""
1977
+ mutation createLaunchAgent(
1978
+ {mutation_params}
1979
+ ) {{
1980
+ createLaunchAgent(
1981
+ input: {{
1982
+ {mutation_input}
1983
+ }}
1984
+ ) {{
1985
+ launchAgentId
1986
+ }}
1987
+ }}
1988
+ """
1989
+ )
1990
+ result: dict = self.gql(mutation, variable_values)["createLaunchAgent"]
1991
+ return result
1992
+
1993
+ @normalize_exceptions
1994
+ def update_launch_agent_status(
1995
+ self,
1996
+ agent_id: str,
1997
+ status: str,
1998
+ gorilla_agent_support: bool,
1999
+ ) -> dict:
2000
+ if not gorilla_agent_support:
2001
+ # if gorilla doesn't support launch agents, this is a no-op
2002
+ return {
2003
+ "success": True,
2004
+ }
2005
+
2006
+ mutation = gql(
2007
+ """
2008
+ mutation updateLaunchAgent($agentId: ID!, $agentStatus: String){
2009
+ updateLaunchAgent(
2010
+ input: {
2011
+ launchAgentId: $agentId
2012
+ agentStatus: $agentStatus
2013
+ }
2014
+ ) {
2015
+ success
2016
+ }
2017
+ }
2018
+ """
2019
+ )
2020
+ variable_values = {
2021
+ "agentId": agent_id,
2022
+ "agentStatus": status,
2023
+ }
2024
+ result: dict = self.gql(mutation, variable_values)["updateLaunchAgent"]
2025
+ return result
2026
+
2027
+ @normalize_exceptions
2028
+ def get_launch_agent(self, agent_id: str, gorilla_agent_support: bool) -> dict:
2029
+ if not gorilla_agent_support:
2030
+ return {
2031
+ "id": None,
2032
+ "name": "",
2033
+ "stopPolling": False,
2034
+ }
2035
+ query = gql(
2036
+ """
2037
+ query LaunchAgent($agentId: ID!) {
2038
+ launchAgent(id: $agentId) {
2039
+ id
2040
+ name
2041
+ runQueues
2042
+ hostname
2043
+ agentStatus
2044
+ stopPolling
2045
+ heartbeatAt
2046
+ }
2047
+ }
2048
+ """
2049
+ )
2050
+ variable_values = {
2051
+ "agentId": agent_id,
2052
+ }
2053
+ result: dict = self.gql(query, variable_values)["launchAgent"]
2054
+ return result
2055
+
2056
+ @normalize_exceptions
2057
+ def upsert_run(
2058
+ self,
2059
+ id: Optional[str] = None,
2060
+ name: Optional[str] = None,
2061
+ project: Optional[str] = None,
2062
+ host: Optional[str] = None,
2063
+ group: Optional[str] = None,
2064
+ tags: Optional[List[str]] = None,
2065
+ config: Optional[dict] = None,
2066
+ description: Optional[str] = None,
2067
+ entity: Optional[str] = None,
2068
+ state: Optional[str] = None,
2069
+ display_name: Optional[str] = None,
2070
+ notes: Optional[str] = None,
2071
+ repo: Optional[str] = None,
2072
+ job_type: Optional[str] = None,
2073
+ program_path: Optional[str] = None,
2074
+ commit: Optional[str] = None,
2075
+ sweep_name: Optional[str] = None,
2076
+ summary_metrics: Optional[str] = None,
2077
+ num_retries: Optional[int] = None,
2078
+ ) -> Tuple[dict, bool, Optional[List]]:
2079
+ """Update a run.
2080
+
2081
+ Arguments:
2082
+ id (str, optional): The existing run to update
2083
+ name (str, optional): The name of the run to create
2084
+ group (str, optional): Name of the group this run is a part of
2085
+ project (str, optional): The name of the project
2086
+ host (str, optional): The name of the host
2087
+ tags (list, optional): A list of tags to apply to the run
2088
+ config (dict, optional): The latest config params
2089
+ description (str, optional): A description of this project
2090
+ entity (str, optional): The entity to scope this project to.
2091
+ display_name (str, optional): The display name of this project
2092
+ notes (str, optional): Notes about this run
2093
+ repo (str, optional): Url of the program's repository.
2094
+ state (str, optional): State of the program.
2095
+ job_type (str, optional): Type of job, e.g 'train'.
2096
+ program_path (str, optional): Path to the program.
2097
+ commit (str, optional): The Git SHA to associate the run with
2098
+ sweep_name (str, optional): The name of the sweep this run is a part of
2099
+ summary_metrics (str, optional): The JSON summary metrics
2100
+ num_retries (int, optional): Number of retries
2101
+ """
2102
+ query_string = """
2103
+ mutation UpsertBucket(
2104
+ $id: String,
2105
+ $name: String,
2106
+ $project: String,
2107
+ $entity: String,
2108
+ $groupName: String,
2109
+ $description: String,
2110
+ $displayName: String,
2111
+ $notes: String,
2112
+ $commit: String,
2113
+ $config: JSONString,
2114
+ $host: String,
2115
+ $debug: Boolean,
2116
+ $program: String,
2117
+ $repo: String,
2118
+ $jobType: String,
2119
+ $state: String,
2120
+ $sweep: String,
2121
+ $tags: [String!],
2122
+ $summaryMetrics: JSONString,
2123
+ ) {
2124
+ upsertBucket(input: {
2125
+ id: $id,
2126
+ name: $name,
2127
+ groupName: $groupName,
2128
+ modelName: $project,
2129
+ entityName: $entity,
2130
+ description: $description,
2131
+ displayName: $displayName,
2132
+ notes: $notes,
2133
+ config: $config,
2134
+ commit: $commit,
2135
+ host: $host,
2136
+ debug: $debug,
2137
+ jobProgram: $program,
2138
+ jobRepo: $repo,
2139
+ jobType: $jobType,
2140
+ state: $state,
2141
+ sweep: $sweep,
2142
+ tags: $tags,
2143
+ summaryMetrics: $summaryMetrics,
2144
+ }) {
2145
+ bucket {
2146
+ id
2147
+ name
2148
+ displayName
2149
+ description
2150
+ config
2151
+ sweepName
2152
+ project {
2153
+ id
2154
+ name
2155
+ entity {
2156
+ id
2157
+ name
2158
+ }
2159
+ }
2160
+ historyLineCount
2161
+ }
2162
+ inserted
2163
+ _Server_Settings_
2164
+ }
2165
+ }
2166
+ """
2167
+ self.server_settings_introspection()
2168
+
2169
+ server_settings_string = (
2170
+ """
2171
+ serverSettings {
2172
+ serverMessages{
2173
+ utfText
2174
+ plainText
2175
+ htmlText
2176
+ messageType
2177
+ messageLevel
2178
+ }
2179
+ }
2180
+ """
2181
+ if self._server_settings_type
2182
+ else ""
2183
+ )
2184
+
2185
+ query_string = query_string.replace("_Server_Settings_", server_settings_string)
2186
+ mutation = gql(query_string)
2187
+ config_str = json.dumps(config) if config else None
2188
+ if not description or description.isspace():
2189
+ description = None
2190
+
2191
+ kwargs = {}
2192
+ if num_retries is not None:
2193
+ kwargs["num_retries"] = num_retries
2194
+
2195
+ variable_values = {
2196
+ "id": id,
2197
+ "entity": entity or self.settings("entity"),
2198
+ "name": name,
2199
+ "project": project or util.auto_project_name(program_path),
2200
+ "groupName": group,
2201
+ "tags": tags,
2202
+ "description": description,
2203
+ "config": config_str,
2204
+ "commit": commit,
2205
+ "displayName": display_name,
2206
+ "notes": notes,
2207
+ "host": None if self.settings().get("anonymous") == "true" else host,
2208
+ "debug": env.is_debug(env=self._environ),
2209
+ "repo": repo,
2210
+ "program": program_path,
2211
+ "jobType": job_type,
2212
+ "state": state,
2213
+ "sweep": sweep_name,
2214
+ "summaryMetrics": summary_metrics,
2215
+ }
2216
+
2217
+ # retry conflict errors for 2 minutes, default to no_auth_retry
2218
+ check_retry_fn = util.make_check_retry_fn(
2219
+ check_fn=util.check_retry_conflict_or_gone,
2220
+ check_timedelta=datetime.timedelta(minutes=2),
2221
+ fallback_retry_fn=util.no_retry_auth,
2222
+ )
2223
+
2224
+ response = self.gql(
2225
+ mutation,
2226
+ variable_values=variable_values,
2227
+ check_retry_fn=check_retry_fn,
2228
+ **kwargs,
2229
+ )
2230
+
2231
+ run_obj: Dict[str, Dict[str, Dict[str, str]]] = response["upsertBucket"][
2232
+ "bucket"
2233
+ ]
2234
+ project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {})
2235
+ if project_obj:
2236
+ self.set_setting("project", project_obj["name"])
2237
+ entity_obj = project_obj.get("entity", {})
2238
+ if entity_obj:
2239
+ self.set_setting("entity", entity_obj["name"])
2240
+
2241
+ server_messages = None
2242
+ if self._server_settings_type:
2243
+ server_messages = (
2244
+ response["upsertBucket"]
2245
+ .get("serverSettings", {})
2246
+ .get("serverMessages", [])
2247
+ )
2248
+
2249
+ return (
2250
+ response["upsertBucket"]["bucket"],
2251
+ response["upsertBucket"]["inserted"],
2252
+ server_messages,
2253
+ )
2254
+
2255
+ @normalize_exceptions
2256
+ def rewind_run(
2257
+ self,
2258
+ run_name: str,
2259
+ metric_name: str,
2260
+ metric_value: float,
2261
+ program_path: Optional[str] = None,
2262
+ entity: Optional[str] = None,
2263
+ project: Optional[str] = None,
2264
+ num_retries: Optional[int] = None,
2265
+ ) -> dict:
2266
+ """Rewinds a run to a previous state.
2267
+
2268
+ Arguments:
2269
+ run_name (str): The name of the run to rewind
2270
+ metric_name (str): The name of the metric to rewind to
2271
+ metric_value (float): The value of the metric to rewind to
2272
+ program_path (str, optional): Path to the program
2273
+ entity (str, optional): The entity to scope this project to
2274
+ project (str, optional): The name of the project
2275
+ num_retries (int, optional): Number of retries
2276
+
2277
+ Returns:
2278
+ A dict with the rewound run
2279
+
2280
+ {
2281
+ "id": "run_id",
2282
+ "name": "run_name",
2283
+ "displayName": "run_display_name",
2284
+ "description": "run_description",
2285
+ "config": "stringified_run_config_json",
2286
+ "sweepName": "run_sweep_name",
2287
+ "project": {
2288
+ "id": "project_id",
2289
+ "name": "project_name",
2290
+ "entity": {
2291
+ "id": "entity_id",
2292
+ "name": "entity_name"
2293
+ }
2294
+ },
2295
+ "historyLineCount": 100,
2296
+ }
2297
+ """
2298
+ query_string = """
2299
+ mutation RewindRun($runName: String!, $entity: String, $project: String, $metricName: String!, $metricValue: Float!) {
2300
+ rewindRun(input: {runName: $runName, entityName: $entity, projectName: $project, metricName: $metricName, metricValue: $metricValue}) {
2301
+ rewoundRun {
2302
+ id
2303
+ name
2304
+ displayName
2305
+ description
2306
+ config
2307
+ sweepName
2308
+ project {
2309
+ id
2310
+ name
2311
+ entity {
2312
+ id
2313
+ name
2314
+ }
2315
+ }
2316
+ historyLineCount
2317
+ }
2318
+ }
2319
+ }
2320
+ """
2321
+
2322
+ mutation = gql(query_string)
2323
+
2324
+ kwargs = {}
2325
+ if num_retries is not None:
2326
+ kwargs["num_retries"] = num_retries
2327
+
2328
+ variable_values = {
2329
+ "runName": run_name,
2330
+ "entity": entity or self.settings("entity"),
2331
+ "project": project or util.auto_project_name(program_path),
2332
+ "metricName": metric_name,
2333
+ "metricValue": metric_value,
2334
+ }
2335
+
2336
+ # retry conflict errors for 2 minutes, default to no_auth_retry
2337
+ check_retry_fn = util.make_check_retry_fn(
2338
+ check_fn=util.check_retry_conflict_or_gone,
2339
+ check_timedelta=datetime.timedelta(minutes=2),
2340
+ fallback_retry_fn=util.no_retry_auth,
2341
+ )
2342
+
2343
+ response = self.gql(
2344
+ mutation,
2345
+ variable_values=variable_values,
2346
+ check_retry_fn=check_retry_fn,
2347
+ **kwargs,
2348
+ )
2349
+
2350
+ run_obj: Dict[str, Dict[str, Dict[str, str]]] = response.get(
2351
+ "rewindRun", {}
2352
+ ).get("rewoundRun", {})
2353
+ project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {})
2354
+ if project_obj:
2355
+ self.set_setting("project", project_obj["name"])
2356
+ entity_obj = project_obj.get("entity", {})
2357
+ if entity_obj:
2358
+ self.set_setting("entity", entity_obj["name"])
2359
+
2360
+ return run_obj
2361
+
2362
+ @normalize_exceptions
2363
+ def get_run_info(
2364
+ self,
2365
+ entity: str,
2366
+ project: str,
2367
+ name: str,
2368
+ ) -> dict:
2369
+ query = gql(
2370
+ """
2371
+ query RunInfo($project: String!, $entity: String!, $name: String!) {
2372
+ project(name: $project, entityName: $entity) {
2373
+ run(name: $name) {
2374
+ runInfo {
2375
+ program
2376
+ args
2377
+ os
2378
+ python
2379
+ colab
2380
+ executable
2381
+ codeSaved
2382
+ cpuCount
2383
+ gpuCount
2384
+ gpu
2385
+ git {
2386
+ remote
2387
+ commit
2388
+ }
2389
+ }
2390
+ }
2391
+ }
2392
+ }
2393
+ """
2394
+ )
2395
+ variable_values = {"project": project, "entity": entity, "name": name}
2396
+ res = self.gql(query, variable_values)
2397
+ if res.get("project") is None:
2398
+ raise CommError(
2399
+ "Error fetching run info for {}/{}/{}. Check that this project exists and you have access to this entity and project".format(
2400
+ entity, project, name
2401
+ )
2402
+ )
2403
+ elif res["project"].get("run") is None:
2404
+ raise CommError(
2405
+ "Error fetching run info for {}/{}/{}. Check that this run id exists".format(
2406
+ entity, project, name
2407
+ )
2408
+ )
2409
+ run_info: dict = res["project"]["run"]["runInfo"]
2410
+ return run_info
2411
+
2412
+ @normalize_exceptions
2413
+ def get_run_state(self, entity: str, project: str, name: str) -> str:
2414
+ query = gql(
2415
+ """
2416
+ query RunState(
2417
+ $project: String!,
2418
+ $entity: String!,
2419
+ $name: String!) {
2420
+ project(name: $project, entityName: $entity) {
2421
+ run(name: $name) {
2422
+ state
2423
+ }
2424
+ }
2425
+ }
2426
+ """
2427
+ )
2428
+ variable_values = {
2429
+ "project": project,
2430
+ "entity": entity,
2431
+ "name": name,
2432
+ }
2433
+ res = self.gql(query, variable_values)
2434
+ if res.get("project") is None or res["project"].get("run") is None:
2435
+ raise CommError(f"Error fetching run state for {entity}/{project}/{name}.")
2436
+ run_state: str = res["project"]["run"]["state"]
2437
+ return run_state
2438
+
2439
+ @normalize_exceptions
2440
+ def create_run_files_introspection(self) -> bool:
2441
+ _, _, mutations = self.server_info_introspection()
2442
+ return "createRunFiles" in mutations
2443
+
2444
+ @normalize_exceptions
2445
+ def upload_urls(
2446
+ self,
2447
+ project: str,
2448
+ files: Union[List[str], Dict[str, IO]],
2449
+ run: Optional[str] = None,
2450
+ entity: Optional[str] = None,
2451
+ description: Optional[str] = None,
2452
+ ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]:
2453
+ """Generate temporary resumable upload urls.
2454
+
2455
+ Arguments:
2456
+ project (str): The project to download
2457
+ files (list or dict): The filenames to upload
2458
+ run (str, optional): The run to upload to
2459
+ entity (str, optional): The entity to scope this project to.
2460
+ description (str, optional): description
2461
+
2462
+ Returns:
2463
+ (run_id, upload_headers, file_info)
2464
+ run_id: id of run we uploaded files to
2465
+ upload_headers: A list of headers to use when uploading files.
2466
+ file_info: A dict of filenames and urls.
2467
+ {
2468
+ "run_id": "run_id",
2469
+ "upload_headers": [""],
2470
+ "file_info": [
2471
+ { "weights.h5": { "uploadUrl": "https://weights.url" } },
2472
+ { "model.json": { "uploadUrl": "https://model.json" } }
2473
+ ]
2474
+ }
2475
+ """
2476
+ run_name = run or self.current_run_id
2477
+ assert run_name, "run must be specified"
2478
+ entity = entity or self.settings("entity")
2479
+ assert entity, "entity must be specified"
2480
+
2481
+ has_create_run_files_mutation = self.create_run_files_introspection()
2482
+ if not has_create_run_files_mutation:
2483
+ return self.legacy_upload_urls(project, files, run, entity, description)
2484
+
2485
+ query = gql(
2486
+ """
2487
+ mutation CreateRunFiles($entity: String!, $project: String!, $run: String!, $files: [String!]!) {
2488
+ createRunFiles(input: {entityName: $entity, projectName: $project, runName: $run, files: $files}) {
2489
+ runID
2490
+ uploadHeaders
2491
+ files {
2492
+ name
2493
+ uploadUrl
2494
+ }
2495
+ }
2496
+ }
2497
+ """
2498
+ )
2499
+
2500
+ query_result = self.gql(
2501
+ query,
2502
+ variable_values={
2503
+ "project": project,
2504
+ "run": run_name,
2505
+ "entity": entity,
2506
+ "files": [file for file in files],
2507
+ },
2508
+ )
2509
+
2510
+ result = query_result["createRunFiles"]
2511
+ run_id = result["runID"]
2512
+ if not run_id:
2513
+ raise CommError(
2514
+ f"Error uploading files to {entity}/{project}/{run_name}. Check that this project exists and you have access to this entity and project"
2515
+ )
2516
+ file_name_urls = {file["name"]: file for file in result["files"]}
2517
+ return run_id, result["uploadHeaders"], file_name_urls
2518
+
2519
+ def legacy_upload_urls(
2520
+ self,
2521
+ project: str,
2522
+ files: Union[List[str], Dict[str, IO]],
2523
+ run: Optional[str] = None,
2524
+ entity: Optional[str] = None,
2525
+ description: Optional[str] = None,
2526
+ ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]:
2527
+ """Generate temporary resumable upload urls.
2528
+
2529
+ A new mutation createRunFiles was introduced after 0.15.4.
2530
+ This function is used to support older versions.
2531
+ """
2532
+ query = gql(
2533
+ """
2534
+ query RunUploadUrls($name: String!, $files: [String]!, $entity: String, $run: String!, $description: String) {
2535
+ model(name: $name, entityName: $entity) {
2536
+ bucket(name: $run, desc: $description) {
2537
+ id
2538
+ files(names: $files) {
2539
+ uploadHeaders
2540
+ edges {
2541
+ node {
2542
+ name
2543
+ url(upload: true)
2544
+ updatedAt
2545
+ }
2546
+ }
2547
+ }
2548
+ }
2549
+ }
2550
+ }
2551
+ """
2552
+ )
2553
+ run_id = run or self.current_run_id
2554
+ assert run_id, "run must be specified"
2555
+ entity = entity or self.settings("entity")
2556
+ query_result = self.gql(
2557
+ query,
2558
+ variable_values={
2559
+ "name": project,
2560
+ "run": run_id,
2561
+ "entity": entity,
2562
+ "files": [file for file in files],
2563
+ "description": description,
2564
+ },
2565
+ )
2566
+
2567
+ run_obj = query_result["model"]["bucket"]
2568
+ if run_obj:
2569
+ for file_node in run_obj["files"]["edges"]:
2570
+ file = file_node["node"]
2571
+ # we previously used "url" field but now use "uploadUrl"
2572
+ # replace the "url" field with "uploadUrl for downstream compatibility
2573
+ if "url" in file and "uploadUrl" not in file:
2574
+ file["uploadUrl"] = file.pop("url")
2575
+
2576
+ result = {
2577
+ file["name"]: file for file in self._flatten_edges(run_obj["files"])
2578
+ }
2579
+ return run_obj["id"], run_obj["files"]["uploadHeaders"], result
2580
+ else:
2581
+ raise CommError(f"Run does not exist {entity}/{project}/{run_id}.")
2582
+
2583
+ @normalize_exceptions
2584
+ def download_urls(
2585
+ self,
2586
+ project: str,
2587
+ run: Optional[str] = None,
2588
+ entity: Optional[str] = None,
2589
+ ) -> Dict[str, Dict[str, str]]:
2590
+ """Generate download urls.
2591
+
2592
+ Arguments:
2593
+ project (str): The project to download
2594
+ run (str): The run to upload to
2595
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
2596
+
2597
+ Returns:
2598
+ A dict of extensions and urls
2599
+
2600
+ {
2601
+ 'weights.h5': { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' },
2602
+ 'model.json': { "url": "https://model.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
2603
+ }
2604
+ """
2605
+ query = gql(
2606
+ """
2607
+ query RunDownloadUrls($name: String!, $entity: String, $run: String!) {
2608
+ model(name: $name, entityName: $entity) {
2609
+ bucket(name: $run) {
2610
+ files {
2611
+ edges {
2612
+ node {
2613
+ name
2614
+ url
2615
+ md5
2616
+ updatedAt
2617
+ }
2618
+ }
2619
+ }
2620
+ }
2621
+ }
2622
+ }
2623
+ """
2624
+ )
2625
+ run = run or self.current_run_id
2626
+ assert run, "run must be specified"
2627
+ entity = entity or self.settings("entity")
2628
+ query_result = self.gql(
2629
+ query,
2630
+ variable_values={
2631
+ "name": project,
2632
+ "run": run,
2633
+ "entity": entity,
2634
+ },
2635
+ )
2636
+ if query_result["model"] is None:
2637
+ raise CommError(f"Run does not exist {entity}/{project}/{run}.")
2638
+ files = self._flatten_edges(query_result["model"]["bucket"]["files"])
2639
+ return {file["name"]: file for file in files if file}
2640
+
2641
+ @normalize_exceptions
2642
+ def download_url(
2643
+ self,
2644
+ project: str,
2645
+ file_name: str,
2646
+ run: Optional[str] = None,
2647
+ entity: Optional[str] = None,
2648
+ ) -> Optional[Dict[str, str]]:
2649
+ """Generate download urls.
2650
+
2651
+ Arguments:
2652
+ project (str): The project to download
2653
+ file_name (str): The name of the file to download
2654
+ run (str): The run to upload to
2655
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
2656
+
2657
+ Returns:
2658
+ A dict of extensions and urls
2659
+
2660
+ { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
2661
+
2662
+ """
2663
+ query = gql(
2664
+ """
2665
+ query RunDownloadUrl($name: String!, $fileName: String!, $entity: String, $run: String!) {
2666
+ model(name: $name, entityName: $entity) {
2667
+ bucket(name: $run) {
2668
+ files(names: [$fileName]) {
2669
+ edges {
2670
+ node {
2671
+ name
2672
+ url
2673
+ md5
2674
+ updatedAt
2675
+ }
2676
+ }
2677
+ }
2678
+ }
2679
+ }
2680
+ }
2681
+ """
2682
+ )
2683
+ run = run or self.current_run_id
2684
+ assert run, "run must be specified"
2685
+ query_result = self.gql(
2686
+ query,
2687
+ variable_values={
2688
+ "name": project,
2689
+ "run": run,
2690
+ "fileName": file_name,
2691
+ "entity": entity or self.settings("entity"),
2692
+ },
2693
+ )
2694
+ if query_result["model"]:
2695
+ files = self._flatten_edges(query_result["model"]["bucket"]["files"])
2696
+ return files[0] if len(files) > 0 and files[0].get("updatedAt") else None
2697
+ else:
2698
+ return None
2699
+
2700
+ @normalize_exceptions
2701
+ def download_file(self, url: str) -> Tuple[int, requests.Response]:
2702
+ """Initiate a streaming download.
2703
+
2704
+ Arguments:
2705
+ url (str): The url to download
2706
+
2707
+ Returns:
2708
+ A tuple of the content length and the streaming response
2709
+ """
2710
+ check_httpclient_logger_handler()
2711
+
2712
+ http_headers = _thread_local_api_settings.headers or {}
2713
+
2714
+ auth = None
2715
+ if self.access_token is not None:
2716
+ http_headers["Authorization"] = f"Bearer {self.access_token}"
2717
+ elif _thread_local_api_settings.cookies is None:
2718
+ auth = ("api", self.api_key or "")
2719
+
2720
+ response = requests.get(
2721
+ url,
2722
+ auth=auth,
2723
+ cookies=_thread_local_api_settings.cookies or {},
2724
+ headers=http_headers,
2725
+ stream=True,
2726
+ )
2727
+ response.raise_for_status()
2728
+ return int(response.headers.get("content-length", 0)), response
2729
+
2730
+ @normalize_exceptions
2731
+ def download_write_file(
2732
+ self,
2733
+ metadata: Dict[str, str],
2734
+ out_dir: Optional[str] = None,
2735
+ ) -> Tuple[str, Optional[requests.Response]]:
2736
+ """Download a file from a run and write it to wandb/.
2737
+
2738
+ Arguments:
2739
+ metadata (obj): The metadata object for the file to download. Comes from Api.download_urls().
2740
+ out_dir (str, optional): The directory to write the file to. Defaults to wandb/
2741
+
2742
+ Returns:
2743
+ A tuple of the file's local path and the streaming response. The streaming response is None if the file
2744
+ already existed and was up-to-date.
2745
+ """
2746
+ filename = metadata["name"]
2747
+ path = os.path.join(out_dir or self.settings("wandb_dir"), filename)
2748
+ if self.file_current(filename, B64MD5(metadata["md5"])):
2749
+ return path, None
2750
+
2751
+ size, response = self.download_file(metadata["url"])
2752
+
2753
+ with util.fsync_open(path, "wb") as file:
2754
+ for data in response.iter_content(chunk_size=1024):
2755
+ file.write(data)
2756
+
2757
+ return path, response
2758
+
2759
+ def upload_file_azure(
2760
+ self, url: str, file: Any, extra_headers: Dict[str, str]
2761
+ ) -> None:
2762
+ """Upload a file to azure."""
2763
+ from azure.core.exceptions import AzureError # type: ignore
2764
+
2765
+ # Configure the client without retries so our existing logic can handle them
2766
+ client = self._azure_blob_module.BlobClient.from_blob_url(
2767
+ url, retry_policy=self._azure_blob_module.LinearRetry(retry_total=0)
2768
+ )
2769
+ try:
2770
+ if extra_headers.get("Content-MD5") is not None:
2771
+ md5: Optional[bytes] = base64.b64decode(extra_headers["Content-MD5"])
2772
+ else:
2773
+ md5 = None
2774
+ content_settings = self._azure_blob_module.ContentSettings(
2775
+ content_md5=md5,
2776
+ content_type=extra_headers.get("Content-Type"),
2777
+ )
2778
+ client.upload_blob(
2779
+ file,
2780
+ max_concurrency=4,
2781
+ length=len(file),
2782
+ overwrite=True,
2783
+ content_settings=content_settings,
2784
+ )
2785
+ except AzureError as e:
2786
+ if hasattr(e, "response"):
2787
+ response = requests.models.Response()
2788
+ response.status_code = e.response.status_code
2789
+ response.headers = e.response.headers
2790
+ raise requests.exceptions.RequestException(e.message, response=response)
2791
+ else:
2792
+ raise requests.exceptions.ConnectionError(e.message)
2793
+
2794
+ def upload_multipart_file_chunk(
2795
+ self,
2796
+ url: str,
2797
+ upload_chunk: bytes,
2798
+ extra_headers: Optional[Dict[str, str]] = None,
2799
+ ) -> Optional[requests.Response]:
2800
+ """Upload a file chunk to S3 with failure resumption.
2801
+
2802
+ Arguments:
2803
+ url: The url to download
2804
+ upload_chunk: The path to the file you want to upload
2805
+ extra_headers: A dictionary of extra headers to send with the request
2806
+
2807
+ Returns:
2808
+ The `requests` library response object
2809
+ """
2810
+ check_httpclient_logger_handler()
2811
+ try:
2812
+ if env.is_debug(env=self._environ):
2813
+ logger.debug("upload_file: %s", url)
2814
+ response = self._upload_file_session.put(
2815
+ url, data=upload_chunk, headers=extra_headers
2816
+ )
2817
+ if env.is_debug(env=self._environ):
2818
+ logger.debug("upload_file: %s complete", url)
2819
+ response.raise_for_status()
2820
+ except requests.exceptions.RequestException as e:
2821
+ logger.error(f"upload_file exception {url}: {e}")
2822
+ request_headers = e.request.headers if e.request is not None else ""
2823
+ logger.error(f"upload_file request headers: {request_headers!r}")
2824
+ response_content = e.response.content if e.response is not None else ""
2825
+ logger.error(f"upload_file response body: {response_content!r}")
2826
+ status_code = e.response.status_code if e.response is not None else 0
2827
+ # S3 reports retryable request timeouts out-of-band
2828
+ is_aws_retryable = status_code == 400 and "RequestTimeout" in str(
2829
+ response_content
2830
+ )
2831
+ # Retry errors from cloud storage or local network issues
2832
+ if (
2833
+ status_code in (308, 408, 409, 429, 500, 502, 503, 504)
2834
+ or isinstance(
2835
+ e,
2836
+ (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
2837
+ )
2838
+ or is_aws_retryable
2839
+ ):
2840
+ _e = retry.TransientError(exc=e)
2841
+ raise _e.with_traceback(sys.exc_info()[2])
2842
+ else:
2843
+ wandb._sentry.reraise(e)
2844
+ return response
2845
+
2846
+ def upload_file(
2847
+ self,
2848
+ url: str,
2849
+ file: IO[bytes],
2850
+ callback: Optional["ProgressFn"] = None,
2851
+ extra_headers: Optional[Dict[str, str]] = None,
2852
+ ) -> Optional[requests.Response]:
2853
+ """Upload a file to W&B with failure resumption.
2854
+
2855
+ Arguments:
2856
+ url: The url to download
2857
+ file: The path to the file you want to upload
2858
+ callback: A callback which is passed the number of
2859
+ bytes uploaded since the last time it was called, used to report progress
2860
+ extra_headers: A dictionary of extra headers to send with the request
2861
+
2862
+ Returns:
2863
+ The `requests` library response object
2864
+ """
2865
+ check_httpclient_logger_handler()
2866
+ extra_headers = extra_headers.copy() if extra_headers else {}
2867
+ response: Optional[requests.Response] = None
2868
+ progress = Progress(file, callback=callback)
2869
+ try:
2870
+ if "x-ms-blob-type" in extra_headers and self._azure_blob_module:
2871
+ self.upload_file_azure(url, progress, extra_headers)
2872
+ else:
2873
+ if "x-ms-blob-type" in extra_headers:
2874
+ wandb.termwarn(
2875
+ "Azure uploads over 256MB require the azure SDK, install with pip install wandb[azure]",
2876
+ repeat=False,
2877
+ )
2878
+ if env.is_debug(env=self._environ):
2879
+ logger.debug("upload_file: %s", url)
2880
+ response = self._upload_file_session.put(
2881
+ url, data=progress, headers=extra_headers
2882
+ )
2883
+ if env.is_debug(env=self._environ):
2884
+ logger.debug("upload_file: %s complete", url)
2885
+ response.raise_for_status()
2886
+ except requests.exceptions.RequestException as e:
2887
+ logger.error(f"upload_file exception {url}: {e}")
2888
+ request_headers = e.request.headers if e.request is not None else ""
2889
+ logger.error(f"upload_file request headers: {request_headers}")
2890
+ response_content = e.response.content if e.response is not None else ""
2891
+ logger.error(f"upload_file response body: {response_content!r}")
2892
+ status_code = e.response.status_code if e.response is not None else 0
2893
+ # S3 reports retryable request timeouts out-of-band
2894
+ is_aws_retryable = (
2895
+ "x-amz-meta-md5" in extra_headers
2896
+ and status_code == 400
2897
+ and "RequestTimeout" in str(response_content)
2898
+ )
2899
+ # We need to rewind the file for the next retry (the file passed in is `seek`'ed to 0)
2900
+ progress.rewind()
2901
+ # Retry errors from cloud storage or local network issues
2902
+ if (
2903
+ status_code in (308, 408, 409, 429, 500, 502, 503, 504)
2904
+ or isinstance(
2905
+ e,
2906
+ (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
2907
+ )
2908
+ or is_aws_retryable
2909
+ ):
2910
+ _e = retry.TransientError(exc=e)
2911
+ raise _e.with_traceback(sys.exc_info()[2])
2912
+ else:
2913
+ wandb._sentry.reraise(e)
2914
+
2915
+ return response
2916
+
2917
+ @normalize_exceptions
2918
+ def register_agent(
2919
+ self,
2920
+ host: str,
2921
+ sweep_id: Optional[str] = None,
2922
+ project_name: Optional[str] = None,
2923
+ entity: Optional[str] = None,
2924
+ ) -> dict:
2925
+ """Register a new agent.
2926
+
2927
+ Arguments:
2928
+ host (str): hostname
2929
+ sweep_id (str): sweep id
2930
+ project_name: (str): model that contains sweep
2931
+ entity: (str): entity that contains sweep
2932
+ """
2933
+ mutation = gql(
2934
+ """
2935
+ mutation CreateAgent(
2936
+ $host: String!
2937
+ $projectName: String,
2938
+ $entityName: String,
2939
+ $sweep: String!
2940
+ ) {
2941
+ createAgent(input: {
2942
+ host: $host,
2943
+ projectName: $projectName,
2944
+ entityName: $entityName,
2945
+ sweep: $sweep,
2946
+ }) {
2947
+ agent {
2948
+ id
2949
+ }
2950
+ }
2951
+ }
2952
+ """
2953
+ )
2954
+ if entity is None:
2955
+ entity = self.settings("entity")
2956
+ if project_name is None:
2957
+ project_name = self.settings("project")
2958
+
2959
+ response = self.gql(
2960
+ mutation,
2961
+ variable_values={
2962
+ "host": host,
2963
+ "entityName": entity,
2964
+ "projectName": project_name,
2965
+ "sweep": sweep_id,
2966
+ },
2967
+ check_retry_fn=util.no_retry_4xx,
2968
+ )
2969
+ result: dict = response["createAgent"]["agent"]
2970
+ return result
2971
+
2972
+ def agent_heartbeat(
2973
+ self, agent_id: str, metrics: dict, run_states: dict
2974
+ ) -> List[Dict[str, Any]]:
2975
+ """Notify server about agent state, receive commands.
2976
+
2977
+ Arguments:
2978
+ agent_id (str): agent_id
2979
+ metrics (dict): system metrics
2980
+ run_states (dict): run_id: state mapping
2981
+ Returns:
2982
+ List of commands to execute.
2983
+ """
2984
+ mutation = gql(
2985
+ """
2986
+ mutation Heartbeat(
2987
+ $id: ID!,
2988
+ $metrics: JSONString,
2989
+ $runState: JSONString
2990
+ ) {
2991
+ agentHeartbeat(input: {
2992
+ id: $id,
2993
+ metrics: $metrics,
2994
+ runState: $runState
2995
+ }) {
2996
+ agent {
2997
+ id
2998
+ }
2999
+ commands
3000
+ }
3001
+ }
3002
+ """
3003
+ )
3004
+
3005
+ if agent_id is None:
3006
+ raise ValueError("Cannot call heartbeat with an unregistered agent.")
3007
+
3008
+ try:
3009
+ response = self.gql(
3010
+ mutation,
3011
+ variable_values={
3012
+ "id": agent_id,
3013
+ "metrics": json.dumps(metrics),
3014
+ "runState": json.dumps(run_states),
3015
+ },
3016
+ timeout=60,
3017
+ )
3018
+ except Exception as e:
3019
+ # GQL raises exceptions with stringified python dictionaries :/
3020
+ message = ast.literal_eval(e.args[0])["message"]
3021
+ logger.error("Error communicating with W&B: %s", message)
3022
+ return []
3023
+ else:
3024
+ result: List[Dict[str, Any]] = json.loads(
3025
+ response["agentHeartbeat"]["commands"]
3026
+ )
3027
+ return result
3028
+
3029
+ @staticmethod
3030
+ def _validate_config_and_fill_distribution(config: dict) -> dict:
3031
+ # verify that parameters are well specified.
3032
+ # TODO(dag): deprecate this in favor of jsonschema validation once
3033
+ # apiVersion 2 is released and local controller is integrated with
3034
+ # wandb/client.
3035
+
3036
+ # avoid modifying the original config dict in
3037
+ # case it is reused outside the calling func
3038
+ config = deepcopy(config)
3039
+
3040
+ # explicitly cast to dict in case config was passed as a sweepconfig
3041
+ # sweepconfig does not serialize cleanly to yaml and breaks graphql,
3042
+ # but it is a subclass of dict, so this conversion is clean
3043
+ config = dict(config)
3044
+
3045
+ if "parameters" not in config:
3046
+ # still shows an anaconda warning, but doesn't error
3047
+ return config
3048
+
3049
+ for parameter_name in config["parameters"]:
3050
+ parameter = config["parameters"][parameter_name]
3051
+ if "min" in parameter and "max" in parameter:
3052
+ if "distribution" not in parameter:
3053
+ if isinstance(parameter["min"], int) and isinstance(
3054
+ parameter["max"], int
3055
+ ):
3056
+ parameter["distribution"] = "int_uniform"
3057
+ elif isinstance(parameter["min"], float) and isinstance(
3058
+ parameter["max"], float
3059
+ ):
3060
+ parameter["distribution"] = "uniform"
3061
+ else:
3062
+ raise ValueError(
3063
+ "Parameter {} is ambiguous, please specify bounds as both floats (for a float_"
3064
+ "uniform distribution) or ints (for an int_uniform distribution).".format(
3065
+ parameter_name
3066
+ )
3067
+ )
3068
+ return config
3069
+
3070
+ @normalize_exceptions
3071
+ def upsert_sweep(
3072
+ self,
3073
+ config: dict,
3074
+ controller: Optional[str] = None,
3075
+ launch_scheduler: Optional[str] = None,
3076
+ scheduler: Optional[str] = None,
3077
+ obj_id: Optional[str] = None,
3078
+ project: Optional[str] = None,
3079
+ entity: Optional[str] = None,
3080
+ state: Optional[str] = None,
3081
+ prior_runs: Optional[List[str]] = None,
3082
+ template_variable_values: Optional[Dict[str, Any]] = None,
3083
+ ) -> Tuple[str, List[str]]:
3084
+ """Upsert a sweep object.
3085
+
3086
+ Arguments:
3087
+ config (dict): sweep config (will be converted to yaml)
3088
+ controller (str): controller to use
3089
+ launch_scheduler (str): launch scheduler to use
3090
+ scheduler (str): scheduler to use
3091
+ obj_id (str): object id
3092
+ project (str): project to use
3093
+ entity (str): entity to use
3094
+ state (str): state
3095
+ prior_runs (list): IDs of existing runs to add to the sweep
3096
+ template_variable_values (dict): template variable values
3097
+ """
3098
+ project_query = """
3099
+ project {
3100
+ id
3101
+ name
3102
+ entity {
3103
+ id
3104
+ name
3105
+ }
3106
+ }
3107
+ """
3108
+ mutation_str = """
3109
+ mutation UpsertSweep(
3110
+ $id: ID,
3111
+ $config: String,
3112
+ $description: String,
3113
+ $entityName: String,
3114
+ $projectName: String,
3115
+ $controller: JSONString,
3116
+ $scheduler: JSONString,
3117
+ $state: String,
3118
+ $priorRunsFilters: JSONString,
3119
+ ) {
3120
+ upsertSweep(input: {
3121
+ id: $id,
3122
+ config: $config,
3123
+ description: $description,
3124
+ entityName: $entityName,
3125
+ projectName: $projectName,
3126
+ controller: $controller,
3127
+ scheduler: $scheduler,
3128
+ state: $state,
3129
+ priorRunsFilters: $priorRunsFilters,
3130
+ }) {
3131
+ sweep {
3132
+ name
3133
+ _PROJECT_QUERY_
3134
+ }
3135
+ configValidationWarnings
3136
+ }
3137
+ }
3138
+ """
3139
+ # TODO(jhr): we need protocol versioning to know schema is not supported
3140
+ # for now we will just try both new and old query
3141
+ mutation_5 = gql(
3142
+ mutation_str.replace(
3143
+ "$controller: JSONString,",
3144
+ "$controller: JSONString,$launchScheduler: JSONString, $templateVariableValues: JSONString,",
3145
+ )
3146
+ .replace(
3147
+ "controller: $controller,",
3148
+ "controller: $controller,launchScheduler: $launchScheduler,templateVariableValues: $templateVariableValues,",
3149
+ )
3150
+ .replace("_PROJECT_QUERY_", project_query)
3151
+ )
3152
+ # launchScheduler was introduced in core v0.14.0
3153
+ mutation_4 = gql(
3154
+ mutation_str.replace(
3155
+ "$controller: JSONString,",
3156
+ "$controller: JSONString,$launchScheduler: JSONString,",
3157
+ )
3158
+ .replace(
3159
+ "controller: $controller,",
3160
+ "controller: $controller,launchScheduler: $launchScheduler",
3161
+ )
3162
+ .replace("_PROJECT_QUERY_", project_query)
3163
+ )
3164
+
3165
+ # mutation 3 maps to backend that can support CLI version of at least 0.10.31
3166
+ mutation_3 = gql(mutation_str.replace("_PROJECT_QUERY_", project_query))
3167
+ mutation_2 = gql(
3168
+ mutation_str.replace("_PROJECT_QUERY_", project_query).replace(
3169
+ "configValidationWarnings", ""
3170
+ )
3171
+ )
3172
+ mutation_1 = gql(
3173
+ mutation_str.replace("_PROJECT_QUERY_", "").replace(
3174
+ "configValidationWarnings", ""
3175
+ )
3176
+ )
3177
+
3178
+ # TODO(dag): replace this with a query for protocol versioning
3179
+ mutations = [mutation_5, mutation_4, mutation_3, mutation_2, mutation_1]
3180
+
3181
+ config = self._validate_config_and_fill_distribution(config)
3182
+
3183
+ # Silly, but attr-dicts like EasyDicts don't serialize correctly to yaml.
3184
+ # This sanitizes them with a round trip pass through json to get a regular dict.
3185
+ config_str = yaml.dump(
3186
+ json.loads(json.dumps(config)), Dumper=util.NonOctalStringDumper
3187
+ )
3188
+ filters = None
3189
+ if prior_runs:
3190
+ filters = json.dumps({"$or": [{"name": r} for r in prior_runs]})
3191
+
3192
+ err: Optional[Exception] = None
3193
+ for mutation in mutations:
3194
+ try:
3195
+ variables = {
3196
+ "id": obj_id,
3197
+ "config": config_str,
3198
+ "description": config.get("description"),
3199
+ "entityName": entity or self.settings("entity"),
3200
+ "projectName": project or self.settings("project"),
3201
+ "controller": controller,
3202
+ "launchScheduler": launch_scheduler,
3203
+ "templateVariableValues": json.dumps(template_variable_values),
3204
+ "scheduler": scheduler,
3205
+ "priorRunsFilters": filters,
3206
+ }
3207
+ if state:
3208
+ variables["state"] = state
3209
+
3210
+ response = self.gql(
3211
+ mutation,
3212
+ variable_values=variables,
3213
+ check_retry_fn=util.no_retry_4xx,
3214
+ )
3215
+ except UsageError as e:
3216
+ raise e
3217
+ except Exception as e:
3218
+ # graphql schema exception is generic
3219
+ err = e
3220
+ continue
3221
+ err = None
3222
+ break
3223
+ if err:
3224
+ raise err
3225
+
3226
+ sweep: Dict[str, Dict[str, Dict]] = response["upsertSweep"]["sweep"]
3227
+ project_obj: Dict[str, Dict] = sweep.get("project", {})
3228
+ if project_obj:
3229
+ self.set_setting("project", project_obj["name"])
3230
+ entity_obj: dict = project_obj.get("entity", {})
3231
+ if entity_obj:
3232
+ self.set_setting("entity", entity_obj["name"])
3233
+
3234
+ warnings = response["upsertSweep"].get("configValidationWarnings", [])
3235
+ return response["upsertSweep"]["sweep"]["name"], warnings
3236
+
3237
+ @normalize_exceptions
3238
+ def create_anonymous_api_key(self) -> str:
3239
+ """Create a new API key belonging to a new anonymous user."""
3240
+ mutation = gql(
3241
+ """
3242
+ mutation CreateAnonymousApiKey {
3243
+ createAnonymousEntity(input: {}) {
3244
+ apiKey {
3245
+ name
3246
+ }
3247
+ }
3248
+ }
3249
+ """
3250
+ )
3251
+
3252
+ response = self.gql(mutation, variable_values={})
3253
+ key: str = str(response["createAnonymousEntity"]["apiKey"]["name"])
3254
+ return key
3255
+
3256
+ @staticmethod
3257
+ def file_current(fname: str, md5: B64MD5) -> bool:
3258
+ """Checksum a file and compare the md5 with the known md5."""
3259
+ return os.path.isfile(fname) and md5_file_b64(fname) == md5
3260
+
3261
+ @normalize_exceptions
3262
+ def pull(
3263
+ self, project: str, run: Optional[str] = None, entity: Optional[str] = None
3264
+ ) -> "List[requests.Response]":
3265
+ """Download files from W&B.
3266
+
3267
+ Arguments:
3268
+ project (str): The project to download
3269
+ run (str, optional): The run to upload to
3270
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
3271
+
3272
+ Returns:
3273
+ The `requests` library response object
3274
+ """
3275
+ project, run = self.parse_slug(project, run=run)
3276
+ urls = self.download_urls(project, run, entity)
3277
+ responses = []
3278
+ for filename in urls:
3279
+ _, response = self.download_write_file(urls[filename])
3280
+ if response:
3281
+ responses.append(response)
3282
+
3283
+ return responses
3284
+
3285
+ def get_project(self) -> str:
3286
+ project: str = self.default_settings.get("project") or self.settings("project")
3287
+ return project
3288
+
3289
+ @normalize_exceptions
3290
+ def push(
3291
+ self,
3292
+ files: Union[List[str], Dict[str, IO]],
3293
+ run: Optional[str] = None,
3294
+ entity: Optional[str] = None,
3295
+ project: Optional[str] = None,
3296
+ description: Optional[str] = None,
3297
+ force: bool = True,
3298
+ progress: Union[TextIO, bool] = False,
3299
+ ) -> "List[Optional[requests.Response]]":
3300
+ """Uploads multiple files to W&B.
3301
+
3302
+ Arguments:
3303
+ files (list or dict): The filenames to upload, when dict the values are open files
3304
+ run (str, optional): The run to upload to
3305
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
3306
+ project (str, optional): The name of the project to upload to. Defaults to the one in settings.
3307
+ description (str, optional): The description of the changes
3308
+ force (bool, optional): Whether to prevent push if git has uncommitted changes
3309
+ progress (callable, or stream): If callable, will be called with (chunk_bytes,
3310
+ total_bytes) as argument else if True, renders a progress bar to stream.
3311
+
3312
+ Returns:
3313
+ A list of `requests.Response` objects
3314
+ """
3315
+ if project is None:
3316
+ project = self.get_project()
3317
+ if project is None:
3318
+ raise CommError("No project configured.")
3319
+ if run is None:
3320
+ run = self.current_run_id
3321
+
3322
+ # TODO(adrian): we use a retriable version of self.upload_file() so
3323
+ # will never retry self.upload_urls() here. Instead, maybe we should
3324
+ # make push itself retriable.
3325
+ _, upload_headers, result = self.upload_urls(
3326
+ project,
3327
+ files,
3328
+ run,
3329
+ entity,
3330
+ )
3331
+ extra_headers = {}
3332
+ for upload_header in upload_headers:
3333
+ key, val = upload_header.split(":", 1)
3334
+ extra_headers[key] = val
3335
+ responses = []
3336
+ for file_name, file_info in result.items():
3337
+ file_url = file_info["uploadUrl"]
3338
+
3339
+ # If the upload URL is relative, fill it in with the base URL,
3340
+ # since it's a proxied file store like the on-prem VM.
3341
+ if file_url.startswith("/"):
3342
+ file_url = f"{self.api_url}{file_url}"
3343
+
3344
+ try:
3345
+ # To handle Windows paths
3346
+ # TODO: this doesn't handle absolute paths...
3347
+ normal_name = os.path.join(*file_name.split("/"))
3348
+ open_file = (
3349
+ files[file_name]
3350
+ if isinstance(files, dict)
3351
+ else open(normal_name, "rb")
3352
+ )
3353
+ except OSError:
3354
+ print(f"{file_name} does not exist")
3355
+ continue
3356
+ if progress is False:
3357
+ responses.append(
3358
+ self.upload_file_retry(
3359
+ file_info["uploadUrl"], open_file, extra_headers=extra_headers
3360
+ )
3361
+ )
3362
+ else:
3363
+ if callable(progress):
3364
+ responses.append( # type: ignore
3365
+ self.upload_file_retry(
3366
+ file_url, open_file, progress, extra_headers=extra_headers
3367
+ )
3368
+ )
3369
+ else:
3370
+ length = os.fstat(open_file.fileno()).st_size
3371
+ with click.progressbar(
3372
+ file=progress, # type: ignore
3373
+ length=length,
3374
+ label=f"Uploading file: {file_name}",
3375
+ fill_char=click.style("&", fg="green"),
3376
+ ) as bar:
3377
+ responses.append(
3378
+ self.upload_file_retry(
3379
+ file_url,
3380
+ open_file,
3381
+ lambda bites, _: bar.update(bites),
3382
+ extra_headers=extra_headers,
3383
+ )
3384
+ )
3385
+ open_file.close()
3386
+ return responses
3387
+
3388
+ def link_artifact(
3389
+ self,
3390
+ client_id: str,
3391
+ server_id: str,
3392
+ portfolio_name: str,
3393
+ entity: str,
3394
+ project: str,
3395
+ aliases: Sequence[str],
3396
+ ) -> Dict[str, Any]:
3397
+ template = """
3398
+ mutation LinkArtifact(
3399
+ $artifactPortfolioName: String!,
3400
+ $entityName: String!,
3401
+ $projectName: String!,
3402
+ $aliases: [ArtifactAliasInput!],
3403
+ ID_TYPE
3404
+ ) {
3405
+ linkArtifact(input: {
3406
+ artifactPortfolioName: $artifactPortfolioName,
3407
+ entityName: $entityName,
3408
+ projectName: $projectName,
3409
+ aliases: $aliases,
3410
+ ID_VALUE
3411
+ }) {
3412
+ versionIndex
3413
+ }
3414
+ }
3415
+ """
3416
+
3417
+ def replace(a: str, b: str) -> None:
3418
+ nonlocal template
3419
+ template = template.replace(a, b)
3420
+
3421
+ if server_id:
3422
+ replace("ID_TYPE", "$artifactID: ID")
3423
+ replace("ID_VALUE", "artifactID: $artifactID")
3424
+ elif client_id:
3425
+ replace("ID_TYPE", "$clientID: ID")
3426
+ replace("ID_VALUE", "clientID: $clientID")
3427
+
3428
+ variable_values = {
3429
+ "clientID": client_id,
3430
+ "artifactID": server_id,
3431
+ "artifactPortfolioName": portfolio_name,
3432
+ "entityName": entity,
3433
+ "projectName": project,
3434
+ "aliases": [
3435
+ {"alias": alias, "artifactCollectionName": portfolio_name}
3436
+ for alias in aliases
3437
+ ],
3438
+ }
3439
+
3440
+ mutation = gql(template)
3441
+ response = self.gql(mutation, variable_values=variable_values)
3442
+ link_artifact: Dict[str, Any] = response["linkArtifact"]
3443
+ return link_artifact
3444
+
3445
+ def use_artifact(
3446
+ self,
3447
+ artifact_id: str,
3448
+ entity_name: Optional[str] = None,
3449
+ project_name: Optional[str] = None,
3450
+ run_name: Optional[str] = None,
3451
+ use_as: Optional[str] = None,
3452
+ ) -> Optional[Dict[str, Any]]:
3453
+ query_template = """
3454
+ mutation UseArtifact(
3455
+ $entityName: String!,
3456
+ $projectName: String!,
3457
+ $runName: String!,
3458
+ $artifactID: ID!,
3459
+ _USED_AS_TYPE_
3460
+ ) {
3461
+ useArtifact(input: {
3462
+ entityName: $entityName,
3463
+ projectName: $projectName,
3464
+ runName: $runName,
3465
+ artifactID: $artifactID,
3466
+ _USED_AS_VALUE_
3467
+ }) {
3468
+ artifact {
3469
+ id
3470
+ digest
3471
+ description
3472
+ state
3473
+ createdAt
3474
+ metadata
3475
+ }
3476
+ }
3477
+ }
3478
+ """
3479
+
3480
+ artifact_types = self.server_use_artifact_input_introspection()
3481
+ if "usedAs" in artifact_types:
3482
+ query_template = query_template.replace(
3483
+ "_USED_AS_TYPE_", "$usedAs: String"
3484
+ ).replace("_USED_AS_VALUE_", "usedAs: $usedAs")
3485
+ else:
3486
+ query_template = query_template.replace("_USED_AS_TYPE_", "").replace(
3487
+ "_USED_AS_VALUE_", ""
3488
+ )
3489
+
3490
+ query = gql(query_template)
3491
+
3492
+ entity_name = entity_name or self.settings("entity")
3493
+ project_name = project_name or self.settings("project")
3494
+ run_name = run_name or self.current_run_id
3495
+
3496
+ response = self.gql(
3497
+ query,
3498
+ variable_values={
3499
+ "entityName": entity_name,
3500
+ "projectName": project_name,
3501
+ "runName": run_name,
3502
+ "artifactID": artifact_id,
3503
+ "usedAs": use_as,
3504
+ },
3505
+ )
3506
+
3507
+ if response["useArtifact"]["artifact"]:
3508
+ artifact: Dict[str, Any] = response["useArtifact"]["artifact"]
3509
+ return artifact
3510
+ return None
3511
+
3512
+ def create_artifact_type(
3513
+ self,
3514
+ artifact_type_name: str,
3515
+ entity_name: Optional[str] = None,
3516
+ project_name: Optional[str] = None,
3517
+ description: Optional[str] = None,
3518
+ ) -> Optional[str]:
3519
+ mutation = gql(
3520
+ """
3521
+ mutation CreateArtifactType(
3522
+ $entityName: String!,
3523
+ $projectName: String!,
3524
+ $artifactTypeName: String!,
3525
+ $description: String
3526
+ ) {
3527
+ createArtifactType(input: {
3528
+ entityName: $entityName,
3529
+ projectName: $projectName,
3530
+ name: $artifactTypeName,
3531
+ description: $description
3532
+ }) {
3533
+ artifactType {
3534
+ id
3535
+ }
3536
+ }
3537
+ }
3538
+ """
3539
+ )
3540
+ entity_name = entity_name or self.settings("entity")
3541
+ project_name = project_name or self.settings("project")
3542
+ response = self.gql(
3543
+ mutation,
3544
+ variable_values={
3545
+ "entityName": entity_name,
3546
+ "projectName": project_name,
3547
+ "artifactTypeName": artifact_type_name,
3548
+ "description": description,
3549
+ },
3550
+ )
3551
+ _id: Optional[str] = response["createArtifactType"]["artifactType"]["id"]
3552
+ return _id
3553
+
3554
+ def server_artifact_introspection(self) -> List[str]:
3555
+ query_string = """
3556
+ query ProbeServerArtifact {
3557
+ ArtifactInfoType: __type(name:"Artifact") {
3558
+ fields {
3559
+ name
3560
+ }
3561
+ }
3562
+ }
3563
+ """
3564
+
3565
+ if self.server_artifact_fields_info is None:
3566
+ query = gql(query_string)
3567
+ res = self.gql(query)
3568
+ input_fields = res.get("ArtifactInfoType", {}).get("fields", [{}])
3569
+ self.server_artifact_fields_info = [
3570
+ field["name"] for field in input_fields if "name" in field
3571
+ ]
3572
+
3573
+ return self.server_artifact_fields_info
3574
+
3575
+ def server_create_artifact_introspection(self) -> List[str]:
3576
+ query_string = """
3577
+ query ProbeServerCreateArtifactInput {
3578
+ CreateArtifactInputInfoType: __type(name:"CreateArtifactInput") {
3579
+ inputFields{
3580
+ name
3581
+ }
3582
+ }
3583
+ }
3584
+ """
3585
+
3586
+ if self.server_create_artifact_input_info is None:
3587
+ query = gql(query_string)
3588
+ res = self.gql(query)
3589
+ input_fields = res.get("CreateArtifactInputInfoType", {}).get(
3590
+ "inputFields", [{}]
3591
+ )
3592
+ self.server_create_artifact_input_info = [
3593
+ field["name"] for field in input_fields if "name" in field
3594
+ ]
3595
+
3596
+ return self.server_create_artifact_input_info
3597
+
3598
+ def _get_create_artifact_mutation(
3599
+ self,
3600
+ fields: List,
3601
+ history_step: Optional[int],
3602
+ distributed_id: Optional[str],
3603
+ ) -> str:
3604
+ types = ""
3605
+ values = ""
3606
+
3607
+ if "historyStep" in fields and history_step not in [0, None]:
3608
+ types += "$historyStep: Int64!,"
3609
+ values += "historyStep: $historyStep,"
3610
+
3611
+ if distributed_id:
3612
+ types += "$distributedID: String,"
3613
+ values += "distributedID: $distributedID,"
3614
+
3615
+ if "clientID" in fields:
3616
+ types += "$clientID: ID,"
3617
+ values += "clientID: $clientID,"
3618
+
3619
+ if "sequenceClientID" in fields:
3620
+ types += "$sequenceClientID: ID,"
3621
+ values += "sequenceClientID: $sequenceClientID,"
3622
+
3623
+ if "enableDigestDeduplication" in fields:
3624
+ values += "enableDigestDeduplication: true,"
3625
+
3626
+ if "ttlDurationSeconds" in fields:
3627
+ types += "$ttlDurationSeconds: Int64,"
3628
+ values += "ttlDurationSeconds: $ttlDurationSeconds,"
3629
+
3630
+ if "tags" in fields:
3631
+ types += "$tags: [TagInput!],"
3632
+ values += "tags: $tags,"
3633
+
3634
+ query_template = """
3635
+ mutation CreateArtifact(
3636
+ $artifactTypeName: String!,
3637
+ $artifactCollectionNames: [String!],
3638
+ $entityName: String!,
3639
+ $projectName: String!,
3640
+ $runName: String,
3641
+ $description: String,
3642
+ $digest: String!,
3643
+ $aliases: [ArtifactAliasInput!],
3644
+ $metadata: JSONString,
3645
+ _CREATE_ARTIFACT_ADDITIONAL_TYPE_
3646
+ ) {
3647
+ createArtifact(input: {
3648
+ artifactTypeName: $artifactTypeName,
3649
+ artifactCollectionNames: $artifactCollectionNames,
3650
+ entityName: $entityName,
3651
+ projectName: $projectName,
3652
+ runName: $runName,
3653
+ description: $description,
3654
+ digest: $digest,
3655
+ digestAlgorithm: MANIFEST_MD5,
3656
+ aliases: $aliases,
3657
+ metadata: $metadata,
3658
+ _CREATE_ARTIFACT_ADDITIONAL_VALUE_
3659
+ }) {
3660
+ artifact {
3661
+ id
3662
+ state
3663
+ artifactSequence {
3664
+ id
3665
+ latestArtifact {
3666
+ id
3667
+ versionIndex
3668
+ }
3669
+ }
3670
+ }
3671
+ }
3672
+ }
3673
+ """
3674
+
3675
+ return query_template.replace(
3676
+ "_CREATE_ARTIFACT_ADDITIONAL_TYPE_", types
3677
+ ).replace("_CREATE_ARTIFACT_ADDITIONAL_VALUE_", values)
3678
+
3679
+ def create_artifact(
3680
+ self,
3681
+ artifact_type_name: str,
3682
+ artifact_collection_name: str,
3683
+ digest: str,
3684
+ client_id: Optional[str] = None,
3685
+ sequence_client_id: Optional[str] = None,
3686
+ entity_name: Optional[str] = None,
3687
+ project_name: Optional[str] = None,
3688
+ run_name: Optional[str] = None,
3689
+ description: Optional[str] = None,
3690
+ metadata: Optional[Dict] = None,
3691
+ ttl_duration_seconds: Optional[int] = None,
3692
+ aliases: Optional[List[Dict[str, str]]] = None,
3693
+ tags: Optional[List[Dict[str, str]]] = None,
3694
+ distributed_id: Optional[str] = None,
3695
+ is_user_created: Optional[bool] = False,
3696
+ history_step: Optional[int] = None,
3697
+ ) -> Tuple[Dict, Dict]:
3698
+ fields = self.server_create_artifact_introspection()
3699
+ artifact_fields = self.server_artifact_introspection()
3700
+ if ("ttlIsInherited" not in artifact_fields) and ttl_duration_seconds:
3701
+ wandb.termwarn(
3702
+ "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL"
3703
+ )
3704
+ # ttlDurationSeconds is only usable if ttlIsInherited is also present
3705
+ ttl_duration_seconds = None
3706
+ if ("tags" not in artifact_fields) and tags:
3707
+ wandb.termwarn(
3708
+ "Server not compatible with Artifact tags. "
3709
+ "To use Artifact tags, please upgrade the server to v0.85 or higher."
3710
+ )
3711
+
3712
+ query_template = self._get_create_artifact_mutation(
3713
+ fields, history_step, distributed_id
3714
+ )
3715
+
3716
+ entity_name = entity_name or self.settings("entity")
3717
+ project_name = project_name or self.settings("project")
3718
+ if not is_user_created:
3719
+ run_name = run_name or self.current_run_id
3720
+
3721
+ mutation = gql(query_template)
3722
+ response = self.gql(
3723
+ mutation,
3724
+ variable_values={
3725
+ "entityName": entity_name,
3726
+ "projectName": project_name,
3727
+ "runName": run_name,
3728
+ "artifactTypeName": artifact_type_name,
3729
+ "artifactCollectionNames": [artifact_collection_name],
3730
+ "clientID": client_id,
3731
+ "sequenceClientID": sequence_client_id,
3732
+ "digest": digest,
3733
+ "description": description,
3734
+ "aliases": list(aliases or []),
3735
+ "tags": list(tags or []),
3736
+ "metadata": json.dumps(util.make_safe_for_json(metadata))
3737
+ if metadata
3738
+ else None,
3739
+ "ttlDurationSeconds": ttl_duration_seconds,
3740
+ "distributedID": distributed_id,
3741
+ "historyStep": history_step,
3742
+ },
3743
+ )
3744
+ av = response["createArtifact"]["artifact"]
3745
+ latest = response["createArtifact"]["artifact"]["artifactSequence"].get(
3746
+ "latestArtifact"
3747
+ )
3748
+ return av, latest
3749
+
3750
+ def commit_artifact(self, artifact_id: str) -> "_Response":
3751
+ mutation = gql(
3752
+ """
3753
+ mutation CommitArtifact(
3754
+ $artifactID: ID!,
3755
+ ) {
3756
+ commitArtifact(input: {
3757
+ artifactID: $artifactID,
3758
+ }) {
3759
+ artifact {
3760
+ id
3761
+ digest
3762
+ }
3763
+ }
3764
+ }
3765
+ """
3766
+ )
3767
+
3768
+ response: _Response = self.gql(
3769
+ mutation,
3770
+ variable_values={"artifactID": artifact_id},
3771
+ timeout=60,
3772
+ )
3773
+ return response
3774
+
3775
+ def complete_multipart_upload_artifact(
3776
+ self,
3777
+ artifact_id: str,
3778
+ storage_path: str,
3779
+ completed_parts: List[Dict[str, Any]],
3780
+ upload_id: Optional[str],
3781
+ complete_multipart_action: str = "Complete",
3782
+ ) -> Optional[str]:
3783
+ mutation = gql(
3784
+ """
3785
+ mutation CompleteMultipartUploadArtifact(
3786
+ $completeMultipartAction: CompleteMultipartAction!,
3787
+ $completedParts: [UploadPartsInput!]!,
3788
+ $artifactID: ID!
3789
+ $storagePath: String!
3790
+ $uploadID: String!
3791
+ ) {
3792
+ completeMultipartUploadArtifact(
3793
+ input: {
3794
+ completeMultipartAction: $completeMultipartAction,
3795
+ completedParts: $completedParts,
3796
+ artifactID: $artifactID,
3797
+ storagePath: $storagePath
3798
+ uploadID: $uploadID
3799
+ }
3800
+ ) {
3801
+ digest
3802
+ }
3803
+ }
3804
+ """
3805
+ )
3806
+ response = self.gql(
3807
+ mutation,
3808
+ variable_values={
3809
+ "completeMultipartAction": complete_multipart_action,
3810
+ "artifactID": artifact_id,
3811
+ "storagePath": storage_path,
3812
+ "completedParts": completed_parts,
3813
+ "uploadID": upload_id,
3814
+ },
3815
+ )
3816
+ digest: Optional[str] = response["completeMultipartUploadArtifact"]["digest"]
3817
+ return digest
3818
+
3819
+ def create_artifact_manifest(
3820
+ self,
3821
+ name: str,
3822
+ digest: str,
3823
+ artifact_id: Optional[str],
3824
+ base_artifact_id: Optional[str] = None,
3825
+ entity: Optional[str] = None,
3826
+ project: Optional[str] = None,
3827
+ run: Optional[str] = None,
3828
+ include_upload: bool = True,
3829
+ type: str = "FULL",
3830
+ ) -> Tuple[str, Dict[str, Any]]:
3831
+ mutation = gql(
3832
+ """
3833
+ mutation CreateArtifactManifest(
3834
+ $name: String!,
3835
+ $digest: String!,
3836
+ $artifactID: ID!,
3837
+ $baseArtifactID: ID,
3838
+ $entityName: String!,
3839
+ $projectName: String!,
3840
+ $runName: String!,
3841
+ $includeUpload: Boolean!,
3842
+ {}
3843
+ ) {{
3844
+ createArtifactManifest(input: {{
3845
+ name: $name,
3846
+ digest: $digest,
3847
+ artifactID: $artifactID,
3848
+ baseArtifactID: $baseArtifactID,
3849
+ entityName: $entityName,
3850
+ projectName: $projectName,
3851
+ runName: $runName,
3852
+ {}
3853
+ }}) {{
3854
+ artifactManifest {{
3855
+ id
3856
+ file {{
3857
+ id
3858
+ name
3859
+ displayName
3860
+ uploadUrl @include(if: $includeUpload)
3861
+ uploadHeaders @include(if: $includeUpload)
3862
+ }}
3863
+ }}
3864
+ }}
3865
+ }}
3866
+ """.format(
3867
+ "$type: ArtifactManifestType = FULL" if type != "FULL" else "",
3868
+ "type: $type" if type != "FULL" else "",
3869
+ )
3870
+ )
3871
+
3872
+ entity_name = entity or self.settings("entity")
3873
+ project_name = project or self.settings("project")
3874
+ run_name = run or self.current_run_id
3875
+
3876
+ response = self.gql(
3877
+ mutation,
3878
+ variable_values={
3879
+ "name": name,
3880
+ "digest": digest,
3881
+ "artifactID": artifact_id,
3882
+ "baseArtifactID": base_artifact_id,
3883
+ "entityName": entity_name,
3884
+ "projectName": project_name,
3885
+ "runName": run_name,
3886
+ "includeUpload": include_upload,
3887
+ "type": type,
3888
+ },
3889
+ )
3890
+ return (
3891
+ response["createArtifactManifest"]["artifactManifest"]["id"],
3892
+ response["createArtifactManifest"]["artifactManifest"]["file"],
3893
+ )
3894
+
3895
+ def update_artifact_manifest(
3896
+ self,
3897
+ artifact_manifest_id: str,
3898
+ base_artifact_id: Optional[str] = None,
3899
+ digest: Optional[str] = None,
3900
+ include_upload: Optional[bool] = True,
3901
+ ) -> Tuple[str, Dict[str, Any]]:
3902
+ mutation = gql(
3903
+ """
3904
+ mutation UpdateArtifactManifest(
3905
+ $artifactManifestID: ID!,
3906
+ $digest: String,
3907
+ $baseArtifactID: ID,
3908
+ $includeUpload: Boolean!,
3909
+ ) {
3910
+ updateArtifactManifest(input: {
3911
+ artifactManifestID: $artifactManifestID,
3912
+ digest: $digest,
3913
+ baseArtifactID: $baseArtifactID,
3914
+ }) {
3915
+ artifactManifest {
3916
+ id
3917
+ file {
3918
+ id
3919
+ name
3920
+ displayName
3921
+ uploadUrl @include(if: $includeUpload)
3922
+ uploadHeaders @include(if: $includeUpload)
3923
+ }
3924
+ }
3925
+ }
3926
+ }
3927
+ """
3928
+ )
3929
+
3930
+ response = self.gql(
3931
+ mutation,
3932
+ variable_values={
3933
+ "artifactManifestID": artifact_manifest_id,
3934
+ "digest": digest,
3935
+ "baseArtifactID": base_artifact_id,
3936
+ "includeUpload": include_upload,
3937
+ },
3938
+ )
3939
+
3940
+ return (
3941
+ response["updateArtifactManifest"]["artifactManifest"]["id"],
3942
+ response["updateArtifactManifest"]["artifactManifest"]["file"],
3943
+ )
3944
+
3945
+ def update_artifact_metadata(
3946
+ self, artifact_id: str, metadata: Dict[str, Any]
3947
+ ) -> Dict[str, Any]:
3948
+ """Set the metadata of the given artifact version."""
3949
+ mutation = gql(
3950
+ """
3951
+ mutation UpdateArtifact(
3952
+ $artifactID: ID!,
3953
+ $metadata: JSONString,
3954
+ ) {
3955
+ updateArtifact(input: {
3956
+ artifactID: $artifactID,
3957
+ metadata: $metadata,
3958
+ }) {
3959
+ artifact {
3960
+ id
3961
+ }
3962
+ }
3963
+ }
3964
+ """
3965
+ )
3966
+ response = self.gql(
3967
+ mutation,
3968
+ variable_values={
3969
+ "artifactID": artifact_id,
3970
+ "metadata": json.dumps(metadata),
3971
+ },
3972
+ )
3973
+ return response["updateArtifact"]["artifact"]
3974
+
3975
+ def _resolve_client_id(
3976
+ self,
3977
+ client_id: str,
3978
+ ) -> Optional[str]:
3979
+ if client_id in self._client_id_mapping:
3980
+ return self._client_id_mapping[client_id]
3981
+
3982
+ query = gql(
3983
+ """
3984
+ query ClientIDMapping($clientID: ID!) {
3985
+ clientIDMapping(clientID: $clientID) {
3986
+ serverID
3987
+ }
3988
+ }
3989
+ """
3990
+ )
3991
+ response = self.gql(
3992
+ query,
3993
+ variable_values={
3994
+ "clientID": client_id,
3995
+ },
3996
+ )
3997
+ server_id = None
3998
+ if response is not None:
3999
+ client_id_mapping = response.get("clientIDMapping")
4000
+ if client_id_mapping is not None:
4001
+ server_id = client_id_mapping.get("serverID")
4002
+ if server_id is not None:
4003
+ self._client_id_mapping[client_id] = server_id
4004
+ return server_id
4005
+
4006
+ def server_create_artifact_file_spec_input_introspection(self) -> List:
4007
+ query_string = """
4008
+ query ProbeServerCreateArtifactFileSpecInput {
4009
+ CreateArtifactFileSpecInputInfoType: __type(name:"CreateArtifactFileSpecInput") {
4010
+ inputFields{
4011
+ name
4012
+ }
4013
+ }
4014
+ }
4015
+ """
4016
+
4017
+ query = gql(query_string)
4018
+ res = self.gql(query)
4019
+ create_artifact_file_spec_input_info = [
4020
+ field.get("name", "")
4021
+ for field in res.get("CreateArtifactFileSpecInputInfoType", {}).get(
4022
+ "inputFields", [{}]
4023
+ )
4024
+ ]
4025
+ return create_artifact_file_spec_input_info
4026
+
4027
+ @normalize_exceptions
4028
+ def create_artifact_files(
4029
+ self, artifact_files: Iterable["CreateArtifactFileSpecInput"]
4030
+ ) -> Mapping[str, "CreateArtifactFilesResponseFile"]:
4031
+ query_template = """
4032
+ mutation CreateArtifactFiles(
4033
+ $storageLayout: ArtifactStorageLayout!
4034
+ $artifactFiles: [CreateArtifactFileSpecInput!]!
4035
+ ) {
4036
+ createArtifactFiles(input: {
4037
+ artifactFiles: $artifactFiles,
4038
+ storageLayout: $storageLayout,
4039
+ }) {
4040
+ files {
4041
+ edges {
4042
+ node {
4043
+ id
4044
+ name
4045
+ displayName
4046
+ uploadUrl
4047
+ uploadHeaders
4048
+ _MULTIPART_UPLOAD_FIELDS_
4049
+ artifact {
4050
+ id
4051
+ }
4052
+ }
4053
+ }
4054
+ }
4055
+ }
4056
+ }
4057
+ """
4058
+ multipart_upload_url_query = """
4059
+ storagePath
4060
+ uploadMultipartUrls {
4061
+ uploadID
4062
+ uploadUrlParts {
4063
+ partNumber
4064
+ uploadUrl
4065
+ }
4066
+ }
4067
+ """
4068
+
4069
+ # TODO: we should use constants here from interface/artifacts.py
4070
+ # but probably don't want the dependency. We're going to remove
4071
+ # this setting in a future release, so I'm just hard-coding the strings.
4072
+ storage_layout = "V2"
4073
+ if env.get_use_v1_artifacts():
4074
+ storage_layout = "V1"
4075
+
4076
+ create_artifact_file_spec_input_fields = (
4077
+ self.server_create_artifact_file_spec_input_introspection()
4078
+ )
4079
+ if "uploadPartsInput" in create_artifact_file_spec_input_fields:
4080
+ query_template = query_template.replace(
4081
+ "_MULTIPART_UPLOAD_FIELDS_", multipart_upload_url_query
4082
+ )
4083
+ else:
4084
+ query_template = query_template.replace("_MULTIPART_UPLOAD_FIELDS_", "")
4085
+
4086
+ mutation = gql(query_template)
4087
+ response = self.gql(
4088
+ mutation,
4089
+ variable_values={
4090
+ "storageLayout": storage_layout,
4091
+ "artifactFiles": [af for af in artifact_files],
4092
+ },
4093
+ )
4094
+
4095
+ result = {}
4096
+ for edge in response["createArtifactFiles"]["files"]["edges"]:
4097
+ node = edge["node"]
4098
+ result[node["displayName"]] = node
4099
+ return result
4100
+
4101
+ @normalize_exceptions
4102
+ def notify_scriptable_run_alert(
4103
+ self,
4104
+ title: str,
4105
+ text: str,
4106
+ level: Optional[str] = None,
4107
+ wait_duration: Optional["Number"] = None,
4108
+ ) -> bool:
4109
+ mutation = gql(
4110
+ """
4111
+ mutation NotifyScriptableRunAlert(
4112
+ $entityName: String!,
4113
+ $projectName: String!,
4114
+ $runName: String!,
4115
+ $title: String!,
4116
+ $text: String!,
4117
+ $severity: AlertSeverity = INFO,
4118
+ $waitDuration: Duration
4119
+ ) {
4120
+ notifyScriptableRunAlert(input: {
4121
+ entityName: $entityName,
4122
+ projectName: $projectName,
4123
+ runName: $runName,
4124
+ title: $title,
4125
+ text: $text,
4126
+ severity: $severity,
4127
+ waitDuration: $waitDuration
4128
+ }) {
4129
+ success
4130
+ }
4131
+ }
4132
+ """
4133
+ )
4134
+
4135
+ response = self.gql(
4136
+ mutation,
4137
+ variable_values={
4138
+ "entityName": self.settings("entity"),
4139
+ "projectName": self.settings("project"),
4140
+ "runName": self.current_run_id,
4141
+ "title": title,
4142
+ "text": text,
4143
+ "severity": level,
4144
+ "waitDuration": wait_duration,
4145
+ },
4146
+ )
4147
+ success: bool = response["notifyScriptableRunAlert"]["success"]
4148
+ return success
4149
+
4150
+ def get_sweep_state(
4151
+ self, sweep: str, entity: Optional[str] = None, project: Optional[str] = None
4152
+ ) -> "SweepState":
4153
+ state: SweepState = self.sweep(
4154
+ sweep=sweep, entity=entity, project=project, specs="{}"
4155
+ )["state"]
4156
+ return state
4157
+
4158
+ def set_sweep_state(
4159
+ self,
4160
+ sweep: str,
4161
+ state: "SweepState",
4162
+ entity: Optional[str] = None,
4163
+ project: Optional[str] = None,
4164
+ ) -> None:
4165
+ assert state in ("RUNNING", "PAUSED", "CANCELED", "FINISHED")
4166
+ s = self.sweep(sweep=sweep, entity=entity, project=project, specs="{}")
4167
+ curr_state = s["state"].upper()
4168
+ if state == "PAUSED" and curr_state not in ("PAUSED", "RUNNING"):
4169
+ raise Exception("Cannot pause {} sweep.".format(curr_state.lower()))
4170
+ elif state != "RUNNING" and curr_state not in ("RUNNING", "PAUSED", "PENDING"):
4171
+ raise Exception("Sweep already {}.".format(curr_state.lower()))
4172
+ sweep_id = s["id"]
4173
+ mutation = gql(
4174
+ """
4175
+ mutation UpsertSweep(
4176
+ $id: ID,
4177
+ $state: String,
4178
+ $entityName: String,
4179
+ $projectName: String
4180
+ ) {
4181
+ upsertSweep(input: {
4182
+ id: $id,
4183
+ state: $state,
4184
+ entityName: $entityName,
4185
+ projectName: $projectName
4186
+ }){
4187
+ sweep {
4188
+ name
4189
+ }
4190
+ }
4191
+ }
4192
+ """
4193
+ )
4194
+ self.gql(
4195
+ mutation,
4196
+ variable_values={
4197
+ "id": sweep_id,
4198
+ "state": state,
4199
+ "entityName": entity or self.settings("entity"),
4200
+ "projectName": project or self.settings("project"),
4201
+ },
4202
+ )
4203
+
4204
+ def stop_sweep(
4205
+ self,
4206
+ sweep: str,
4207
+ entity: Optional[str] = None,
4208
+ project: Optional[str] = None,
4209
+ ) -> None:
4210
+ """Finish the sweep to stop running new runs and let currently running runs finish."""
4211
+ self.set_sweep_state(
4212
+ sweep=sweep, state="FINISHED", entity=entity, project=project
4213
+ )
4214
+
4215
+ def cancel_sweep(
4216
+ self,
4217
+ sweep: str,
4218
+ entity: Optional[str] = None,
4219
+ project: Optional[str] = None,
4220
+ ) -> None:
4221
+ """Cancel the sweep to kill all running runs and stop running new runs."""
4222
+ self.set_sweep_state(
4223
+ sweep=sweep, state="CANCELED", entity=entity, project=project
4224
+ )
4225
+
4226
+ def pause_sweep(
4227
+ self,
4228
+ sweep: str,
4229
+ entity: Optional[str] = None,
4230
+ project: Optional[str] = None,
4231
+ ) -> None:
4232
+ """Pause the sweep to temporarily stop running new runs."""
4233
+ self.set_sweep_state(
4234
+ sweep=sweep, state="PAUSED", entity=entity, project=project
4235
+ )
4236
+
4237
+ def resume_sweep(
4238
+ self,
4239
+ sweep: str,
4240
+ entity: Optional[str] = None,
4241
+ project: Optional[str] = None,
4242
+ ) -> None:
4243
+ """Resume the sweep to continue running new runs."""
4244
+ self.set_sweep_state(
4245
+ sweep=sweep, state="RUNNING", entity=entity, project=project
4246
+ )
4247
+
4248
+ def _status_request(self, url: str, length: int) -> requests.Response:
4249
+ """Ask google how much we've uploaded."""
4250
+ check_httpclient_logger_handler()
4251
+ return requests.put(
4252
+ url=url,
4253
+ headers={"Content-Length": "0", "Content-Range": "bytes */%i" % length},
4254
+ )
4255
+
4256
+ def _flatten_edges(self, response: "_Response") -> List[Dict]:
4257
+ """Return an array from the nested graphql relay structure."""
4258
+ return [node["node"] for node in response["edges"]]
4259
+
4260
+ @normalize_exceptions
4261
+ def stop_run(
4262
+ self,
4263
+ run_id: str,
4264
+ ) -> bool:
4265
+ mutation = gql(
4266
+ """
4267
+ mutation stopRun($id: ID!) {
4268
+ stopRun(input: {
4269
+ id: $id
4270
+ }) {
4271
+ clientMutationId
4272
+ success
4273
+ }
4274
+ }
4275
+ """
4276
+ )
4277
+
4278
+ response = self.gql(
4279
+ mutation,
4280
+ variable_values={
4281
+ "id": run_id,
4282
+ },
4283
+ )
4284
+
4285
+ success: bool = response["stopRun"].get("success")
4286
+
4287
+ return success