wandb 0.17.0rc1__py3-none-macosx_10_9_x86_64.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (842) hide show
  1. package_readme.md +95 -0
  2. wandb/__init__.py +253 -0
  3. wandb/__main__.py +3 -0
  4. wandb/_globals.py +19 -0
  5. wandb/agents/__init__.py +0 -0
  6. wandb/agents/pyagent.py +364 -0
  7. wandb/analytics/__init__.py +3 -0
  8. wandb/analytics/sentry.py +266 -0
  9. wandb/apis/__init__.py +48 -0
  10. wandb/apis/attrs.py +40 -0
  11. wandb/apis/importers/__init__.py +1 -0
  12. wandb/apis/importers/internals/internal.py +386 -0
  13. wandb/apis/importers/internals/protocols.py +99 -0
  14. wandb/apis/importers/internals/util.py +78 -0
  15. wandb/apis/importers/mlflow.py +254 -0
  16. wandb/apis/importers/validation.py +108 -0
  17. wandb/apis/importers/wandb.py +1598 -0
  18. wandb/apis/internal.py +228 -0
  19. wandb/apis/normalize.py +89 -0
  20. wandb/apis/paginator.py +81 -0
  21. wandb/apis/public/__init__.py +34 -0
  22. wandb/apis/public/api.py +1045 -0
  23. wandb/apis/public/artifacts.py +851 -0
  24. wandb/apis/public/const.py +4 -0
  25. wandb/apis/public/files.py +195 -0
  26. wandb/apis/public/history.py +149 -0
  27. wandb/apis/public/jobs.py +634 -0
  28. wandb/apis/public/projects.py +162 -0
  29. wandb/apis/public/query_generator.py +166 -0
  30. wandb/apis/public/reports.py +469 -0
  31. wandb/apis/public/runs.py +803 -0
  32. wandb/apis/public/sweeps.py +240 -0
  33. wandb/apis/public/teams.py +198 -0
  34. wandb/apis/public/users.py +136 -0
  35. wandb/apis/reports/__init__.py +7 -0
  36. wandb/apis/reports/v1/__init__.py +30 -0
  37. wandb/apis/reports/v1/_blocks.py +1406 -0
  38. wandb/apis/reports/v1/_helpers.py +70 -0
  39. wandb/apis/reports/v1/_panels.py +1282 -0
  40. wandb/apis/reports/v1/_templates.py +478 -0
  41. wandb/apis/reports/v1/blocks.py +27 -0
  42. wandb/apis/reports/v1/helpers.py +2 -0
  43. wandb/apis/reports/v1/mutations.py +66 -0
  44. wandb/apis/reports/v1/panels.py +17 -0
  45. wandb/apis/reports/v1/report.py +268 -0
  46. wandb/apis/reports/v1/runset.py +144 -0
  47. wandb/apis/reports/v1/templates.py +7 -0
  48. wandb/apis/reports/v1/util.py +406 -0
  49. wandb/apis/reports/v1/validators.py +131 -0
  50. wandb/apis/reports/v2/__init__.py +20 -0
  51. wandb/apis/reports/v2/blocks.py +25 -0
  52. wandb/apis/reports/v2/expr_parsing.py +257 -0
  53. wandb/apis/reports/v2/gql.py +68 -0
  54. wandb/apis/reports/v2/interface.py +1911 -0
  55. wandb/apis/reports/v2/internal.py +867 -0
  56. wandb/apis/reports/v2/metrics.py +6 -0
  57. wandb/apis/reports/v2/panels.py +15 -0
  58. wandb/beta/workflows.py +283 -0
  59. wandb/bin/apple_gpu_stats +0 -0
  60. wandb/bin/wandb-core +0 -0
  61. wandb/catboost/__init__.py +9 -0
  62. wandb/cli/__init__.py +0 -0
  63. wandb/cli/cli.py +2890 -0
  64. wandb/data_types.py +2068 -0
  65. wandb/docker/__init__.py +342 -0
  66. wandb/docker/auth.py +436 -0
  67. wandb/docker/wandb-entrypoint.sh +33 -0
  68. wandb/docker/www_authenticate.py +94 -0
  69. wandb/env.py +496 -0
  70. wandb/errors/__init__.py +46 -0
  71. wandb/errors/term.py +95 -0
  72. wandb/errors/util.py +57 -0
  73. wandb/fastai/__init__.py +9 -0
  74. wandb/filesync/__init__.py +0 -0
  75. wandb/filesync/dir_watcher.py +403 -0
  76. wandb/filesync/stats.py +100 -0
  77. wandb/filesync/step_checksum.py +145 -0
  78. wandb/filesync/step_prepare.py +199 -0
  79. wandb/filesync/step_upload.py +392 -0
  80. wandb/filesync/upload_job.py +218 -0
  81. wandb/integration/__init__.py +0 -0
  82. wandb/integration/catboost/__init__.py +5 -0
  83. wandb/integration/catboost/catboost.py +178 -0
  84. wandb/integration/cohere/__init__.py +3 -0
  85. wandb/integration/cohere/cohere.py +21 -0
  86. wandb/integration/cohere/resolver.py +347 -0
  87. wandb/integration/diffusers/__init__.py +3 -0
  88. wandb/integration/diffusers/autologger.py +76 -0
  89. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  90. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  91. wandb/integration/diffusers/resolvers/multimodal.py +882 -0
  92. wandb/integration/diffusers/resolvers/utils.py +102 -0
  93. wandb/integration/fastai/__init__.py +249 -0
  94. wandb/integration/gym/__init__.py +85 -0
  95. wandb/integration/huggingface/__init__.py +3 -0
  96. wandb/integration/huggingface/huggingface.py +18 -0
  97. wandb/integration/huggingface/resolver.py +213 -0
  98. wandb/integration/keras/__init__.py +14 -0
  99. wandb/integration/keras/callbacks/__init__.py +5 -0
  100. wandb/integration/keras/callbacks/metrics_logger.py +130 -0
  101. wandb/integration/keras/callbacks/model_checkpoint.py +200 -0
  102. wandb/integration/keras/callbacks/tables_builder.py +226 -0
  103. wandb/integration/keras/keras.py +1080 -0
  104. wandb/integration/kfp/__init__.py +6 -0
  105. wandb/integration/kfp/helpers.py +28 -0
  106. wandb/integration/kfp/kfp_patch.py +324 -0
  107. wandb/integration/kfp/wandb_logging.py +182 -0
  108. wandb/integration/langchain/__init__.py +3 -0
  109. wandb/integration/langchain/wandb_tracer.py +48 -0
  110. wandb/integration/lightgbm/__init__.py +239 -0
  111. wandb/integration/lightning/__init__.py +0 -0
  112. wandb/integration/lightning/fabric/__init__.py +3 -0
  113. wandb/integration/lightning/fabric/logger.py +762 -0
  114. wandb/integration/magic.py +556 -0
  115. wandb/integration/metaflow/__init__.py +3 -0
  116. wandb/integration/metaflow/metaflow.py +383 -0
  117. wandb/integration/openai/__init__.py +3 -0
  118. wandb/integration/openai/fine_tuning.py +454 -0
  119. wandb/integration/openai/openai.py +22 -0
  120. wandb/integration/openai/resolver.py +240 -0
  121. wandb/integration/prodigy/__init__.py +3 -0
  122. wandb/integration/prodigy/prodigy.py +299 -0
  123. wandb/integration/sacred/__init__.py +117 -0
  124. wandb/integration/sagemaker/__init__.py +12 -0
  125. wandb/integration/sagemaker/auth.py +28 -0
  126. wandb/integration/sagemaker/config.py +49 -0
  127. wandb/integration/sagemaker/files.py +3 -0
  128. wandb/integration/sagemaker/resources.py +34 -0
  129. wandb/integration/sb3/__init__.py +3 -0
  130. wandb/integration/sb3/sb3.py +153 -0
  131. wandb/integration/tensorboard/__init__.py +10 -0
  132. wandb/integration/tensorboard/log.py +358 -0
  133. wandb/integration/tensorboard/monkeypatch.py +185 -0
  134. wandb/integration/tensorflow/__init__.py +5 -0
  135. wandb/integration/tensorflow/estimator_hook.py +54 -0
  136. wandb/integration/torch/__init__.py +0 -0
  137. wandb/integration/ultralytics/__init__.py +11 -0
  138. wandb/integration/ultralytics/bbox_utils.py +208 -0
  139. wandb/integration/ultralytics/callback.py +524 -0
  140. wandb/integration/ultralytics/classification_utils.py +83 -0
  141. wandb/integration/ultralytics/mask_utils.py +202 -0
  142. wandb/integration/ultralytics/pose_utils.py +104 -0
  143. wandb/integration/xgboost/__init__.py +11 -0
  144. wandb/integration/xgboost/xgboost.py +189 -0
  145. wandb/integration/yolov8/__init__.py +0 -0
  146. wandb/integration/yolov8/yolov8.py +284 -0
  147. wandb/jupyter.py +501 -0
  148. wandb/keras/__init__.py +19 -0
  149. wandb/lightgbm/__init__.py +9 -0
  150. wandb/magic.py +3 -0
  151. wandb/mpmain/__init__.py +0 -0
  152. wandb/mpmain/__main__.py +1 -0
  153. wandb/old/__init__.py +0 -0
  154. wandb/old/core.py +131 -0
  155. wandb/old/settings.py +173 -0
  156. wandb/old/summary.py +435 -0
  157. wandb/plot/__init__.py +19 -0
  158. wandb/plot/bar.py +42 -0
  159. wandb/plot/confusion_matrix.py +99 -0
  160. wandb/plot/histogram.py +36 -0
  161. wandb/plot/line.py +40 -0
  162. wandb/plot/line_series.py +88 -0
  163. wandb/plot/pr_curve.py +135 -0
  164. wandb/plot/roc_curve.py +117 -0
  165. wandb/plot/scatter.py +32 -0
  166. wandb/plots/__init__.py +6 -0
  167. wandb/plots/explain_text.py +36 -0
  168. wandb/plots/heatmap.py +81 -0
  169. wandb/plots/named_entity.py +43 -0
  170. wandb/plots/part_of_speech.py +50 -0
  171. wandb/plots/plot_definitions.py +768 -0
  172. wandb/plots/precision_recall.py +121 -0
  173. wandb/plots/roc.py +103 -0
  174. wandb/plots/utils.py +195 -0
  175. wandb/proto/__init__.py +0 -0
  176. wandb/proto/v3/__init__.py +0 -0
  177. wandb/proto/v3/wandb_base_pb2.py +54 -0
  178. wandb/proto/v3/wandb_internal_pb2.py +1586 -0
  179. wandb/proto/v3/wandb_server_pb2.py +207 -0
  180. wandb/proto/v3/wandb_settings_pb2.py +111 -0
  181. wandb/proto/v3/wandb_telemetry_pb2.py +105 -0
  182. wandb/proto/v4/__init__.py +0 -0
  183. wandb/proto/v4/wandb_base_pb2.py +29 -0
  184. wandb/proto/v4/wandb_internal_pb2.py +354 -0
  185. wandb/proto/v4/wandb_server_pb2.py +62 -0
  186. wandb/proto/v4/wandb_settings_pb2.py +44 -0
  187. wandb/proto/v4/wandb_telemetry_pb2.py +40 -0
  188. wandb/proto/wandb_base_pb2.py +8 -0
  189. wandb/proto/wandb_deprecated.py +37 -0
  190. wandb/proto/wandb_internal_codegen.py +83 -0
  191. wandb/proto/wandb_internal_pb2.py +8 -0
  192. wandb/proto/wandb_server_pb2.py +8 -0
  193. wandb/proto/wandb_settings_pb2.py +8 -0
  194. wandb/proto/wandb_telemetry_pb2.py +8 -0
  195. wandb/py.typed +0 -0
  196. wandb/sacred/__init__.py +3 -0
  197. wandb/sdk/__init__.py +37 -0
  198. wandb/sdk/artifacts/__init__.py +0 -0
  199. wandb/sdk/artifacts/artifact.py +2317 -0
  200. wandb/sdk/artifacts/artifact_download_logger.py +43 -0
  201. wandb/sdk/artifacts/artifact_file_cache.py +229 -0
  202. wandb/sdk/artifacts/artifact_instance_cache.py +15 -0
  203. wandb/sdk/artifacts/artifact_manifest.py +72 -0
  204. wandb/sdk/artifacts/artifact_manifest_entry.py +205 -0
  205. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  206. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +90 -0
  207. wandb/sdk/artifacts/artifact_saver.py +270 -0
  208. wandb/sdk/artifacts/artifact_state.py +11 -0
  209. wandb/sdk/artifacts/artifact_ttl.py +7 -0
  210. wandb/sdk/artifacts/exceptions.py +56 -0
  211. wandb/sdk/artifacts/staging.py +25 -0
  212. wandb/sdk/artifacts/storage_handler.py +60 -0
  213. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  214. wandb/sdk/artifacts/storage_handlers/azure_handler.py +194 -0
  215. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +195 -0
  216. wandb/sdk/artifacts/storage_handlers/http_handler.py +113 -0
  217. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +135 -0
  218. wandb/sdk/artifacts/storage_handlers/multi_handler.py +54 -0
  219. wandb/sdk/artifacts/storage_handlers/s3_handler.py +300 -0
  220. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +68 -0
  221. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +133 -0
  222. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +72 -0
  223. wandb/sdk/artifacts/storage_layout.py +6 -0
  224. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  225. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  226. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +411 -0
  227. wandb/sdk/artifacts/storage_policy.py +83 -0
  228. wandb/sdk/backend/__init__.py +0 -0
  229. wandb/sdk/backend/backend.py +240 -0
  230. wandb/sdk/data_types/__init__.py +0 -0
  231. wandb/sdk/data_types/_dtypes.py +911 -0
  232. wandb/sdk/data_types/_private.py +10 -0
  233. wandb/sdk/data_types/base_types/__init__.py +0 -0
  234. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  235. wandb/sdk/data_types/base_types/media.py +313 -0
  236. wandb/sdk/data_types/base_types/wb_value.py +274 -0
  237. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  238. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +293 -0
  239. wandb/sdk/data_types/helper_types/classes.py +159 -0
  240. wandb/sdk/data_types/helper_types/image_mask.py +233 -0
  241. wandb/sdk/data_types/histogram.py +96 -0
  242. wandb/sdk/data_types/html.py +115 -0
  243. wandb/sdk/data_types/image.py +687 -0
  244. wandb/sdk/data_types/molecule.py +241 -0
  245. wandb/sdk/data_types/object_3d.py +363 -0
  246. wandb/sdk/data_types/plotly.py +82 -0
  247. wandb/sdk/data_types/saved_model.py +444 -0
  248. wandb/sdk/data_types/trace_tree.py +438 -0
  249. wandb/sdk/data_types/utils.py +180 -0
  250. wandb/sdk/data_types/video.py +245 -0
  251. wandb/sdk/integration_utils/__init__.py +0 -0
  252. wandb/sdk/integration_utils/auto_logging.py +239 -0
  253. wandb/sdk/integration_utils/data_logging.py +475 -0
  254. wandb/sdk/interface/__init__.py +0 -0
  255. wandb/sdk/interface/constants.py +4 -0
  256. wandb/sdk/interface/interface.py +949 -0
  257. wandb/sdk/interface/interface_queue.py +59 -0
  258. wandb/sdk/interface/interface_relay.py +53 -0
  259. wandb/sdk/interface/interface_shared.py +550 -0
  260. wandb/sdk/interface/interface_sock.py +61 -0
  261. wandb/sdk/interface/message_future.py +27 -0
  262. wandb/sdk/interface/message_future_poll.py +50 -0
  263. wandb/sdk/interface/router.py +118 -0
  264. wandb/sdk/interface/router_queue.py +44 -0
  265. wandb/sdk/interface/router_relay.py +39 -0
  266. wandb/sdk/interface/router_sock.py +36 -0
  267. wandb/sdk/interface/summary_record.py +67 -0
  268. wandb/sdk/internal/__init__.py +0 -0
  269. wandb/sdk/internal/context.py +89 -0
  270. wandb/sdk/internal/datastore.py +297 -0
  271. wandb/sdk/internal/file_pusher.py +184 -0
  272. wandb/sdk/internal/file_stream.py +708 -0
  273. wandb/sdk/internal/flow_control.py +263 -0
  274. wandb/sdk/internal/handler.py +909 -0
  275. wandb/sdk/internal/internal.py +417 -0
  276. wandb/sdk/internal/internal_api.py +4202 -0
  277. wandb/sdk/internal/internal_util.py +100 -0
  278. wandb/sdk/internal/job_builder.py +554 -0
  279. wandb/sdk/internal/profiler.py +78 -0
  280. wandb/sdk/internal/progress.py +111 -0
  281. wandb/sdk/internal/run.py +25 -0
  282. wandb/sdk/internal/sample.py +70 -0
  283. wandb/sdk/internal/sender.py +1642 -0
  284. wandb/sdk/internal/sender_config.py +197 -0
  285. wandb/sdk/internal/settings_static.py +83 -0
  286. wandb/sdk/internal/system/__init__.py +0 -0
  287. wandb/sdk/internal/system/assets/__init__.py +27 -0
  288. wandb/sdk/internal/system/assets/aggregators.py +37 -0
  289. wandb/sdk/internal/system/assets/asset_registry.py +20 -0
  290. wandb/sdk/internal/system/assets/cpu.py +163 -0
  291. wandb/sdk/internal/system/assets/disk.py +210 -0
  292. wandb/sdk/internal/system/assets/gpu.py +414 -0
  293. wandb/sdk/internal/system/assets/gpu_amd.py +230 -0
  294. wandb/sdk/internal/system/assets/gpu_apple.py +177 -0
  295. wandb/sdk/internal/system/assets/interfaces.py +207 -0
  296. wandb/sdk/internal/system/assets/ipu.py +177 -0
  297. wandb/sdk/internal/system/assets/memory.py +166 -0
  298. wandb/sdk/internal/system/assets/network.py +125 -0
  299. wandb/sdk/internal/system/assets/open_metrics.py +299 -0
  300. wandb/sdk/internal/system/assets/tpu.py +154 -0
  301. wandb/sdk/internal/system/assets/trainium.py +398 -0
  302. wandb/sdk/internal/system/env_probe_helpers.py +13 -0
  303. wandb/sdk/internal/system/system_info.py +247 -0
  304. wandb/sdk/internal/system/system_monitor.py +229 -0
  305. wandb/sdk/internal/tb_watcher.py +518 -0
  306. wandb/sdk/internal/thread_local_settings.py +18 -0
  307. wandb/sdk/internal/update.py +113 -0
  308. wandb/sdk/internal/writer.py +206 -0
  309. wandb/sdk/launch/__init__.py +6 -0
  310. wandb/sdk/launch/_launch.py +348 -0
  311. wandb/sdk/launch/_launch_add.py +257 -0
  312. wandb/sdk/launch/_project_spec.py +578 -0
  313. wandb/sdk/launch/agent/__init__.py +5 -0
  314. wandb/sdk/launch/agent/agent.py +878 -0
  315. wandb/sdk/launch/agent/config.py +299 -0
  316. wandb/sdk/launch/agent/job_status_tracker.py +53 -0
  317. wandb/sdk/launch/agent/run_queue_item_file_saver.py +47 -0
  318. wandb/sdk/launch/builder/__init__.py +0 -0
  319. wandb/sdk/launch/builder/abstract.py +89 -0
  320. wandb/sdk/launch/builder/build.py +706 -0
  321. wandb/sdk/launch/builder/docker_builder.py +193 -0
  322. wandb/sdk/launch/builder/kaniko_builder.py +579 -0
  323. wandb/sdk/launch/builder/noop.py +58 -0
  324. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +187 -0
  325. wandb/sdk/launch/create_job.py +520 -0
  326. wandb/sdk/launch/environment/abstract.py +29 -0
  327. wandb/sdk/launch/environment/aws_environment.py +297 -0
  328. wandb/sdk/launch/environment/azure_environment.py +105 -0
  329. wandb/sdk/launch/environment/gcp_environment.py +335 -0
  330. wandb/sdk/launch/environment/local_environment.py +66 -0
  331. wandb/sdk/launch/errors.py +19 -0
  332. wandb/sdk/launch/git_reference.py +109 -0
  333. wandb/sdk/launch/loader.py +249 -0
  334. wandb/sdk/launch/registry/abstract.py +48 -0
  335. wandb/sdk/launch/registry/anon.py +29 -0
  336. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  337. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  338. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  339. wandb/sdk/launch/registry/local_registry.py +67 -0
  340. wandb/sdk/launch/runner/__init__.py +0 -0
  341. wandb/sdk/launch/runner/abstract.py +195 -0
  342. wandb/sdk/launch/runner/kubernetes_monitor.py +441 -0
  343. wandb/sdk/launch/runner/kubernetes_runner.py +893 -0
  344. wandb/sdk/launch/runner/local_container.py +299 -0
  345. wandb/sdk/launch/runner/local_process.py +99 -0
  346. wandb/sdk/launch/runner/sagemaker_runner.py +422 -0
  347. wandb/sdk/launch/runner/vertex_runner.py +229 -0
  348. wandb/sdk/launch/sweeps/__init__.py +39 -0
  349. wandb/sdk/launch/sweeps/scheduler.py +738 -0
  350. wandb/sdk/launch/sweeps/scheduler_sweep.py +91 -0
  351. wandb/sdk/launch/sweeps/utils.py +316 -0
  352. wandb/sdk/launch/utils.py +866 -0
  353. wandb/sdk/launch/wandb_reference.py +138 -0
  354. wandb/sdk/lib/__init__.py +5 -0
  355. wandb/sdk/lib/_settings_toposort_generate.py +159 -0
  356. wandb/sdk/lib/_settings_toposort_generated.py +244 -0
  357. wandb/sdk/lib/_wburls_generate.py +25 -0
  358. wandb/sdk/lib/_wburls_generated.py +22 -0
  359. wandb/sdk/lib/apikey.py +258 -0
  360. wandb/sdk/lib/capped_dict.py +26 -0
  361. wandb/sdk/lib/config_util.py +101 -0
  362. wandb/sdk/lib/console.py +39 -0
  363. wandb/sdk/lib/deprecate.py +42 -0
  364. wandb/sdk/lib/disabled.py +190 -0
  365. wandb/sdk/lib/exit_hooks.py +54 -0
  366. wandb/sdk/lib/file_stream_utils.py +118 -0
  367. wandb/sdk/lib/filenames.py +64 -0
  368. wandb/sdk/lib/filesystem.py +372 -0
  369. wandb/sdk/lib/fsm.py +174 -0
  370. wandb/sdk/lib/gitlib.py +239 -0
  371. wandb/sdk/lib/gql_request.py +65 -0
  372. wandb/sdk/lib/handler_util.py +21 -0
  373. wandb/sdk/lib/hashutil.py +62 -0
  374. wandb/sdk/lib/import_hooks.py +275 -0
  375. wandb/sdk/lib/ipython.py +146 -0
  376. wandb/sdk/lib/json_util.py +80 -0
  377. wandb/sdk/lib/lazyloader.py +63 -0
  378. wandb/sdk/lib/mailbox.py +460 -0
  379. wandb/sdk/lib/module.py +69 -0
  380. wandb/sdk/lib/paths.py +106 -0
  381. wandb/sdk/lib/preinit.py +42 -0
  382. wandb/sdk/lib/printer.py +313 -0
  383. wandb/sdk/lib/proto_util.py +69 -0
  384. wandb/sdk/lib/redirect.py +840 -0
  385. wandb/sdk/lib/reporting.py +99 -0
  386. wandb/sdk/lib/retry.py +289 -0
  387. wandb/sdk/lib/run_moment.py +78 -0
  388. wandb/sdk/lib/runid.py +12 -0
  389. wandb/sdk/lib/server.py +52 -0
  390. wandb/sdk/lib/sock_client.py +291 -0
  391. wandb/sdk/lib/sparkline.py +45 -0
  392. wandb/sdk/lib/telemetry.py +100 -0
  393. wandb/sdk/lib/timed_input.py +133 -0
  394. wandb/sdk/lib/timer.py +19 -0
  395. wandb/sdk/lib/tracelog.py +255 -0
  396. wandb/sdk/lib/wburls.py +46 -0
  397. wandb/sdk/service/__init__.py +0 -0
  398. wandb/sdk/service/_startup_debug.py +22 -0
  399. wandb/sdk/service/port_file.py +53 -0
  400. wandb/sdk/service/server.py +119 -0
  401. wandb/sdk/service/server_sock.py +276 -0
  402. wandb/sdk/service/service.py +266 -0
  403. wandb/sdk/service/service_base.py +50 -0
  404. wandb/sdk/service/service_sock.py +70 -0
  405. wandb/sdk/service/streams.py +426 -0
  406. wandb/sdk/verify/__init__.py +0 -0
  407. wandb/sdk/verify/verify.py +501 -0
  408. wandb/sdk/wandb_alerts.py +12 -0
  409. wandb/sdk/wandb_config.py +319 -0
  410. wandb/sdk/wandb_helper.py +54 -0
  411. wandb/sdk/wandb_init.py +1220 -0
  412. wandb/sdk/wandb_login.py +339 -0
  413. wandb/sdk/wandb_manager.py +222 -0
  414. wandb/sdk/wandb_metric.py +110 -0
  415. wandb/sdk/wandb_require.py +92 -0
  416. wandb/sdk/wandb_require_helpers.py +44 -0
  417. wandb/sdk/wandb_run.py +4191 -0
  418. wandb/sdk/wandb_settings.py +1973 -0
  419. wandb/sdk/wandb_setup.py +335 -0
  420. wandb/sdk/wandb_summary.py +150 -0
  421. wandb/sdk/wandb_sweep.py +114 -0
  422. wandb/sdk/wandb_sync.py +75 -0
  423. wandb/sdk/wandb_watch.py +128 -0
  424. wandb/sklearn/__init__.py +37 -0
  425. wandb/sklearn/calculate/__init__.py +32 -0
  426. wandb/sklearn/calculate/calibration_curves.py +125 -0
  427. wandb/sklearn/calculate/class_proportions.py +68 -0
  428. wandb/sklearn/calculate/confusion_matrix.py +92 -0
  429. wandb/sklearn/calculate/decision_boundaries.py +40 -0
  430. wandb/sklearn/calculate/elbow_curve.py +55 -0
  431. wandb/sklearn/calculate/feature_importances.py +67 -0
  432. wandb/sklearn/calculate/learning_curve.py +64 -0
  433. wandb/sklearn/calculate/outlier_candidates.py +69 -0
  434. wandb/sklearn/calculate/residuals.py +86 -0
  435. wandb/sklearn/calculate/silhouette.py +118 -0
  436. wandb/sklearn/calculate/summary_metrics.py +62 -0
  437. wandb/sklearn/plot/__init__.py +35 -0
  438. wandb/sklearn/plot/classifier.py +331 -0
  439. wandb/sklearn/plot/clusterer.py +142 -0
  440. wandb/sklearn/plot/regressor.py +121 -0
  441. wandb/sklearn/plot/shared.py +91 -0
  442. wandb/sklearn/utils.py +183 -0
  443. wandb/sync/__init__.py +3 -0
  444. wandb/sync/sync.py +443 -0
  445. wandb/testing/relay.py +859 -0
  446. wandb/trigger.py +29 -0
  447. wandb/util.py +1925 -0
  448. wandb/vendor/__init__.py +0 -0
  449. wandb/vendor/gql-0.2.0/setup.py +40 -0
  450. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  451. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  452. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  453. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  454. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  455. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  456. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  457. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  458. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  459. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  460. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  461. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  462. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  463. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  464. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  465. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  466. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  467. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  468. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  469. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  470. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  471. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  472. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  473. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  474. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  475. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  476. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  477. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  478. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  479. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  480. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  481. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  482. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  483. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  484. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  485. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  486. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  487. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  488. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  489. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  490. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  491. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  492. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  493. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  494. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  495. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  496. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  497. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  498. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  499. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  500. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  501. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  502. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  503. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  504. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  505. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  506. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  507. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  508. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  509. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  510. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  511. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  512. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  513. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  514. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  515. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  516. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  517. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  518. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  519. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  520. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  521. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  522. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  523. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  524. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  525. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  526. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  527. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  528. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  529. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  530. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  531. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  532. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  533. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  534. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  535. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  549. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  550. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  551. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  552. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  553. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  554. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  555. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  556. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  557. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  558. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  559. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  560. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  561. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  562. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  563. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  564. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  565. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  566. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  567. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  568. wandb/vendor/promise-2.3.0/setup.py +64 -0
  569. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  570. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  571. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  572. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  573. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  574. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  575. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  576. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  577. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  578. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  579. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  580. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  581. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  582. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  583. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  584. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  585. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  586. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  587. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  588. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  589. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  590. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  591. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  592. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  593. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  594. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  595. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  596. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  597. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  598. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  599. wandb/vendor/pygments/__init__.py +90 -0
  600. wandb/vendor/pygments/cmdline.py +568 -0
  601. wandb/vendor/pygments/console.py +74 -0
  602. wandb/vendor/pygments/filter.py +74 -0
  603. wandb/vendor/pygments/filters/__init__.py +350 -0
  604. wandb/vendor/pygments/formatter.py +95 -0
  605. wandb/vendor/pygments/formatters/__init__.py +153 -0
  606. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  607. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  608. wandb/vendor/pygments/formatters/html.py +851 -0
  609. wandb/vendor/pygments/formatters/img.py +600 -0
  610. wandb/vendor/pygments/formatters/irc.py +182 -0
  611. wandb/vendor/pygments/formatters/latex.py +482 -0
  612. wandb/vendor/pygments/formatters/other.py +160 -0
  613. wandb/vendor/pygments/formatters/rtf.py +147 -0
  614. wandb/vendor/pygments/formatters/svg.py +153 -0
  615. wandb/vendor/pygments/formatters/terminal.py +136 -0
  616. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  617. wandb/vendor/pygments/lexer.py +871 -0
  618. wandb/vendor/pygments/lexers/__init__.py +329 -0
  619. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  620. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  621. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  622. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  623. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  624. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  625. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  626. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  627. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  628. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  629. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  630. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  631. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  632. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  633. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  634. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  635. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  636. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  637. wandb/vendor/pygments/lexers/agile.py +24 -0
  638. wandb/vendor/pygments/lexers/algebra.py +221 -0
  639. wandb/vendor/pygments/lexers/ambient.py +76 -0
  640. wandb/vendor/pygments/lexers/ampl.py +87 -0
  641. wandb/vendor/pygments/lexers/apl.py +101 -0
  642. wandb/vendor/pygments/lexers/archetype.py +318 -0
  643. wandb/vendor/pygments/lexers/asm.py +641 -0
  644. wandb/vendor/pygments/lexers/automation.py +374 -0
  645. wandb/vendor/pygments/lexers/basic.py +500 -0
  646. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  647. wandb/vendor/pygments/lexers/business.py +612 -0
  648. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  649. wandb/vendor/pygments/lexers/c_like.py +541 -0
  650. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  651. wandb/vendor/pygments/lexers/chapel.py +102 -0
  652. wandb/vendor/pygments/lexers/clean.py +288 -0
  653. wandb/vendor/pygments/lexers/compiled.py +34 -0
  654. wandb/vendor/pygments/lexers/configs.py +833 -0
  655. wandb/vendor/pygments/lexers/console.py +114 -0
  656. wandb/vendor/pygments/lexers/crystal.py +393 -0
  657. wandb/vendor/pygments/lexers/csound.py +366 -0
  658. wandb/vendor/pygments/lexers/css.py +689 -0
  659. wandb/vendor/pygments/lexers/d.py +251 -0
  660. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  661. wandb/vendor/pygments/lexers/data.py +555 -0
  662. wandb/vendor/pygments/lexers/diff.py +165 -0
  663. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  664. wandb/vendor/pygments/lexers/dsls.py +878 -0
  665. wandb/vendor/pygments/lexers/dylan.py +289 -0
  666. wandb/vendor/pygments/lexers/ecl.py +125 -0
  667. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  668. wandb/vendor/pygments/lexers/elm.py +121 -0
  669. wandb/vendor/pygments/lexers/erlang.py +533 -0
  670. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  671. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  672. wandb/vendor/pygments/lexers/factor.py +344 -0
  673. wandb/vendor/pygments/lexers/fantom.py +250 -0
  674. wandb/vendor/pygments/lexers/felix.py +273 -0
  675. wandb/vendor/pygments/lexers/forth.py +177 -0
  676. wandb/vendor/pygments/lexers/fortran.py +205 -0
  677. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  678. wandb/vendor/pygments/lexers/functional.py +21 -0
  679. wandb/vendor/pygments/lexers/go.py +101 -0
  680. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  681. wandb/vendor/pygments/lexers/graph.py +80 -0
  682. wandb/vendor/pygments/lexers/graphics.py +553 -0
  683. wandb/vendor/pygments/lexers/haskell.py +843 -0
  684. wandb/vendor/pygments/lexers/haxe.py +936 -0
  685. wandb/vendor/pygments/lexers/hdl.py +382 -0
  686. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  687. wandb/vendor/pygments/lexers/html.py +602 -0
  688. wandb/vendor/pygments/lexers/idl.py +270 -0
  689. wandb/vendor/pygments/lexers/igor.py +288 -0
  690. wandb/vendor/pygments/lexers/inferno.py +96 -0
  691. wandb/vendor/pygments/lexers/installers.py +322 -0
  692. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  693. wandb/vendor/pygments/lexers/iolang.py +63 -0
  694. wandb/vendor/pygments/lexers/j.py +146 -0
  695. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  696. wandb/vendor/pygments/lexers/julia.py +333 -0
  697. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  698. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  699. wandb/vendor/pygments/lexers/make.py +202 -0
  700. wandb/vendor/pygments/lexers/markup.py +595 -0
  701. wandb/vendor/pygments/lexers/math.py +21 -0
  702. wandb/vendor/pygments/lexers/matlab.py +663 -0
  703. wandb/vendor/pygments/lexers/ml.py +769 -0
  704. wandb/vendor/pygments/lexers/modeling.py +358 -0
  705. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  706. wandb/vendor/pygments/lexers/monte.py +204 -0
  707. wandb/vendor/pygments/lexers/ncl.py +894 -0
  708. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  709. wandb/vendor/pygments/lexers/nit.py +64 -0
  710. wandb/vendor/pygments/lexers/nix.py +136 -0
  711. wandb/vendor/pygments/lexers/oberon.py +105 -0
  712. wandb/vendor/pygments/lexers/objective.py +504 -0
  713. wandb/vendor/pygments/lexers/ooc.py +85 -0
  714. wandb/vendor/pygments/lexers/other.py +41 -0
  715. wandb/vendor/pygments/lexers/parasail.py +79 -0
  716. wandb/vendor/pygments/lexers/parsers.py +835 -0
  717. wandb/vendor/pygments/lexers/pascal.py +644 -0
  718. wandb/vendor/pygments/lexers/pawn.py +199 -0
  719. wandb/vendor/pygments/lexers/perl.py +620 -0
  720. wandb/vendor/pygments/lexers/php.py +267 -0
  721. wandb/vendor/pygments/lexers/praat.py +294 -0
  722. wandb/vendor/pygments/lexers/prolog.py +306 -0
  723. wandb/vendor/pygments/lexers/python.py +939 -0
  724. wandb/vendor/pygments/lexers/qvt.py +152 -0
  725. wandb/vendor/pygments/lexers/r.py +453 -0
  726. wandb/vendor/pygments/lexers/rdf.py +270 -0
  727. wandb/vendor/pygments/lexers/rebol.py +431 -0
  728. wandb/vendor/pygments/lexers/resource.py +85 -0
  729. wandb/vendor/pygments/lexers/rnc.py +67 -0
  730. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  731. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  732. wandb/vendor/pygments/lexers/ruby.py +519 -0
  733. wandb/vendor/pygments/lexers/rust.py +220 -0
  734. wandb/vendor/pygments/lexers/sas.py +228 -0
  735. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  736. wandb/vendor/pygments/lexers/shell.py +794 -0
  737. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  738. wandb/vendor/pygments/lexers/smv.py +79 -0
  739. wandb/vendor/pygments/lexers/snobol.py +83 -0
  740. wandb/vendor/pygments/lexers/special.py +103 -0
  741. wandb/vendor/pygments/lexers/sql.py +681 -0
  742. wandb/vendor/pygments/lexers/stata.py +108 -0
  743. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  744. wandb/vendor/pygments/lexers/tcl.py +145 -0
  745. wandb/vendor/pygments/lexers/templates.py +2283 -0
  746. wandb/vendor/pygments/lexers/testing.py +207 -0
  747. wandb/vendor/pygments/lexers/text.py +25 -0
  748. wandb/vendor/pygments/lexers/textedit.py +169 -0
  749. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  750. wandb/vendor/pygments/lexers/theorem.py +458 -0
  751. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  752. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  753. wandb/vendor/pygments/lexers/urbi.py +133 -0
  754. wandb/vendor/pygments/lexers/varnish.py +190 -0
  755. wandb/vendor/pygments/lexers/verification.py +111 -0
  756. wandb/vendor/pygments/lexers/web.py +24 -0
  757. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  758. wandb/vendor/pygments/lexers/whiley.py +116 -0
  759. wandb/vendor/pygments/lexers/x10.py +69 -0
  760. wandb/vendor/pygments/modeline.py +44 -0
  761. wandb/vendor/pygments/plugin.py +68 -0
  762. wandb/vendor/pygments/regexopt.py +92 -0
  763. wandb/vendor/pygments/scanner.py +105 -0
  764. wandb/vendor/pygments/sphinxext.py +158 -0
  765. wandb/vendor/pygments/style.py +155 -0
  766. wandb/vendor/pygments/styles/__init__.py +80 -0
  767. wandb/vendor/pygments/styles/abap.py +29 -0
  768. wandb/vendor/pygments/styles/algol.py +63 -0
  769. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  770. wandb/vendor/pygments/styles/arduino.py +98 -0
  771. wandb/vendor/pygments/styles/autumn.py +65 -0
  772. wandb/vendor/pygments/styles/borland.py +51 -0
  773. wandb/vendor/pygments/styles/bw.py +49 -0
  774. wandb/vendor/pygments/styles/colorful.py +81 -0
  775. wandb/vendor/pygments/styles/default.py +73 -0
  776. wandb/vendor/pygments/styles/emacs.py +72 -0
  777. wandb/vendor/pygments/styles/friendly.py +72 -0
  778. wandb/vendor/pygments/styles/fruity.py +42 -0
  779. wandb/vendor/pygments/styles/igor.py +29 -0
  780. wandb/vendor/pygments/styles/lovelace.py +97 -0
  781. wandb/vendor/pygments/styles/manni.py +75 -0
  782. wandb/vendor/pygments/styles/monokai.py +106 -0
  783. wandb/vendor/pygments/styles/murphy.py +80 -0
  784. wandb/vendor/pygments/styles/native.py +65 -0
  785. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  786. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  787. wandb/vendor/pygments/styles/pastie.py +75 -0
  788. wandb/vendor/pygments/styles/perldoc.py +69 -0
  789. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  790. wandb/vendor/pygments/styles/rrt.py +33 -0
  791. wandb/vendor/pygments/styles/sas.py +44 -0
  792. wandb/vendor/pygments/styles/stata.py +40 -0
  793. wandb/vendor/pygments/styles/tango.py +141 -0
  794. wandb/vendor/pygments/styles/trac.py +63 -0
  795. wandb/vendor/pygments/styles/vim.py +63 -0
  796. wandb/vendor/pygments/styles/vs.py +38 -0
  797. wandb/vendor/pygments/styles/xcode.py +51 -0
  798. wandb/vendor/pygments/token.py +213 -0
  799. wandb/vendor/pygments/unistring.py +217 -0
  800. wandb/vendor/pygments/util.py +388 -0
  801. wandb/vendor/pynvml/__init__.py +0 -0
  802. wandb/vendor/pynvml/pynvml.py +4779 -0
  803. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  804. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  805. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  806. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  807. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  808. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  809. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  810. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  811. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  812. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  813. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  814. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  815. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  816. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  817. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  818. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  819. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  820. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  821. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  822. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  823. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  824. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  825. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  826. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  827. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  828. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  829. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  830. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  831. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  832. wandb/viz.py +123 -0
  833. wandb/wandb_agent.py +586 -0
  834. wandb/wandb_controller.py +720 -0
  835. wandb/wandb_run.py +9 -0
  836. wandb/wandb_torch.py +550 -0
  837. wandb/xgboost/__init__.py +9 -0
  838. wandb-0.17.0rc1.dist-info/METADATA +219 -0
  839. wandb-0.17.0rc1.dist-info/RECORD +842 -0
  840. wandb-0.17.0rc1.dist-info/WHEEL +4 -0
  841. wandb-0.17.0rc1.dist-info/entry_points.txt +3 -0
  842. wandb-0.17.0rc1.dist-info/licenses/LICENSE +21 -0
wandb/data_types.py ADDED
@@ -0,0 +1,2068 @@
1
+ """This module defines data types for logging rich, interactive visualizations to W&B.
2
+
3
+ Data types include common media types, like images, audio, and videos,
4
+ flexible containers for information, like tables and HTML, and more.
5
+
6
+ For more on logging media, see [our guide](https://docs.wandb.com/guides/track/log/media)
7
+
8
+ For more on logging structured data for interactive dataset and model analysis,
9
+ see [our guide to W&B Tables](https://docs.wandb.com/guides/data-vis).
10
+
11
+ All of these special data types are subclasses of WBValue. All the data types
12
+ serialize to JSON, since that is what wandb uses to save the objects locally
13
+ and upload them to the W&B server.
14
+ """
15
+
16
+ import base64
17
+ import binascii
18
+ import codecs
19
+ import datetime
20
+ import hashlib
21
+ import json
22
+ import logging
23
+ import os
24
+ import pprint
25
+ from decimal import Decimal
26
+ from typing import Optional
27
+
28
+ import wandb
29
+ from wandb import util
30
+ from wandb.sdk.lib import filesystem
31
+
32
+ from .sdk.data_types import _dtypes
33
+ from .sdk.data_types._private import MEDIA_TMP
34
+ from .sdk.data_types.base_types.media import (
35
+ BatchableMedia,
36
+ Media,
37
+ _numpy_arrays_to_lists,
38
+ )
39
+ from .sdk.data_types.base_types.wb_value import WBValue
40
+ from .sdk.data_types.helper_types.bounding_boxes_2d import BoundingBoxes2D
41
+ from .sdk.data_types.helper_types.classes import Classes
42
+ from .sdk.data_types.helper_types.image_mask import ImageMask
43
+ from .sdk.data_types.histogram import Histogram
44
+ from .sdk.data_types.html import Html
45
+ from .sdk.data_types.image import Image
46
+ from .sdk.data_types.molecule import Molecule
47
+ from .sdk.data_types.object_3d import Object3D
48
+ from .sdk.data_types.plotly import Plotly
49
+ from .sdk.data_types.saved_model import _SavedModel
50
+ from .sdk.data_types.trace_tree import WBTraceTree
51
+ from .sdk.data_types.video import Video
52
+ from .sdk.lib import runid
53
+
54
+ # Note: we are importing everything from the sdk/data_types to maintain a namespace for now.
55
+ # Once we fully type this file and move it all into sdk, then we will need to clean up the
56
+ # other internal imports
57
+
58
+ __all__ = [
59
+ # Untyped Exports
60
+ "Audio",
61
+ "Table",
62
+ "Bokeh",
63
+ # Typed Exports
64
+ "Histogram",
65
+ "Html",
66
+ "Image",
67
+ "Molecule",
68
+ "Object3D",
69
+ "Plotly",
70
+ "Video",
71
+ "WBTraceTree",
72
+ "_SavedModel",
73
+ # Typed Legacy Exports (I'd like to remove these)
74
+ "ImageMask",
75
+ "BoundingBoxes2D",
76
+ "Classes",
77
+ ]
78
+
79
+
80
+ class _TableLinkMixin:
81
+ def set_table(self, table):
82
+ self._table = table
83
+
84
+
85
+ class _TableKey(str, _TableLinkMixin):
86
+ def set_table(self, table, col_name):
87
+ assert col_name in table.columns
88
+ self._table = table
89
+ self._col_name = col_name
90
+
91
+
92
+ class _TableIndex(int, _TableLinkMixin):
93
+ def get_row(self):
94
+ row = {}
95
+ if self._table:
96
+ row = {
97
+ c: self._table.data[self][i] for i, c in enumerate(self._table.columns)
98
+ }
99
+
100
+ return row
101
+
102
+
103
+ def _json_helper(val, artifact):
104
+ if isinstance(val, WBValue):
105
+ return val.to_json(artifact)
106
+ elif val.__class__ == dict:
107
+ res = {}
108
+ for key in val:
109
+ res[key] = _json_helper(val[key], artifact)
110
+ return res
111
+
112
+ if hasattr(val, "tolist"):
113
+ py_val = val.tolist()
114
+ if val.__class__.__name__ == "datetime64" and isinstance(py_val, int):
115
+ # when numpy datetime64 .tolist() returns an int, it is nanoseconds.
116
+ # need to convert to milliseconds
117
+ return _json_helper(py_val / int(1e6), artifact)
118
+ return _json_helper(py_val, artifact)
119
+ elif hasattr(val, "item"):
120
+ return _json_helper(val.item(), artifact)
121
+
122
+ if isinstance(val, datetime.datetime):
123
+ if val.tzinfo is None:
124
+ val = datetime.datetime(
125
+ val.year,
126
+ val.month,
127
+ val.day,
128
+ val.hour,
129
+ val.minute,
130
+ val.second,
131
+ val.microsecond,
132
+ tzinfo=datetime.timezone.utc,
133
+ )
134
+ return int(val.timestamp() * 1000)
135
+ elif isinstance(val, datetime.date):
136
+ return int(
137
+ datetime.datetime(
138
+ val.year, val.month, val.day, tzinfo=datetime.timezone.utc
139
+ ).timestamp()
140
+ * 1000
141
+ )
142
+ elif isinstance(val, (list, tuple)):
143
+ return [_json_helper(i, artifact) for i in val]
144
+ elif isinstance(val, Decimal):
145
+ return float(val)
146
+ else:
147
+ return util.json_friendly(val)[0]
148
+
149
+
150
+ class Table(Media):
151
+ """The Table class used to display and analyze tabular data.
152
+
153
+ Unlike traditional spreadsheets, Tables support numerous types of data:
154
+ scalar values, strings, numpy arrays, and most subclasses of `wandb.data_types.Media`.
155
+ This means you can embed `Images`, `Video`, `Audio`, and other sorts of rich, annotated media
156
+ directly in Tables, alongside other traditional scalar values.
157
+
158
+ This class is the primary class used to generate the Table Visualizer
159
+ in the UI: https://docs.wandb.ai/guides/data-vis/tables.
160
+
161
+ Arguments:
162
+ columns: (List[str]) Names of the columns in the table.
163
+ Defaults to ["Input", "Output", "Expected"].
164
+ data: (List[List[any]]) 2D row-oriented array of values.
165
+ dataframe: (pandas.DataFrame) DataFrame object used to create the table.
166
+ When set, `data` and `columns` arguments are ignored.
167
+ optional: (Union[bool,List[bool]]) Determines if `None` values are allowed. Default to True
168
+ - If a singular bool value, then the optionality is enforced for all
169
+ columns specified at construction time
170
+ - If a list of bool values, then the optionality is applied to each
171
+ column - should be the same length as `columns`
172
+ applies to all columns. A list of bool values applies to each respective column.
173
+ allow_mixed_types: (bool) Determines if columns are allowed to have mixed types
174
+ (disables type validation). Defaults to False
175
+ """
176
+
177
+ MAX_ROWS = 10000
178
+ MAX_ARTIFACT_ROWS = 200000
179
+ _MAX_EMBEDDING_DIMENSIONS = 150
180
+ _log_type = "table"
181
+
182
+ def __init__(
183
+ self,
184
+ columns=None,
185
+ data=None,
186
+ rows=None,
187
+ dataframe=None,
188
+ dtype=None,
189
+ optional=True,
190
+ allow_mixed_types=False,
191
+ ):
192
+ """Initializes a Table object.
193
+
194
+ The rows is availble for legacy reasons and should not be used.
195
+ The Table class uses data to mimic the Pandas API.
196
+ """
197
+ super().__init__()
198
+ self._pk_col = None
199
+ self._fk_cols = set()
200
+ if allow_mixed_types:
201
+ dtype = _dtypes.AnyType
202
+
203
+ # This is kept for legacy reasons (tss: personally, I think we should remove this)
204
+ if columns is None:
205
+ columns = ["Input", "Output", "Expected"]
206
+
207
+ # Explicit dataframe option
208
+ if dataframe is not None:
209
+ self._init_from_dataframe(dataframe, columns, optional, dtype)
210
+ else:
211
+ # Expected pattern
212
+ if data is not None:
213
+ if util.is_numpy_array(data):
214
+ self._init_from_ndarray(data, columns, optional, dtype)
215
+ elif util.is_pandas_data_frame(data):
216
+ self._init_from_dataframe(data, columns, optional, dtype)
217
+ else:
218
+ self._init_from_list(data, columns, optional, dtype)
219
+
220
+ # legacy
221
+ elif rows is not None:
222
+ self._init_from_list(rows, columns, optional, dtype)
223
+
224
+ # Default empty case
225
+ else:
226
+ self._init_from_list([], columns, optional, dtype)
227
+
228
+ @staticmethod
229
+ def _assert_valid_columns(columns):
230
+ valid_col_types = [str, int]
231
+ assert isinstance(columns, list), "columns argument expects a `list` object"
232
+ assert len(columns) == 0 or all(
233
+ [type(col) in valid_col_types for col in columns]
234
+ ), "columns argument expects list of strings or ints"
235
+
236
+ def _init_from_list(self, data, columns, optional=True, dtype=None):
237
+ assert isinstance(data, list), "data argument expects a `list` object"
238
+ self.data = []
239
+ self._assert_valid_columns(columns)
240
+ self.columns = columns
241
+ self._make_column_types(dtype, optional)
242
+ for row in data:
243
+ self.add_data(*row)
244
+
245
+ def _init_from_ndarray(self, ndarray, columns, optional=True, dtype=None):
246
+ assert util.is_numpy_array(
247
+ ndarray
248
+ ), "ndarray argument expects a `numpy.ndarray` object"
249
+ self.data = []
250
+ self._assert_valid_columns(columns)
251
+ self.columns = columns
252
+ self._make_column_types(dtype, optional)
253
+ for row in ndarray:
254
+ self.add_data(*row)
255
+
256
+ def _init_from_dataframe(self, dataframe, columns, optional=True, dtype=None):
257
+ assert util.is_pandas_data_frame(
258
+ dataframe
259
+ ), "dataframe argument expects a `pandas.core.frame.DataFrame` object"
260
+ self.data = []
261
+ columns = list(dataframe.columns)
262
+ self._assert_valid_columns(columns)
263
+ self.columns = columns
264
+ self._make_column_types(dtype, optional)
265
+ for row in range(len(dataframe)):
266
+ self.add_data(*tuple(dataframe[col].values[row] for col in self.columns))
267
+
268
+ def _make_column_types(self, dtype=None, optional=True):
269
+ if dtype is None:
270
+ dtype = _dtypes.UnknownType()
271
+
272
+ if optional.__class__ != list:
273
+ optional = [optional for _ in range(len(self.columns))]
274
+
275
+ if dtype.__class__ != list:
276
+ dtype = [dtype for _ in range(len(self.columns))]
277
+
278
+ self._column_types = _dtypes.TypedDictType({})
279
+ for col_name, opt, dt in zip(self.columns, optional, dtype):
280
+ self.cast(col_name, dt, opt)
281
+
282
+ def cast(self, col_name, dtype, optional=False):
283
+ """Casts a column to a specific data type. This can be one of the normal python classes, an internal W&B type, or an example objec, like an instance of wandb.Image or wandb.Classes.
284
+
285
+ Arguments:
286
+ col_name: (str) - The name of the column to cast.
287
+ dtype: (class, wandb.wandb_sdk.interface._dtypes.Type, any) - The target dtype.
288
+ optional: (bool) - If the column should allow Nones.
289
+ """
290
+ assert col_name in self.columns
291
+
292
+ wbtype = _dtypes.TypeRegistry.type_from_dtype(dtype)
293
+
294
+ if optional:
295
+ wbtype = _dtypes.OptionalType(wbtype)
296
+
297
+ # Cast each value in the row, raising an error if there are invalid entries.
298
+ col_ndx = self.columns.index(col_name)
299
+ for row in self.data:
300
+ result_type = wbtype.assign(row[col_ndx])
301
+ if isinstance(result_type, _dtypes.InvalidType):
302
+ raise TypeError(
303
+ "Existing data {}, of type {} cannot be cast to {}".format(
304
+ row[col_ndx],
305
+ _dtypes.TypeRegistry.type_of(row[col_ndx]),
306
+ wbtype,
307
+ )
308
+ )
309
+ wbtype = result_type
310
+
311
+ # Assert valid options
312
+ is_pk = isinstance(wbtype, _PrimaryKeyType)
313
+ is_fk = isinstance(wbtype, _ForeignKeyType)
314
+ is_fi = isinstance(wbtype, _ForeignIndexType)
315
+ if is_pk or is_fk or is_fi:
316
+ assert (
317
+ not optional
318
+ ), "Primary keys, foreign keys, and foreign indexes cannot be optional."
319
+
320
+ if (is_fk or is_fk) and id(wbtype.params["table"]) == id(self):
321
+ raise AssertionError("Cannot set a foreign table reference to same table.")
322
+
323
+ if is_pk:
324
+ assert (
325
+ self._pk_col is None
326
+ ), "Cannot have multiple primary keys - {} is already set as the primary key.".format(
327
+ self._pk_col
328
+ )
329
+
330
+ # Update the column type
331
+ self._column_types.params["type_map"][col_name] = wbtype
332
+
333
+ # Wrap the data if needed
334
+ self._update_keys()
335
+ return wbtype
336
+
337
+ def __ne__(self, other):
338
+ return not self.__eq__(other)
339
+
340
+ def _eq_debug(self, other, should_assert=False):
341
+ eq = isinstance(other, Table)
342
+ assert not should_assert or eq, "Found type {}, expected {}".format(
343
+ other.__class__, Table
344
+ )
345
+ eq = eq and len(self.data) == len(other.data)
346
+ assert not should_assert or eq, "Found {} rows, expected {}".format(
347
+ len(other.data), len(self.data)
348
+ )
349
+ eq = eq and self.columns == other.columns
350
+ assert not should_assert or eq, "Found columns {}, expected {}".format(
351
+ other.columns, self.columns
352
+ )
353
+ eq = eq and self._column_types == other._column_types
354
+ assert (
355
+ not should_assert or eq
356
+ ), "Found column type {}, expected column type {}".format(
357
+ other._column_types, self._column_types
358
+ )
359
+ if eq:
360
+ for row_ndx in range(len(self.data)):
361
+ for col_ndx in range(len(self.data[row_ndx])):
362
+ _eq = self.data[row_ndx][col_ndx] == other.data[row_ndx][col_ndx]
363
+ # equal if all are equal
364
+ if util.is_numpy_array(_eq):
365
+ _eq = ((_eq * -1) + 1).sum() == 0
366
+ eq = eq and _eq
367
+ assert (
368
+ not should_assert or eq
369
+ ), "Unequal data at row_ndx {} col_ndx {}: found {}, expected {}".format(
370
+ row_ndx,
371
+ col_ndx,
372
+ other.data[row_ndx][col_ndx],
373
+ self.data[row_ndx][col_ndx],
374
+ )
375
+ if not eq:
376
+ return eq
377
+ return eq
378
+
379
+ def __eq__(self, other):
380
+ return self._eq_debug(other)
381
+
382
+ def add_row(self, *row):
383
+ """Deprecated; use add_data instead."""
384
+ logging.warning("add_row is deprecated, use add_data")
385
+ self.add_data(*row)
386
+
387
+ def add_data(self, *data):
388
+ """Adds a new row of data to the table. The maximum amount of rows in a table is determined by `wandb.Table.MAX_ARTIFACT_ROWS`.
389
+
390
+ The length of the data should match the length of the table column.
391
+ """
392
+ if len(data) != len(self.columns):
393
+ raise ValueError(
394
+ "This table expects {} columns: {}, found {}".format(
395
+ len(self.columns), self.columns, len(data)
396
+ )
397
+ )
398
+
399
+ # Special case to pre-emptively cast a column as a key.
400
+ # Needed as String.assign(Key) is invalid
401
+ for ndx, item in enumerate(data):
402
+ if isinstance(item, _TableLinkMixin):
403
+ self.cast(
404
+ self.columns[ndx],
405
+ _dtypes.TypeRegistry.type_of(item),
406
+ optional=False,
407
+ )
408
+
409
+ # Update the table's column types
410
+ result_type = self._get_updated_result_type(data)
411
+ self._column_types = result_type
412
+
413
+ # rows need to be mutable
414
+ if isinstance(data, tuple):
415
+ data = list(data)
416
+ # Add the new data
417
+ self.data.append(data)
418
+
419
+ # Update the wrapper values if needed
420
+ self._update_keys(force_last=True)
421
+
422
+ def _get_updated_result_type(self, row):
423
+ """Returns the updated result type based on the inputted row.
424
+
425
+ Raises:
426
+ TypeError: if the assignment is invalid.
427
+ """
428
+ incoming_row_dict = {
429
+ col_key: row[ndx] for ndx, col_key in enumerate(self.columns)
430
+ }
431
+ current_type = self._column_types
432
+ result_type = current_type.assign(incoming_row_dict)
433
+ if isinstance(result_type, _dtypes.InvalidType):
434
+ raise TypeError(
435
+ "Data row contained incompatible types:\n{}".format(
436
+ current_type.explain(incoming_row_dict)
437
+ )
438
+ )
439
+ return result_type
440
+
441
+ def _to_table_json(self, max_rows=None, warn=True):
442
+ # separate this method for easier testing
443
+ if max_rows is None:
444
+ max_rows = Table.MAX_ROWS
445
+ n_rows = len(self.data)
446
+ if n_rows > max_rows and warn:
447
+ if wandb.run and (
448
+ wandb.run.settings.table_raise_on_max_row_limit_exceeded
449
+ or wandb.run.settings.strict
450
+ ):
451
+ raise ValueError(
452
+ f"Table row limit exceeded: table has {n_rows} rows, limit is {max_rows}. "
453
+ f"To increase the maximum number of allowed rows in a wandb.Table, override "
454
+ f"the limit with `wandb.Table.MAX_ARTIFACT_ROWS = X` and try again. Note: "
455
+ f"this may cause slower queries in the W&B UI."
456
+ )
457
+ logging.warning("Truncating wandb.Table object to %i rows." % max_rows)
458
+ return {"columns": self.columns, "data": self.data[:max_rows]}
459
+
460
+ def bind_to_run(self, *args, **kwargs):
461
+ # We set `warn=False` since Tables will now always be logged to both
462
+ # files and artifacts. The file limit will never practically matter and
463
+ # this code path will be ultimately removed. The 10k limit warning confuses
464
+ # users given that we publicly say 200k is the limit.
465
+ data = self._to_table_json(warn=False)
466
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".table.json")
467
+ data = _numpy_arrays_to_lists(data)
468
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
469
+ util.json_dump_safer(data, fp)
470
+ self._set_file(tmp_path, is_tmp=True, extension=".table.json")
471
+ super().bind_to_run(*args, **kwargs)
472
+
473
+ @classmethod
474
+ def get_media_subdir(cls):
475
+ return os.path.join("media", "table")
476
+
477
+ @classmethod
478
+ def from_json(cls, json_obj, source_artifact):
479
+ data = []
480
+ column_types = None
481
+ np_deserialized_columns = {}
482
+ timestamp_column_indices = set()
483
+ if json_obj.get("column_types") is not None:
484
+ column_types = _dtypes.TypeRegistry.type_from_dict(
485
+ json_obj["column_types"], source_artifact
486
+ )
487
+ for col_name in column_types.params["type_map"]:
488
+ col_type = column_types.params["type_map"][col_name]
489
+ ndarray_type = None
490
+ if isinstance(col_type, _dtypes.NDArrayType):
491
+ ndarray_type = col_type
492
+ elif isinstance(col_type, _dtypes.UnionType):
493
+ for t in col_type.params["allowed_types"]:
494
+ if isinstance(t, _dtypes.NDArrayType):
495
+ ndarray_type = t
496
+ elif isinstance(t, _dtypes.TimestampType):
497
+ timestamp_column_indices.add(
498
+ json_obj["columns"].index(col_name)
499
+ )
500
+
501
+ elif isinstance(col_type, _dtypes.TimestampType):
502
+ timestamp_column_indices.add(json_obj["columns"].index(col_name))
503
+
504
+ if (
505
+ ndarray_type is not None
506
+ and ndarray_type._get_serialization_path() is not None
507
+ ):
508
+ serialization_path = ndarray_type._get_serialization_path()
509
+ np = util.get_module(
510
+ "numpy",
511
+ required="Deserializing NumPy columns requires NumPy to be installed.",
512
+ )
513
+ deserialized = np.load(
514
+ source_artifact.get_entry(serialization_path["path"]).download()
515
+ )
516
+ np_deserialized_columns[json_obj["columns"].index(col_name)] = (
517
+ deserialized[serialization_path["key"]]
518
+ )
519
+ ndarray_type._clear_serialization_path()
520
+
521
+ for r_ndx, row in enumerate(json_obj["data"]):
522
+ row_data = []
523
+ for c_ndx, item in enumerate(row):
524
+ cell = item
525
+ if c_ndx in timestamp_column_indices and isinstance(item, (int, float)):
526
+ cell = datetime.datetime.fromtimestamp(
527
+ item / 1000, tz=datetime.timezone.utc
528
+ )
529
+ elif c_ndx in np_deserialized_columns:
530
+ cell = np_deserialized_columns[c_ndx][r_ndx]
531
+ elif isinstance(item, dict) and "_type" in item:
532
+ obj = WBValue.init_from_json(item, source_artifact)
533
+ if obj is not None:
534
+ cell = obj
535
+ row_data.append(cell)
536
+ data.append(row_data)
537
+
538
+ # construct Table with dtypes for each column if type information exists
539
+ dtypes = None
540
+ if column_types is not None:
541
+ dtypes = [
542
+ column_types.params["type_map"][str(col)] for col in json_obj["columns"]
543
+ ]
544
+
545
+ new_obj = cls(columns=json_obj["columns"], data=data, dtype=dtypes)
546
+
547
+ if column_types is not None:
548
+ new_obj._column_types = column_types
549
+
550
+ new_obj._update_keys()
551
+ return new_obj
552
+
553
+ def to_json(self, run_or_artifact):
554
+ json_dict = super().to_json(run_or_artifact)
555
+
556
+ if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run):
557
+ json_dict.update(
558
+ {
559
+ "_type": "table-file",
560
+ "ncols": len(self.columns),
561
+ "nrows": len(self.data),
562
+ }
563
+ )
564
+
565
+ elif isinstance(run_or_artifact, wandb.Artifact):
566
+ artifact = run_or_artifact
567
+ mapped_data = []
568
+ data = self._to_table_json(Table.MAX_ARTIFACT_ROWS)["data"]
569
+
570
+ ndarray_col_ndxs = set()
571
+ for col_ndx, col_name in enumerate(self.columns):
572
+ col_type = self._column_types.params["type_map"][col_name]
573
+ ndarray_type = None
574
+ if isinstance(col_type, _dtypes.NDArrayType):
575
+ ndarray_type = col_type
576
+ elif isinstance(col_type, _dtypes.UnionType):
577
+ for t in col_type.params["allowed_types"]:
578
+ if isinstance(t, _dtypes.NDArrayType):
579
+ ndarray_type = t
580
+
581
+ # Do not serialize 1d arrays - these are likely embeddings and
582
+ # will not have the same cost as higher dimensional arrays
583
+ is_1d_array = (
584
+ ndarray_type is not None
585
+ and "shape" in ndarray_type._params
586
+ and isinstance(ndarray_type._params["shape"], list)
587
+ and len(ndarray_type._params["shape"]) == 1
588
+ and ndarray_type._params["shape"][0]
589
+ <= self._MAX_EMBEDDING_DIMENSIONS
590
+ )
591
+ if is_1d_array:
592
+ self._column_types.params["type_map"][col_name] = _dtypes.ListType(
593
+ _dtypes.NumberType, ndarray_type._params["shape"][0]
594
+ )
595
+ elif ndarray_type is not None:
596
+ np = util.get_module(
597
+ "numpy",
598
+ required="Serializing NumPy requires NumPy to be installed.",
599
+ )
600
+ file_name = f"{str(col_name)}_{runid.generate_id()}.npz"
601
+ npz_file_name = os.path.join(MEDIA_TMP.name, file_name)
602
+ np.savez_compressed(
603
+ npz_file_name,
604
+ **{
605
+ str(col_name): self.get_column(col_name, convert_to="numpy")
606
+ },
607
+ )
608
+ entry = artifact.add_file(
609
+ npz_file_name, "media/serialized_data/" + file_name, is_tmp=True
610
+ )
611
+ ndarray_type._set_serialization_path(entry.path, str(col_name))
612
+ ndarray_col_ndxs.add(col_ndx)
613
+
614
+ for row in data:
615
+ mapped_row = []
616
+ for ndx, v in enumerate(row):
617
+ if ndx in ndarray_col_ndxs:
618
+ mapped_row.append(None)
619
+ else:
620
+ mapped_row.append(_json_helper(v, artifact))
621
+ mapped_data.append(mapped_row)
622
+
623
+ json_dict.update(
624
+ {
625
+ "_type": Table._log_type,
626
+ "columns": self.columns,
627
+ "data": mapped_data,
628
+ "ncols": len(self.columns),
629
+ "nrows": len(mapped_data),
630
+ "column_types": self._column_types.to_json(artifact),
631
+ }
632
+ )
633
+ else:
634
+ raise ValueError("to_json accepts wandb_run.Run or wandb_artifact.Artifact")
635
+
636
+ return json_dict
637
+
638
+ def iterrows(self):
639
+ """Returns the table data by row, showing the index of the row and the relevant data.
640
+
641
+ Yields:
642
+ ------
643
+ index : int
644
+ The index of the row. Using this value in other W&B tables
645
+ will automatically build a relationship between the tables
646
+ row : List[any]
647
+ The data of the row.
648
+ """
649
+ for ndx in range(len(self.data)):
650
+ index = _TableIndex(ndx)
651
+ index.set_table(self)
652
+ yield index, self.data[ndx]
653
+
654
+ def set_pk(self, col_name):
655
+ # TODO: Docs
656
+ assert col_name in self.columns
657
+ self.cast(col_name, _PrimaryKeyType())
658
+
659
+ def set_fk(self, col_name, table, table_col):
660
+ # TODO: Docs
661
+ assert col_name in self.columns
662
+ assert col_name != self._pk_col
663
+ self.cast(col_name, _ForeignKeyType(table, table_col))
664
+
665
+ def _update_keys(self, force_last=False):
666
+ """Updates the known key-like columns based on current column types.
667
+
668
+ If the state has been updated since the last update, wraps the data
669
+ appropriately in the Key classes.
670
+
671
+ Arguments:
672
+ force_last: (bool) Wraps the last column of data even if there
673
+ are no key updates.
674
+ """
675
+ _pk_col = None
676
+ _fk_cols = set()
677
+
678
+ # Buildup the known keys from column types
679
+ c_types = self._column_types.params["type_map"]
680
+ for t in c_types:
681
+ if isinstance(c_types[t], _PrimaryKeyType):
682
+ _pk_col = t
683
+ elif isinstance(c_types[t], _ForeignKeyType) or isinstance(
684
+ c_types[t], _ForeignIndexType
685
+ ):
686
+ _fk_cols.add(t)
687
+
688
+ # If there are updates to perform, safely update them
689
+ has_update = _pk_col != self._pk_col or _fk_cols != self._fk_cols
690
+ if has_update:
691
+ # If we removed the PK
692
+ if _pk_col is None and self._pk_col is not None:
693
+ raise AssertionError(
694
+ f"Cannot unset primary key (column {self._pk_col})"
695
+ )
696
+ # If there is a removed FK
697
+ if len(self._fk_cols - _fk_cols) > 0:
698
+ raise AssertionError(
699
+ "Cannot unset foreign key. Attempted to unset ({})".format(
700
+ self._fk_cols - _fk_cols
701
+ )
702
+ )
703
+
704
+ self._pk_col = _pk_col
705
+ self._fk_cols = _fk_cols
706
+
707
+ # Apply updates to data only if there are update or the caller
708
+ # requested the final row to be updated
709
+ if has_update or force_last:
710
+ self._apply_key_updates(not has_update)
711
+
712
+ def _apply_key_updates(self, only_last=False):
713
+ """Appropriately wraps the underlying data in special Key classes.
714
+
715
+ Arguments:
716
+ only_last: only apply the updates to the last row (used for performance when
717
+ the caller knows that the only new data is the last row and no updates were
718
+ applied to the column types)
719
+ """
720
+ c_types = self._column_types.params["type_map"]
721
+
722
+ # Define a helper function which will wrap the data of a single row
723
+ # in the appropriate class wrapper.
724
+ def update_row(row_ndx):
725
+ for fk_col in self._fk_cols:
726
+ col_ndx = self.columns.index(fk_col)
727
+
728
+ # Wrap the Foreign Keys
729
+ if isinstance(c_types[fk_col], _ForeignKeyType) and not isinstance(
730
+ self.data[row_ndx][col_ndx], _TableKey
731
+ ):
732
+ self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx])
733
+ self.data[row_ndx][col_ndx].set_table(
734
+ c_types[fk_col].params["table"],
735
+ c_types[fk_col].params["col_name"],
736
+ )
737
+
738
+ # Wrap the Foreign Indexes
739
+ elif isinstance(c_types[fk_col], _ForeignIndexType) and not isinstance(
740
+ self.data[row_ndx][col_ndx], _TableIndex
741
+ ):
742
+ self.data[row_ndx][col_ndx] = _TableIndex(
743
+ self.data[row_ndx][col_ndx]
744
+ )
745
+ self.data[row_ndx][col_ndx].set_table(
746
+ c_types[fk_col].params["table"]
747
+ )
748
+
749
+ # Wrap the Primary Key
750
+ if self._pk_col is not None:
751
+ col_ndx = self.columns.index(self._pk_col)
752
+ self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx])
753
+ self.data[row_ndx][col_ndx].set_table(self, self._pk_col)
754
+
755
+ if only_last:
756
+ update_row(len(self.data) - 1)
757
+ else:
758
+ for row_ndx in range(len(self.data)):
759
+ update_row(row_ndx)
760
+
761
+ def add_column(self, name, data, optional=False):
762
+ """Adds a column of data to the table.
763
+
764
+ Arguments:
765
+ name: (str) - the unique name of the column
766
+ data: (list | np.array) - a column of homogenous data
767
+ optional: (bool) - if null-like values are permitted
768
+ """
769
+ assert isinstance(name, str) and name not in self.columns
770
+ is_np = util.is_numpy_array(data)
771
+ assert isinstance(data, list) or is_np
772
+ assert isinstance(optional, bool)
773
+ is_first_col = len(self.columns) == 0
774
+ assert is_first_col or len(data) == len(
775
+ self.data
776
+ ), f"Expected length {len(self.data)}, found {len(data)}"
777
+
778
+ # Add the new data
779
+ for ndx in range(max(len(data), len(self.data))):
780
+ if is_first_col:
781
+ self.data.append([])
782
+ if is_np:
783
+ self.data[ndx].append(data[ndx])
784
+ else:
785
+ self.data[ndx].append(data[ndx])
786
+ # add the column
787
+ self.columns.append(name)
788
+
789
+ try:
790
+ self.cast(name, _dtypes.UnknownType(), optional=optional)
791
+ except TypeError as err:
792
+ # Undo the changes
793
+ if is_first_col:
794
+ self.data = []
795
+ self.columns = []
796
+ else:
797
+ for ndx in range(len(self.data)):
798
+ self.data[ndx] = self.data[ndx][:-1]
799
+ self.columns = self.columns[:-1]
800
+ raise err
801
+
802
+ def get_column(self, name, convert_to=None):
803
+ """Retrieves a column from the table and optionally converts it to a NumPy object.
804
+
805
+ Arguments:
806
+ name: (str) - the name of the column
807
+ convert_to: (str, optional)
808
+ - "numpy": will convert the underlying data to numpy object
809
+ """
810
+ assert name in self.columns
811
+ assert convert_to is None or convert_to == "numpy"
812
+ if convert_to == "numpy":
813
+ np = util.get_module(
814
+ "numpy", required="Converting to NumPy requires installing NumPy"
815
+ )
816
+ col = []
817
+ col_ndx = self.columns.index(name)
818
+ for row in self.data:
819
+ item = row[col_ndx]
820
+ if convert_to is not None and isinstance(item, WBValue):
821
+ item = item.to_data_array()
822
+ col.append(item)
823
+ if convert_to == "numpy":
824
+ col = np.array(col)
825
+ return col
826
+
827
+ def get_index(self):
828
+ """Returns an array of row indexes for use in other tables to create links."""
829
+ ndxs = []
830
+ for ndx in range(len(self.data)):
831
+ index = _TableIndex(ndx)
832
+ index.set_table(self)
833
+ ndxs.append(index)
834
+ return ndxs
835
+
836
+ def get_dataframe(self):
837
+ """Returns a `pandas.DataFrame` of the table."""
838
+ pd = util.get_module(
839
+ "pandas",
840
+ required="Converting to pandas.DataFrame requires installing pandas",
841
+ )
842
+ return pd.DataFrame.from_records(self.data, columns=self.columns)
843
+
844
+ def index_ref(self, index):
845
+ """Gets a reference of the index of a row in the table."""
846
+ assert index < len(self.data)
847
+ _index = _TableIndex(index)
848
+ _index.set_table(self)
849
+ return _index
850
+
851
+ def add_computed_columns(self, fn):
852
+ """Adds one or more computed columns based on existing data.
853
+
854
+ Args:
855
+ fn: A function which accepts one or two parameters, ndx (int) and row (dict),
856
+ which is expected to return a dict representing new columns for that row, keyed
857
+ by the new column names.
858
+
859
+ `ndx` is an integer representing the index of the row. Only included if `include_ndx`
860
+ is set to `True`.
861
+
862
+ `row` is a dictionary keyed by existing columns
863
+ """
864
+ new_columns = {}
865
+ for ndx, row in self.iterrows():
866
+ row_dict = {self.columns[i]: row[i] for i in range(len(self.columns))}
867
+ new_row_dict = fn(ndx, row_dict)
868
+ assert isinstance(new_row_dict, dict)
869
+ for key in new_row_dict:
870
+ new_columns[key] = new_columns.get(key, [])
871
+ new_columns[key].append(new_row_dict[key])
872
+ for new_col_name in new_columns:
873
+ self.add_column(new_col_name, new_columns[new_col_name])
874
+
875
+
876
+ class _PartitionTablePartEntry:
877
+ """Helper class for PartitionTable to track its parts."""
878
+
879
+ def __init__(self, entry, source_artifact):
880
+ self.entry = entry
881
+ self.source_artifact = source_artifact
882
+ self._part = None
883
+
884
+ def get_part(self):
885
+ if self._part is None:
886
+ self._part = self.source_artifact.get(self.entry.path)
887
+ return self._part
888
+
889
+ def free(self):
890
+ self._part = None
891
+
892
+
893
+ class PartitionedTable(Media):
894
+ """A table which is composed of multiple sub-tables.
895
+
896
+ Currently, PartitionedTable is designed to point to a directory within an artifact.
897
+ """
898
+
899
+ _log_type = "partitioned-table"
900
+
901
+ def __init__(self, parts_path):
902
+ """Initialize a PartitionedTable.
903
+
904
+ Args:
905
+ parts_path (str): path to a directory of tables in the artifact.
906
+ """
907
+ super().__init__()
908
+ self.parts_path = parts_path
909
+ self._loaded_part_entries = {}
910
+
911
+ def to_json(self, artifact_or_run):
912
+ json_obj = {
913
+ "_type": PartitionedTable._log_type,
914
+ }
915
+ if isinstance(artifact_or_run, wandb.wandb_sdk.wandb_run.Run):
916
+ artifact_entry_url = self._get_artifact_entry_ref_url()
917
+ if artifact_entry_url is None:
918
+ raise ValueError(
919
+ "PartitionedTables must first be added to an Artifact before logging to a Run"
920
+ )
921
+ json_obj["artifact_path"] = artifact_entry_url
922
+ else:
923
+ json_obj["parts_path"] = self.parts_path
924
+ return json_obj
925
+
926
+ @classmethod
927
+ def from_json(cls, json_obj, source_artifact):
928
+ instance = cls(json_obj["parts_path"])
929
+ entries = source_artifact.manifest.get_entries_in_directory(
930
+ json_obj["parts_path"]
931
+ )
932
+ for entry in entries:
933
+ instance._add_part_entry(entry, source_artifact)
934
+ return instance
935
+
936
+ def iterrows(self):
937
+ """Iterate over rows as (ndx, row).
938
+
939
+ Yields:
940
+ ------
941
+ index : int
942
+ The index of the row.
943
+ row : List[any]
944
+ The data of the row.
945
+ """
946
+ columns = None
947
+ ndx = 0
948
+ for entry_path in self._loaded_part_entries:
949
+ part = self._loaded_part_entries[entry_path].get_part()
950
+ if columns is None:
951
+ columns = part.columns
952
+ elif columns != part.columns:
953
+ raise ValueError(
954
+ "Table parts have non-matching columns. {} != {}".format(
955
+ columns, part.columns
956
+ )
957
+ )
958
+ for _, row in part.iterrows():
959
+ yield ndx, row
960
+ ndx += 1
961
+
962
+ self._loaded_part_entries[entry_path].free()
963
+
964
+ def _add_part_entry(self, entry, source_artifact):
965
+ self._loaded_part_entries[entry.path] = _PartitionTablePartEntry(
966
+ entry, source_artifact
967
+ )
968
+
969
+ def __ne__(self, other):
970
+ return not self.__eq__(other)
971
+
972
+ def __eq__(self, other):
973
+ return isinstance(other, self.__class__) and self.parts_path == other.parts_path
974
+
975
+ def bind_to_run(self, *args, **kwargs):
976
+ raise ValueError("PartitionedTables cannot be bound to runs")
977
+
978
+
979
+ class Audio(BatchableMedia):
980
+ """Wandb class for audio clips.
981
+
982
+ Arguments:
983
+ data_or_path: (string or numpy array) A path to an audio file
984
+ or a numpy array of audio data.
985
+ sample_rate: (int) Sample rate, required when passing in raw
986
+ numpy array of audio data.
987
+ caption: (string) Caption to display with audio.
988
+ """
989
+
990
+ _log_type = "audio-file"
991
+
992
+ def __init__(self, data_or_path, sample_rate=None, caption=None):
993
+ """Accept a path to an audio file or a numpy array of audio data."""
994
+ super().__init__()
995
+ self._duration = None
996
+ self._sample_rate = sample_rate
997
+ self._caption = caption
998
+
999
+ if isinstance(data_or_path, str):
1000
+ if self.path_is_reference(data_or_path):
1001
+ self._path = data_or_path
1002
+ self._sha256 = hashlib.sha256(data_or_path.encode("utf-8")).hexdigest()
1003
+ self._is_tmp = False
1004
+ else:
1005
+ self._set_file(data_or_path, is_tmp=False)
1006
+ else:
1007
+ if sample_rate is None:
1008
+ raise ValueError(
1009
+ 'Argument "sample_rate" is required when instantiating wandb.Audio with raw data.'
1010
+ )
1011
+
1012
+ soundfile = util.get_module(
1013
+ "soundfile",
1014
+ required='Raw audio requires the soundfile package. To get it, run "pip install soundfile"',
1015
+ )
1016
+
1017
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".wav")
1018
+ soundfile.write(tmp_path, data_or_path, sample_rate)
1019
+ self._duration = len(data_or_path) / float(sample_rate)
1020
+
1021
+ self._set_file(tmp_path, is_tmp=True)
1022
+
1023
+ @classmethod
1024
+ def get_media_subdir(cls):
1025
+ return os.path.join("media", "audio")
1026
+
1027
+ @classmethod
1028
+ def from_json(cls, json_obj, source_artifact):
1029
+ return cls(
1030
+ source_artifact.get_entry(json_obj["path"]).download(),
1031
+ caption=json_obj["caption"],
1032
+ )
1033
+
1034
+ def bind_to_run(
1035
+ self, run, key, step, id_=None, ignore_copy_err: Optional[bool] = None
1036
+ ):
1037
+ if self.path_is_reference(self._path):
1038
+ raise ValueError(
1039
+ "Audio media created by a reference to external storage cannot currently be added to a run"
1040
+ )
1041
+
1042
+ return super().bind_to_run(run, key, step, id_, ignore_copy_err)
1043
+
1044
+ def to_json(self, run):
1045
+ json_dict = super().to_json(run)
1046
+ json_dict.update(
1047
+ {
1048
+ "_type": self._log_type,
1049
+ "caption": self._caption,
1050
+ }
1051
+ )
1052
+ return json_dict
1053
+
1054
+ @classmethod
1055
+ def seq_to_json(cls, seq, run, key, step):
1056
+ audio_list = list(seq)
1057
+
1058
+ util.get_module(
1059
+ "soundfile",
1060
+ required="wandb.Audio requires the soundfile package. To get it, run: pip install soundfile",
1061
+ )
1062
+ base_path = os.path.join(run.dir, "media", "audio")
1063
+ filesystem.mkdir_exists_ok(base_path)
1064
+ meta = {
1065
+ "_type": "audio",
1066
+ "count": len(audio_list),
1067
+ "audio": [a.to_json(run) for a in audio_list],
1068
+ }
1069
+ sample_rates = cls.sample_rates(audio_list)
1070
+ if sample_rates:
1071
+ meta["sampleRates"] = sample_rates
1072
+ durations = cls.durations(audio_list)
1073
+ if durations:
1074
+ meta["durations"] = durations
1075
+ captions = cls.captions(audio_list)
1076
+ if captions:
1077
+ meta["captions"] = captions
1078
+
1079
+ return meta
1080
+
1081
+ @classmethod
1082
+ def durations(cls, audio_list):
1083
+ return [a._duration for a in audio_list]
1084
+
1085
+ @classmethod
1086
+ def sample_rates(cls, audio_list):
1087
+ return [a._sample_rate for a in audio_list]
1088
+
1089
+ @classmethod
1090
+ def captions(cls, audio_list):
1091
+ captions = [a._caption for a in audio_list]
1092
+ if all(c is None for c in captions):
1093
+ return False
1094
+ else:
1095
+ return ["" if c is None else c for c in captions]
1096
+
1097
+ def resolve_ref(self):
1098
+ if self.path_is_reference(self._path):
1099
+ # this object was already created using a ref:
1100
+ return self._path
1101
+ source_artifact = self._artifact_source.artifact
1102
+
1103
+ resolved_name = source_artifact._local_path_to_name(self._path)
1104
+ if resolved_name is not None:
1105
+ target_entry = source_artifact.manifest.get_entry_by_path(resolved_name)
1106
+ if target_entry is not None:
1107
+ return target_entry.ref
1108
+
1109
+ return None
1110
+
1111
+ def __eq__(self, other):
1112
+ if self.path_is_reference(self._path) or self.path_is_reference(other._path):
1113
+ # one or more of these objects is an unresolved reference -- we'll compare
1114
+ # their reference paths instead of their SHAs:
1115
+ return (
1116
+ self.resolve_ref() == other.resolve_ref()
1117
+ and self._caption == other._caption
1118
+ )
1119
+
1120
+ return super().__eq__(other) and self._caption == other._caption
1121
+
1122
+ def __ne__(self, other):
1123
+ return not self.__eq__(other)
1124
+
1125
+
1126
+ class JoinedTable(Media):
1127
+ """Join two tables for visualization in the Artifact UI.
1128
+
1129
+ Arguments:
1130
+ table1 (str, wandb.Table, ArtifactManifestEntry):
1131
+ the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry
1132
+ table2 (str, wandb.Table):
1133
+ the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry
1134
+ join_key (str, [str, str]):
1135
+ key or keys to perform the join
1136
+ """
1137
+
1138
+ _log_type = "joined-table"
1139
+
1140
+ def __init__(self, table1, table2, join_key):
1141
+ super().__init__()
1142
+
1143
+ if not isinstance(join_key, str) and (
1144
+ not isinstance(join_key, list) or len(join_key) != 2
1145
+ ):
1146
+ raise ValueError(
1147
+ "JoinedTable join_key should be a string or a list of two strings"
1148
+ )
1149
+
1150
+ if not self._validate_table_input(table1):
1151
+ raise ValueError(
1152
+ "JoinedTable table1 should be an artifact path to a table or wandb.Table object"
1153
+ )
1154
+
1155
+ if not self._validate_table_input(table2):
1156
+ raise ValueError(
1157
+ "JoinedTable table2 should be an artifact path to a table or wandb.Table object"
1158
+ )
1159
+
1160
+ self._table1 = table1
1161
+ self._table2 = table2
1162
+ self._join_key = join_key
1163
+
1164
+ @classmethod
1165
+ def from_json(cls, json_obj, source_artifact):
1166
+ t1 = source_artifact.get(json_obj["table1"])
1167
+ if t1 is None:
1168
+ t1 = json_obj["table1"]
1169
+
1170
+ t2 = source_artifact.get(json_obj["table2"])
1171
+ if t2 is None:
1172
+ t2 = json_obj["table2"]
1173
+
1174
+ return cls(
1175
+ t1,
1176
+ t2,
1177
+ json_obj["join_key"],
1178
+ )
1179
+
1180
+ @staticmethod
1181
+ def _validate_table_input(table):
1182
+ """Helper method to validate that the table input is one of the 3 supported types."""
1183
+ return (
1184
+ (isinstance(table, str) and table.endswith(".table.json"))
1185
+ or isinstance(table, Table)
1186
+ or isinstance(table, PartitionedTable)
1187
+ or (hasattr(table, "ref_url") and table.ref_url().endswith(".table.json"))
1188
+ )
1189
+
1190
+ def _ensure_table_in_artifact(self, table, artifact, table_ndx):
1191
+ """Helper method to add the table to the incoming artifact. Returns the path."""
1192
+ if isinstance(table, Table) or isinstance(table, PartitionedTable):
1193
+ table_name = f"t{table_ndx}_{str(id(self))}"
1194
+ if (
1195
+ table._artifact_source is not None
1196
+ and table._artifact_source.name is not None
1197
+ ):
1198
+ table_name = os.path.basename(table._artifact_source.name)
1199
+ entry = artifact.add(table, table_name)
1200
+ table = entry.path
1201
+ # Check if this is an ArtifactManifestEntry
1202
+ elif hasattr(table, "ref_url"):
1203
+ # Give the new object a unique, yet deterministic name
1204
+ name = binascii.hexlify(base64.standard_b64decode(table.digest)).decode(
1205
+ "ascii"
1206
+ )[:20]
1207
+ entry = artifact.add_reference(
1208
+ table.ref_url(), "{}.{}.json".format(name, table.name.split(".")[-2])
1209
+ )[0]
1210
+ table = entry.path
1211
+
1212
+ err_str = "JoinedTable table:{} not found in artifact. Add a table to the artifact using Artifact#add(<table>, {}) before adding this JoinedTable"
1213
+ if table not in artifact._manifest.entries:
1214
+ raise ValueError(err_str.format(table, table))
1215
+
1216
+ return table
1217
+
1218
+ def to_json(self, artifact_or_run):
1219
+ json_obj = {
1220
+ "_type": JoinedTable._log_type,
1221
+ }
1222
+ if isinstance(artifact_or_run, wandb.wandb_sdk.wandb_run.Run):
1223
+ artifact_entry_url = self._get_artifact_entry_ref_url()
1224
+ if artifact_entry_url is None:
1225
+ raise ValueError(
1226
+ "JoinedTables must first be added to an Artifact before logging to a Run"
1227
+ )
1228
+ json_obj["artifact_path"] = artifact_entry_url
1229
+ else:
1230
+ table1 = self._ensure_table_in_artifact(self._table1, artifact_or_run, 1)
1231
+ table2 = self._ensure_table_in_artifact(self._table2, artifact_or_run, 2)
1232
+ json_obj.update(
1233
+ {
1234
+ "table1": table1,
1235
+ "table2": table2,
1236
+ "join_key": self._join_key,
1237
+ }
1238
+ )
1239
+ return json_obj
1240
+
1241
+ def __ne__(self, other):
1242
+ return not self.__eq__(other)
1243
+
1244
+ def _eq_debug(self, other, should_assert=False):
1245
+ eq = isinstance(other, JoinedTable)
1246
+ assert not should_assert or eq, "Found type {}, expected {}".format(
1247
+ other.__class__, JoinedTable
1248
+ )
1249
+ eq = eq and self._join_key == other._join_key
1250
+ assert not should_assert or eq, "Found {} join key, expected {}".format(
1251
+ other._join_key, self._join_key
1252
+ )
1253
+ eq = eq and self._table1._eq_debug(other._table1, should_assert)
1254
+ eq = eq and self._table2._eq_debug(other._table2, should_assert)
1255
+ return eq
1256
+
1257
+ def __eq__(self, other):
1258
+ return self._eq_debug(other, False)
1259
+
1260
+ def bind_to_run(self, *args, **kwargs):
1261
+ raise ValueError("JoinedTables cannot be bound to runs")
1262
+
1263
+
1264
+ class Bokeh(Media):
1265
+ """Wandb class for Bokeh plots.
1266
+
1267
+ Arguments:
1268
+ val: Bokeh plot
1269
+ """
1270
+
1271
+ _log_type = "bokeh-file"
1272
+
1273
+ def __init__(self, data_or_path):
1274
+ super().__init__()
1275
+ bokeh = util.get_module("bokeh", required=True)
1276
+ if isinstance(data_or_path, str) and os.path.exists(data_or_path):
1277
+ with open(data_or_path) as file:
1278
+ b_json = json.load(file)
1279
+ self.b_obj = bokeh.document.Document.from_json(b_json)
1280
+ self._set_file(data_or_path, is_tmp=False, extension=".bokeh.json")
1281
+ elif isinstance(data_or_path, bokeh.model.Model):
1282
+ _data = bokeh.document.Document()
1283
+ _data.add_root(data_or_path)
1284
+ # serialize/deserialize pairing followed by sorting attributes ensures
1285
+ # that the file's sha's are equivalent in subsequent calls
1286
+ self.b_obj = bokeh.document.Document.from_json(_data.to_json())
1287
+ b_json = self.b_obj.to_json()
1288
+ if "references" in b_json["roots"]:
1289
+ b_json["roots"]["references"].sort(key=lambda x: x["id"])
1290
+
1291
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".bokeh.json")
1292
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
1293
+ util.json_dump_safer(b_json, fp)
1294
+ self._set_file(tmp_path, is_tmp=True, extension=".bokeh.json")
1295
+ elif not isinstance(data_or_path, bokeh.document.Document):
1296
+ raise TypeError(
1297
+ "Bokeh constructor accepts Bokeh document/model or path to Bokeh json file"
1298
+ )
1299
+
1300
+ def get_media_subdir(self):
1301
+ return os.path.join("media", "bokeh")
1302
+
1303
+ def to_json(self, run):
1304
+ # TODO: (tss) this is getting redundant for all the media objects. We can probably
1305
+ # pull this into Media#to_json and remove this type override for all the media types.
1306
+ # There are only a few cases where the type is different between artifacts and runs.
1307
+ json_dict = super().to_json(run)
1308
+ json_dict["_type"] = self._log_type
1309
+ return json_dict
1310
+
1311
+ @classmethod
1312
+ def from_json(cls, json_obj, source_artifact):
1313
+ return cls(source_artifact.get_entry(json_obj["path"]).download())
1314
+
1315
+
1316
+ def _nest(thing):
1317
+ # Use tensorflows nest function if available, otherwise just wrap object in an array"""
1318
+
1319
+ tfutil = util.get_module("tensorflow.python.util")
1320
+ if tfutil:
1321
+ return tfutil.nest.flatten(thing)
1322
+ else:
1323
+ return [thing]
1324
+
1325
+
1326
+ class Graph(Media):
1327
+ """Wandb class for graphs.
1328
+
1329
+ This class is typically used for saving and displaying neural net models. It
1330
+ represents the graph as an array of nodes and edges. The nodes can have
1331
+ labels that can be visualized by wandb.
1332
+
1333
+ Examples:
1334
+ Import a keras model:
1335
+ ```
1336
+ Graph.from_keras(keras_model)
1337
+ ```
1338
+
1339
+ Attributes:
1340
+ format (string): Format to help wandb display the graph nicely.
1341
+ nodes ([wandb.Node]): List of wandb.Nodes
1342
+ nodes_by_id (dict): dict of ids -> nodes
1343
+ edges ([(wandb.Node, wandb.Node)]): List of pairs of nodes interpreted as edges
1344
+ loaded (boolean): Flag to tell whether the graph is completely loaded
1345
+ root (wandb.Node): root node of the graph
1346
+ """
1347
+
1348
+ _log_type = "graph-file"
1349
+
1350
+ def __init__(self, format="keras"):
1351
+ super().__init__()
1352
+ # LB: TODO: I think we should factor criterion and criterion_passed out
1353
+ self.format = format
1354
+ self.nodes = []
1355
+ self.nodes_by_id = {}
1356
+ self.edges = []
1357
+ self.loaded = False
1358
+ self.criterion = None
1359
+ self.criterion_passed = False
1360
+ self.root = None # optional root Node if applicable
1361
+
1362
+ def _to_graph_json(self, run=None):
1363
+ # Needs to be its own function for tests
1364
+ return {
1365
+ "format": self.format,
1366
+ "nodes": [node.to_json() for node in self.nodes],
1367
+ "edges": [edge.to_json() for edge in self.edges],
1368
+ }
1369
+
1370
+ def bind_to_run(self, *args, **kwargs):
1371
+ data = self._to_graph_json()
1372
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".graph.json")
1373
+ data = _numpy_arrays_to_lists(data)
1374
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
1375
+ util.json_dump_safer(data, fp)
1376
+ self._set_file(tmp_path, is_tmp=True, extension=".graph.json")
1377
+ if self.is_bound():
1378
+ return
1379
+ super().bind_to_run(*args, **kwargs)
1380
+
1381
+ @classmethod
1382
+ def get_media_subdir(cls):
1383
+ return os.path.join("media", "graph")
1384
+
1385
+ def to_json(self, run):
1386
+ json_dict = super().to_json(run)
1387
+ json_dict["_type"] = self._log_type
1388
+ return json_dict
1389
+
1390
+ def __getitem__(self, nid):
1391
+ return self.nodes_by_id[nid]
1392
+
1393
+ def pprint(self):
1394
+ for edge in self.edges:
1395
+ pprint.pprint(edge.attributes)
1396
+ for node in self.nodes:
1397
+ pprint.pprint(node.attributes)
1398
+
1399
+ def add_node(self, node=None, **node_kwargs):
1400
+ if node is None:
1401
+ node = Node(**node_kwargs)
1402
+ elif node_kwargs:
1403
+ raise ValueError(
1404
+ f"Only pass one of either node ({node}) or other keyword arguments ({node_kwargs})"
1405
+ )
1406
+ self.nodes.append(node)
1407
+ self.nodes_by_id[node.id] = node
1408
+
1409
+ return node
1410
+
1411
+ def add_edge(self, from_node, to_node):
1412
+ edge = Edge(from_node, to_node)
1413
+ self.edges.append(edge)
1414
+
1415
+ return edge
1416
+
1417
+ @classmethod
1418
+ def from_keras(cls, model):
1419
+ graph = cls()
1420
+ # Shamelessly copied (then modified) from keras/keras/utils/layer_utils.py
1421
+ sequential_like = cls._is_sequential(model)
1422
+
1423
+ relevant_nodes = None
1424
+ if not sequential_like:
1425
+ relevant_nodes = []
1426
+ for v in model._nodes_by_depth.values():
1427
+ relevant_nodes += v
1428
+
1429
+ layers = model.layers
1430
+ for i in range(len(layers)):
1431
+ node = Node.from_keras(layers[i])
1432
+ if hasattr(layers[i], "_inbound_nodes"):
1433
+ for in_node in layers[i]._inbound_nodes:
1434
+ if relevant_nodes and in_node not in relevant_nodes:
1435
+ # node is not part of the current network
1436
+ continue
1437
+ for in_layer in _nest(in_node.inbound_layers):
1438
+ inbound_keras_node = Node.from_keras(in_layer)
1439
+
1440
+ if inbound_keras_node.id not in graph.nodes_by_id:
1441
+ graph.add_node(inbound_keras_node)
1442
+ inbound_node = graph.nodes_by_id[inbound_keras_node.id]
1443
+
1444
+ graph.add_edge(inbound_node, node)
1445
+ graph.add_node(node)
1446
+ return graph
1447
+
1448
+ @classmethod
1449
+ def _is_sequential(cls, model):
1450
+ sequential_like = True
1451
+
1452
+ if (
1453
+ model.__class__.__name__ != "Sequential"
1454
+ and hasattr(model, "_is_graph_network")
1455
+ and model._is_graph_network
1456
+ ):
1457
+ nodes_by_depth = model._nodes_by_depth.values()
1458
+ nodes = []
1459
+ for v in nodes_by_depth:
1460
+ # TensorFlow2 doesn't insure inbound is always a list
1461
+ inbound = v[0].inbound_layers
1462
+ if not hasattr(inbound, "__len__"):
1463
+ inbound = [inbound]
1464
+ if (len(v) > 1) or (len(v) == 1 and len(inbound) > 1):
1465
+ # if the model has multiple nodes
1466
+ # or if the nodes have multiple inbound_layers
1467
+ # the model is no longer sequential
1468
+ sequential_like = False
1469
+ break
1470
+ nodes += v
1471
+ if sequential_like:
1472
+ # search for shared layers
1473
+ for layer in model.layers:
1474
+ flag = False
1475
+ if hasattr(layer, "_inbound_nodes"):
1476
+ for node in layer._inbound_nodes:
1477
+ if node in nodes:
1478
+ if flag:
1479
+ sequential_like = False
1480
+ break
1481
+ else:
1482
+ flag = True
1483
+ if not sequential_like:
1484
+ break
1485
+ return sequential_like
1486
+
1487
+
1488
+ class Node(WBValue):
1489
+ """Node used in `Graph`."""
1490
+
1491
+ def __init__(
1492
+ self,
1493
+ id=None,
1494
+ name=None,
1495
+ class_name=None,
1496
+ size=None,
1497
+ parameters=None,
1498
+ output_shape=None,
1499
+ is_output=None,
1500
+ num_parameters=None,
1501
+ node=None,
1502
+ ):
1503
+ self._attributes = {"name": None}
1504
+ self.in_edges = {} # indexed by source node id
1505
+ self.out_edges = {} # indexed by dest node id
1506
+ # optional object (e.g. PyTorch Parameter or Module) that this Node represents
1507
+ self.obj = None
1508
+
1509
+ if node is not None:
1510
+ self._attributes.update(node._attributes)
1511
+ del self._attributes["id"]
1512
+ self.obj = node.obj
1513
+
1514
+ if id is not None:
1515
+ self.id = id
1516
+ if name is not None:
1517
+ self.name = name
1518
+ if class_name is not None:
1519
+ self.class_name = class_name
1520
+ if size is not None:
1521
+ self.size = size
1522
+ if parameters is not None:
1523
+ self.parameters = parameters
1524
+ if output_shape is not None:
1525
+ self.output_shape = output_shape
1526
+ if is_output is not None:
1527
+ self.is_output = is_output
1528
+ if num_parameters is not None:
1529
+ self.num_parameters = num_parameters
1530
+
1531
+ def to_json(self, run=None):
1532
+ return self._attributes
1533
+
1534
+ def __repr__(self):
1535
+ return repr(self._attributes)
1536
+
1537
+ @property
1538
+ def id(self):
1539
+ """Must be unique in the graph."""
1540
+ return self._attributes.get("id")
1541
+
1542
+ @id.setter
1543
+ def id(self, val):
1544
+ self._attributes["id"] = val
1545
+ return val
1546
+
1547
+ @property
1548
+ def name(self):
1549
+ """Usually the type of layer or sublayer."""
1550
+ return self._attributes.get("name")
1551
+
1552
+ @name.setter
1553
+ def name(self, val):
1554
+ self._attributes["name"] = val
1555
+ return val
1556
+
1557
+ @property
1558
+ def class_name(self):
1559
+ """Usually the type of layer or sublayer."""
1560
+ return self._attributes.get("class_name")
1561
+
1562
+ @class_name.setter
1563
+ def class_name(self, val):
1564
+ self._attributes["class_name"] = val
1565
+ return val
1566
+
1567
+ @property
1568
+ def functions(self):
1569
+ return self._attributes.get("functions", [])
1570
+
1571
+ @functions.setter
1572
+ def functions(self, val):
1573
+ self._attributes["functions"] = val
1574
+ return val
1575
+
1576
+ @property
1577
+ def parameters(self):
1578
+ return self._attributes.get("parameters", [])
1579
+
1580
+ @parameters.setter
1581
+ def parameters(self, val):
1582
+ self._attributes["parameters"] = val
1583
+ return val
1584
+
1585
+ @property
1586
+ def size(self):
1587
+ return self._attributes.get("size")
1588
+
1589
+ @size.setter
1590
+ def size(self, val):
1591
+ """Tensor size."""
1592
+ self._attributes["size"] = tuple(val)
1593
+ return val
1594
+
1595
+ @property
1596
+ def output_shape(self):
1597
+ return self._attributes.get("output_shape")
1598
+
1599
+ @output_shape.setter
1600
+ def output_shape(self, val):
1601
+ """Tensor output_shape."""
1602
+ self._attributes["output_shape"] = val
1603
+ return val
1604
+
1605
+ @property
1606
+ def is_output(self):
1607
+ return self._attributes.get("is_output")
1608
+
1609
+ @is_output.setter
1610
+ def is_output(self, val):
1611
+ """Tensor is_output."""
1612
+ self._attributes["is_output"] = val
1613
+ return val
1614
+
1615
+ @property
1616
+ def num_parameters(self):
1617
+ return self._attributes.get("num_parameters")
1618
+
1619
+ @num_parameters.setter
1620
+ def num_parameters(self, val):
1621
+ """Tensor num_parameters."""
1622
+ self._attributes["num_parameters"] = val
1623
+ return val
1624
+
1625
+ @property
1626
+ def child_parameters(self):
1627
+ return self._attributes.get("child_parameters")
1628
+
1629
+ @child_parameters.setter
1630
+ def child_parameters(self, val):
1631
+ """Tensor child_parameters."""
1632
+ self._attributes["child_parameters"] = val
1633
+ return val
1634
+
1635
+ @property
1636
+ def is_constant(self):
1637
+ return self._attributes.get("is_constant")
1638
+
1639
+ @is_constant.setter
1640
+ def is_constant(self, val):
1641
+ """Tensor is_constant."""
1642
+ self._attributes["is_constant"] = val
1643
+ return val
1644
+
1645
+ @classmethod
1646
+ def from_keras(cls, layer):
1647
+ node = cls()
1648
+
1649
+ try:
1650
+ output_shape = layer.output_shape
1651
+ except AttributeError:
1652
+ output_shape = ["multiple"]
1653
+
1654
+ node.id = layer.name
1655
+ node.name = layer.name
1656
+ node.class_name = layer.__class__.__name__
1657
+ node.output_shape = output_shape
1658
+ node.num_parameters = layer.count_params()
1659
+
1660
+ return node
1661
+
1662
+
1663
+ class Edge(WBValue):
1664
+ """Edge used in `Graph`."""
1665
+
1666
+ def __init__(self, from_node, to_node):
1667
+ self._attributes = {}
1668
+ self.from_node = from_node
1669
+ self.to_node = to_node
1670
+
1671
+ def __repr__(self):
1672
+ temp_attr = dict(self._attributes)
1673
+ del temp_attr["from_node"]
1674
+ del temp_attr["to_node"]
1675
+ temp_attr["from_id"] = self.from_node.id
1676
+ temp_attr["to_id"] = self.to_node.id
1677
+ return str(temp_attr)
1678
+
1679
+ def to_json(self, run=None):
1680
+ return [self.from_node.id, self.to_node.id]
1681
+
1682
+ @property
1683
+ def name(self):
1684
+ """Optional, not necessarily unique."""
1685
+ return self._attributes.get("name")
1686
+
1687
+ @name.setter
1688
+ def name(self, val):
1689
+ self._attributes["name"] = val
1690
+ return val
1691
+
1692
+ @property
1693
+ def from_node(self):
1694
+ return self._attributes.get("from_node")
1695
+
1696
+ @from_node.setter
1697
+ def from_node(self, val):
1698
+ self._attributes["from_node"] = val
1699
+ return val
1700
+
1701
+ @property
1702
+ def to_node(self):
1703
+ return self._attributes.get("to_node")
1704
+
1705
+ @to_node.setter
1706
+ def to_node(self, val):
1707
+ self._attributes["to_node"] = val
1708
+ return val
1709
+
1710
+
1711
+ # Custom dtypes for typing system
1712
+ class _ImageFileType(_dtypes.Type):
1713
+ name = "image-file"
1714
+ legacy_names = ["wandb.Image"]
1715
+ types = [Image]
1716
+
1717
+ def __init__(
1718
+ self,
1719
+ box_layers=None,
1720
+ box_score_keys=None,
1721
+ mask_layers=None,
1722
+ class_map=None,
1723
+ **kwargs,
1724
+ ):
1725
+ box_layers = box_layers or {}
1726
+ box_score_keys = box_score_keys or []
1727
+ mask_layers = mask_layers or {}
1728
+ class_map = class_map or {}
1729
+
1730
+ if isinstance(box_layers, _dtypes.ConstType):
1731
+ box_layers = box_layers._params["val"]
1732
+ if not isinstance(box_layers, dict):
1733
+ raise TypeError("box_layers must be a dict")
1734
+ else:
1735
+ box_layers = _dtypes.ConstType(
1736
+ {layer_key: set(box_layers[layer_key]) for layer_key in box_layers}
1737
+ )
1738
+
1739
+ if isinstance(mask_layers, _dtypes.ConstType):
1740
+ mask_layers = mask_layers._params["val"]
1741
+ if not isinstance(mask_layers, dict):
1742
+ raise TypeError("mask_layers must be a dict")
1743
+ else:
1744
+ mask_layers = _dtypes.ConstType(
1745
+ {layer_key: set(mask_layers[layer_key]) for layer_key in mask_layers}
1746
+ )
1747
+
1748
+ if isinstance(box_score_keys, _dtypes.ConstType):
1749
+ box_score_keys = box_score_keys._params["val"]
1750
+ if not isinstance(box_score_keys, list) and not isinstance(box_score_keys, set):
1751
+ raise TypeError("box_score_keys must be a list or a set")
1752
+ else:
1753
+ box_score_keys = _dtypes.ConstType(set(box_score_keys))
1754
+
1755
+ if isinstance(class_map, _dtypes.ConstType):
1756
+ class_map = class_map._params["val"]
1757
+ if not isinstance(class_map, dict):
1758
+ raise TypeError("class_map must be a dict")
1759
+ else:
1760
+ class_map = _dtypes.ConstType(class_map)
1761
+
1762
+ self.params.update(
1763
+ {
1764
+ "box_layers": box_layers,
1765
+ "box_score_keys": box_score_keys,
1766
+ "mask_layers": mask_layers,
1767
+ "class_map": class_map,
1768
+ }
1769
+ )
1770
+
1771
+ def assign_type(self, wb_type=None):
1772
+ if isinstance(wb_type, _ImageFileType):
1773
+ box_layers_self = self.params["box_layers"].params["val"] or {}
1774
+ box_score_keys_self = self.params["box_score_keys"].params["val"] or []
1775
+ mask_layers_self = self.params["mask_layers"].params["val"] or {}
1776
+ class_map_self = self.params["class_map"].params["val"] or {}
1777
+
1778
+ box_layers_other = wb_type.params["box_layers"].params["val"] or {}
1779
+ box_score_keys_other = wb_type.params["box_score_keys"].params["val"] or []
1780
+ mask_layers_other = wb_type.params["mask_layers"].params["val"] or {}
1781
+ class_map_other = wb_type.params["class_map"].params["val"] or {}
1782
+
1783
+ # Merge the class_ids from each set of box_layers
1784
+ box_layers = {
1785
+ str(key): set(
1786
+ list(box_layers_self.get(key, []))
1787
+ + list(box_layers_other.get(key, []))
1788
+ )
1789
+ for key in set(
1790
+ list(box_layers_self.keys()) + list(box_layers_other.keys())
1791
+ )
1792
+ }
1793
+
1794
+ # Merge the class_ids from each set of mask_layers
1795
+ mask_layers = {
1796
+ str(key): set(
1797
+ list(mask_layers_self.get(key, []))
1798
+ + list(mask_layers_other.get(key, []))
1799
+ )
1800
+ for key in set(
1801
+ list(mask_layers_self.keys()) + list(mask_layers_other.keys())
1802
+ )
1803
+ }
1804
+
1805
+ # Merge the box score keys
1806
+ box_score_keys = set(list(box_score_keys_self) + list(box_score_keys_other))
1807
+
1808
+ # Merge the class_map
1809
+ class_map = {
1810
+ str(key): class_map_self.get(key, class_map_other.get(key, None))
1811
+ for key in set(
1812
+ list(class_map_self.keys()) + list(class_map_other.keys())
1813
+ )
1814
+ }
1815
+
1816
+ return _ImageFileType(box_layers, box_score_keys, mask_layers, class_map)
1817
+
1818
+ return _dtypes.InvalidType()
1819
+
1820
+ @classmethod
1821
+ def from_obj(cls, py_obj):
1822
+ if not isinstance(py_obj, Image):
1823
+ raise TypeError("py_obj must be a wandb.Image")
1824
+ else:
1825
+ if hasattr(py_obj, "_boxes") and py_obj._boxes:
1826
+ box_layers = {
1827
+ str(key): set(py_obj._boxes[key]._class_labels.keys())
1828
+ for key in py_obj._boxes.keys()
1829
+ }
1830
+ box_score_keys = {
1831
+ key
1832
+ for val in py_obj._boxes.values()
1833
+ for box in val._val
1834
+ for key in box.get("scores", {}).keys()
1835
+ }
1836
+
1837
+ else:
1838
+ box_layers = {}
1839
+ box_score_keys = set()
1840
+
1841
+ if hasattr(py_obj, "_masks") and py_obj._masks:
1842
+ mask_layers = {
1843
+ str(key): set(
1844
+ py_obj._masks[key]._val["class_labels"].keys()
1845
+ if hasattr(py_obj._masks[key], "_val")
1846
+ else []
1847
+ )
1848
+ for key in py_obj._masks.keys()
1849
+ }
1850
+ else:
1851
+ mask_layers = {}
1852
+
1853
+ if hasattr(py_obj, "_classes") and py_obj._classes:
1854
+ class_set = {
1855
+ str(item["id"]): item["name"] for item in py_obj._classes._class_set
1856
+ }
1857
+ else:
1858
+ class_set = {}
1859
+
1860
+ return cls(box_layers, box_score_keys, mask_layers, class_set)
1861
+
1862
+
1863
+ class _TableType(_dtypes.Type):
1864
+ name = "table"
1865
+ legacy_names = ["wandb.Table"]
1866
+ types = [Table]
1867
+
1868
+ def __init__(self, column_types=None):
1869
+ if column_types is None:
1870
+ column_types = _dtypes.UnknownType()
1871
+ if isinstance(column_types, dict):
1872
+ column_types = _dtypes.TypedDictType(column_types)
1873
+ elif not (
1874
+ isinstance(column_types, _dtypes.TypedDictType)
1875
+ or isinstance(column_types, _dtypes.UnknownType)
1876
+ ):
1877
+ raise TypeError("column_types must be a dict or TypedDictType")
1878
+
1879
+ self.params.update({"column_types": column_types})
1880
+
1881
+ def assign_type(self, wb_type=None):
1882
+ if isinstance(wb_type, _TableType):
1883
+ column_types = self.params["column_types"].assign_type(
1884
+ wb_type.params["column_types"]
1885
+ )
1886
+ if not isinstance(column_types, _dtypes.InvalidType):
1887
+ return _TableType(column_types)
1888
+
1889
+ return _dtypes.InvalidType()
1890
+
1891
+ @classmethod
1892
+ def from_obj(cls, py_obj):
1893
+ if not isinstance(py_obj, Table):
1894
+ raise TypeError("py_obj must be a wandb.Table")
1895
+ else:
1896
+ return cls(py_obj._column_types)
1897
+
1898
+
1899
+ class _ForeignKeyType(_dtypes.Type):
1900
+ name = "foreignKey"
1901
+ legacy_names = ["wandb.TableForeignKey"]
1902
+ types = [_TableKey]
1903
+
1904
+ def __init__(self, table, col_name):
1905
+ assert isinstance(table, Table)
1906
+ assert isinstance(col_name, str)
1907
+ assert col_name in table.columns
1908
+ self.params.update({"table": table, "col_name": col_name})
1909
+
1910
+ def assign_type(self, wb_type=None):
1911
+ if isinstance(wb_type, _dtypes.StringType):
1912
+ return self
1913
+ elif (
1914
+ isinstance(wb_type, _ForeignKeyType)
1915
+ and id(self.params["table"]) == id(wb_type.params["table"])
1916
+ and self.params["col_name"] == wb_type.params["col_name"]
1917
+ ):
1918
+ return self
1919
+
1920
+ return _dtypes.InvalidType()
1921
+
1922
+ @classmethod
1923
+ def from_obj(cls, py_obj):
1924
+ if not isinstance(py_obj, _TableKey):
1925
+ raise TypeError("py_obj must be a _TableKey")
1926
+ else:
1927
+ return cls(py_obj._table, py_obj._col_name)
1928
+
1929
+ def to_json(self, artifact=None):
1930
+ res = super().to_json(artifact)
1931
+ if artifact is not None:
1932
+ table_name = f"media/tables/t_{runid.generate_id()}"
1933
+ entry = artifact.add(self.params["table"], table_name)
1934
+ res["params"]["table"] = entry.path
1935
+ else:
1936
+ raise AssertionError(
1937
+ "_ForeignKeyType does not support serialization without an artifact"
1938
+ )
1939
+ return res
1940
+
1941
+ @classmethod
1942
+ def from_json(
1943
+ cls,
1944
+ json_dict,
1945
+ artifact,
1946
+ ):
1947
+ table = None
1948
+ col_name = None
1949
+ if artifact is None:
1950
+ raise AssertionError(
1951
+ "_ForeignKeyType does not support deserialization without an artifact"
1952
+ )
1953
+ else:
1954
+ table = artifact.get(json_dict["params"]["table"])
1955
+ col_name = json_dict["params"]["col_name"]
1956
+
1957
+ if table is None:
1958
+ raise AssertionError("Unable to deserialize referenced table")
1959
+
1960
+ return cls(table, col_name)
1961
+
1962
+
1963
+ class _ForeignIndexType(_dtypes.Type):
1964
+ name = "foreignIndex"
1965
+ legacy_names = ["wandb.TableForeignIndex"]
1966
+ types = [_TableIndex]
1967
+
1968
+ def __init__(self, table):
1969
+ assert isinstance(table, Table)
1970
+ self.params.update({"table": table})
1971
+
1972
+ def assign_type(self, wb_type=None):
1973
+ if isinstance(wb_type, _dtypes.NumberType):
1974
+ return self
1975
+ elif isinstance(wb_type, _ForeignIndexType) and id(self.params["table"]) == id(
1976
+ wb_type.params["table"]
1977
+ ):
1978
+ return self
1979
+
1980
+ return _dtypes.InvalidType()
1981
+
1982
+ @classmethod
1983
+ def from_obj(cls, py_obj):
1984
+ if not isinstance(py_obj, _TableIndex):
1985
+ raise TypeError("py_obj must be a _TableIndex")
1986
+ else:
1987
+ return cls(py_obj._table)
1988
+
1989
+ def to_json(self, artifact=None):
1990
+ res = super().to_json(artifact)
1991
+ if artifact is not None:
1992
+ table_name = f"media/tables/t_{runid.generate_id()}"
1993
+ entry = artifact.add(self.params["table"], table_name)
1994
+ res["params"]["table"] = entry.path
1995
+ else:
1996
+ raise AssertionError(
1997
+ "_ForeignIndexType does not support serialization without an artifact"
1998
+ )
1999
+ return res
2000
+
2001
+ @classmethod
2002
+ def from_json(
2003
+ cls,
2004
+ json_dict,
2005
+ artifact,
2006
+ ):
2007
+ table = None
2008
+ if artifact is None:
2009
+ raise AssertionError(
2010
+ "_ForeignIndexType does not support deserialization without an artifact"
2011
+ )
2012
+ else:
2013
+ table = artifact.get(json_dict["params"]["table"])
2014
+
2015
+ if table is None:
2016
+ raise AssertionError("Unable to deserialize referenced table")
2017
+
2018
+ return cls(table)
2019
+
2020
+
2021
+ class _PrimaryKeyType(_dtypes.Type):
2022
+ name = "primaryKey"
2023
+ legacy_names = ["wandb.TablePrimaryKey"]
2024
+
2025
+ def assign_type(self, wb_type=None):
2026
+ if isinstance(wb_type, _dtypes.StringType) or isinstance(
2027
+ wb_type, _PrimaryKeyType
2028
+ ):
2029
+ return self
2030
+ return _dtypes.InvalidType()
2031
+
2032
+ @classmethod
2033
+ def from_obj(cls, py_obj):
2034
+ if not isinstance(py_obj, _TableKey):
2035
+ raise TypeError("py_obj must be a wandb.Table")
2036
+ else:
2037
+ return cls()
2038
+
2039
+
2040
+ class _AudioFileType(_dtypes.Type):
2041
+ name = "audio-file"
2042
+ types = [Audio]
2043
+
2044
+
2045
+ class _BokehFileType(_dtypes.Type):
2046
+ name = "bokeh-file"
2047
+ types = [Bokeh]
2048
+
2049
+
2050
+ class _JoinedTableType(_dtypes.Type):
2051
+ name = "joined-table"
2052
+ types = [JoinedTable]
2053
+
2054
+
2055
+ class _PartitionedTableType(_dtypes.Type):
2056
+ name = "partitioned-table"
2057
+ types = [PartitionedTable]
2058
+
2059
+
2060
+ _dtypes.TypeRegistry.add(_AudioFileType)
2061
+ _dtypes.TypeRegistry.add(_BokehFileType)
2062
+ _dtypes.TypeRegistry.add(_ImageFileType)
2063
+ _dtypes.TypeRegistry.add(_TableType)
2064
+ _dtypes.TypeRegistry.add(_JoinedTableType)
2065
+ _dtypes.TypeRegistry.add(_PartitionedTableType)
2066
+ _dtypes.TypeRegistry.add(_ForeignKeyType)
2067
+ _dtypes.TypeRegistry.add(_PrimaryKeyType)
2068
+ _dtypes.TypeRegistry.add(_ForeignIndexType)