wandb 0.17.0__py3-none-win_amd64.whl

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