jasonfan commited on
Commit
09d838f
·
verified ·
1 Parent(s): 7a49752

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/INSTALLER +1 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/METADATA +239 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/RECORD +0 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/REQUESTED +0 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/WHEEL +5 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/entry_points.txt +3 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/licenses/LICENSE +21 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/__init__.py +11 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py +5 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py +131 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py +190 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py +230 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/keras.py +1084 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/__init__.py +6 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/helpers.py +28 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py +338 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py +182 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/langchain/__init__.py +3 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py +49 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightgbm/__init__.py +239 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/__init__.py +0 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py +3 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py +764 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/__init__.py +9 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py +74 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_pytorch.py +75 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_sklearn.py +76 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/errors.py +13 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/metaflow.py +327 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/__init__.py +3 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py +482 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/openai.py +22 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/resolver.py +243 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py +3 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/prodigy/prodigy.py +284 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sacred/__init__.py +117 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/__init__.py +14 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/auth.py +40 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/config.py +58 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/files.py +2 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/resources.py +63 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sb3/__init__.py +3 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sb3/sb3.py +151 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/__init__.py +37 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py +32 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py +125 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py +66 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py +93 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py +40 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py +55 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/METADATA ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: wandb
3
+ Version: 0.25.1
4
+ Summary: A CLI and library for interacting with the Weights & Biases API.
5
+ Project-URL: Source, https://github.com/wandb/wandb
6
+ Project-URL: Bug Reports, https://github.com/wandb/wandb/issues
7
+ Project-URL: Documentation, https://docs.wandb.ai/
8
+ Author-email: Weights & Biases <support@wandb.com>
9
+ License: MIT License
10
+
11
+ Copyright (c) 2021 Weights and Biases, Inc.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Classifier: Development Status :: 5 - Production/Stable
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Natural Language :: English
36
+ Classifier: Programming Language :: Go
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3 :: Only
39
+ Classifier: Programming Language :: Python :: 3.9
40
+ Classifier: Programming Language :: Python :: 3.10
41
+ Classifier: Programming Language :: Python :: 3.11
42
+ Classifier: Programming Language :: Python :: 3.12
43
+ Classifier: Programming Language :: Python :: 3.13
44
+ Classifier: Programming Language :: Python :: 3.14
45
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
46
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
47
+ Classifier: Topic :: System :: Logging
48
+ Classifier: Topic :: System :: Monitoring
49
+ Requires-Python: >=3.9
50
+ Requires-Dist: click>=8.0.1
51
+ Requires-Dist: eval-type-backport; python_version < '3.10'
52
+ Requires-Dist: gitpython!=3.1.29,>=1.0.0
53
+ Requires-Dist: packaging
54
+ Requires-Dist: platformdirs
55
+ Requires-Dist: protobuf!=5.28.0,!=5.29.0,<7,>4.21.0
56
+ Requires-Dist: pydantic<3
57
+ Requires-Dist: pyyaml
58
+ Requires-Dist: requests<3,>=2.0.0
59
+ Requires-Dist: sentry-sdk>=2.0.0
60
+ Requires-Dist: typing-extensions<5,>=4.8
61
+ Provides-Extra: aws
62
+ Requires-Dist: boto3; extra == 'aws'
63
+ Requires-Dist: botocore>=1.5.76; extra == 'aws'
64
+ Provides-Extra: azure
65
+ Requires-Dist: azure-identity; extra == 'azure'
66
+ Requires-Dist: azure-storage-blob; extra == 'azure'
67
+ Provides-Extra: gcp
68
+ Requires-Dist: google-cloud-storage; extra == 'gcp'
69
+ Provides-Extra: importers
70
+ Requires-Dist: filelock; extra == 'importers'
71
+ Requires-Dist: mlflow; extra == 'importers'
72
+ Requires-Dist: polars<=1.2.1; extra == 'importers'
73
+ Requires-Dist: rich; extra == 'importers'
74
+ Requires-Dist: tenacity; extra == 'importers'
75
+ Provides-Extra: kubeflow
76
+ Requires-Dist: google-cloud-storage; extra == 'kubeflow'
77
+ Requires-Dist: kubernetes; extra == 'kubeflow'
78
+ Requires-Dist: minio; extra == 'kubeflow'
79
+ Requires-Dist: sh; extra == 'kubeflow'
80
+ Provides-Extra: launch
81
+ Requires-Dist: awscli; extra == 'launch'
82
+ Requires-Dist: azure-containerregistry; extra == 'launch'
83
+ Requires-Dist: azure-identity; extra == 'launch'
84
+ Requires-Dist: azure-storage-blob; extra == 'launch'
85
+ Requires-Dist: boto3; extra == 'launch'
86
+ Requires-Dist: botocore>=1.5.76; extra == 'launch'
87
+ Requires-Dist: chardet; extra == 'launch'
88
+ Requires-Dist: google-auth; extra == 'launch'
89
+ Requires-Dist: google-cloud-aiplatform; extra == 'launch'
90
+ Requires-Dist: google-cloud-artifact-registry; extra == 'launch'
91
+ Requires-Dist: google-cloud-compute; extra == 'launch'
92
+ Requires-Dist: google-cloud-storage; extra == 'launch'
93
+ Requires-Dist: iso8601; extra == 'launch'
94
+ Requires-Dist: jsonschema; extra == 'launch'
95
+ Requires-Dist: kubernetes; extra == 'launch'
96
+ Requires-Dist: kubernetes-asyncio; extra == 'launch'
97
+ Requires-Dist: nbconvert; extra == 'launch'
98
+ Requires-Dist: nbformat; extra == 'launch'
99
+ Requires-Dist: optuna; extra == 'launch'
100
+ Requires-Dist: pydantic; extra == 'launch'
101
+ Requires-Dist: pyyaml>=6.0.0; extra == 'launch'
102
+ Requires-Dist: tomli; extra == 'launch'
103
+ Requires-Dist: tornado>=6.5.0; (python_version >= '3.9') and extra == 'launch'
104
+ Requires-Dist: typing-extensions; extra == 'launch'
105
+ Provides-Extra: media
106
+ Requires-Dist: bokeh; extra == 'media'
107
+ Requires-Dist: imageio>=2.28.1; extra == 'media'
108
+ Requires-Dist: moviepy>=1.0.0; extra == 'media'
109
+ Requires-Dist: numpy; extra == 'media'
110
+ Requires-Dist: pillow; extra == 'media'
111
+ Requires-Dist: plotly>=5.18.0; extra == 'media'
112
+ Requires-Dist: rdkit; extra == 'media'
113
+ Requires-Dist: soundfile; extra == 'media'
114
+ Provides-Extra: models
115
+ Requires-Dist: cloudpickle; extra == 'models'
116
+ Provides-Extra: perf
117
+ Requires-Dist: orjson; extra == 'perf'
118
+ Provides-Extra: sweeps
119
+ Requires-Dist: sweeps>=0.2.0; extra == 'sweeps'
120
+ Provides-Extra: workspaces
121
+ Requires-Dist: wandb-workspaces; extra == 'workspaces'
122
+ Description-Content-Type: text/markdown
123
+
124
+ <div align="center">
125
+ <img src="https://i.imgur.com/dQLeGCc.png" width="600" /><br><br>
126
+ </div>
127
+
128
+ <p align="center">
129
+ <a href="https://pypi.python.org/pypi/wandb"><img src="https://img.shields.io/pypi/v/wandb" /></a>
130
+ <a href="https://anaconda.org/conda-forge/wandb"><img src="https://img.shields.io/conda/vn/conda-forge/wandb" /></a>
131
+ <a href="https://pypi.python.org/pypi/wandb"><img src="https://img.shields.io/pypi/pyversions/wandb" /></a>
132
+ <a href="https://circleci.com/gh/wandb/wandb"><img src="https://img.shields.io/circleci/build/github/wandb/wandb/main" /></a>
133
+ <a href="https://codecov.io/gh/wandb/wandb"><img src="https://img.shields.io/codecov/c/gh/wandb/wandb" /></a>
134
+ </p>
135
+ <p align='center'>
136
+ <a href="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/intro/Intro_to_Weights_%26_Biases.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" /></a>
137
+ </p>
138
+
139
+ Use W&B to build better models faster. Track and visualize all the pieces of your machine learning pipeline, from datasets to production machine learning models. Get started with W&B today, [sign up for a W&B account](https://wandb.com?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=readme)!
140
+
141
+ <br>
142
+
143
+ Building an LLM app? Track, debug, evaluate, and monitor LLM apps with [Weave](https://wandb.github.io/weave?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=readme), our new suite of tools for GenAI.
144
+
145
+ &nbsp;
146
+
147
+ # Documentation
148
+
149
+ See the [W&B Developer Guide](https://docs.wandb.ai/?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) and [API Reference Guide](https://docs.wandb.ai/training/api-reference#api-overview?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) for a full technical description of the W&B platform.
150
+
151
+ &nbsp;
152
+
153
+ # Quickstart
154
+
155
+ Install W&B to track, visualize, and manage machine learning experiments of any size.
156
+
157
+ ## Install the wandb library
158
+
159
+ ```shell
160
+ pip install wandb
161
+ ```
162
+
163
+ ## Sign up and create an API key
164
+
165
+ Sign up for a [W&B account](https://wandb.ai/login?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=quickstart). Optionally, use the `wandb login` CLI to configure an API key on your machine. You can skip this step -- W&B will prompt you for an API key the first time you use it.
166
+
167
+ ## Create a machine learning training experiment
168
+
169
+ In your Python script or notebook, initialize a W&B run with `wandb.init()`.
170
+ Specify hyperparameters and log metrics and other information to W&B.
171
+
172
+ ```python
173
+ import wandb
174
+
175
+ # Project that the run is recorded to
176
+ project = "my-awesome-project"
177
+
178
+ # Dictionary with hyperparameters
179
+ config = {"epochs" : 1337, "lr" : 3e-4}
180
+
181
+ # The `with` syntax marks the run as finished upon exiting the `with` block,
182
+ # and it marks the run "failed" if there's an exception.
183
+ #
184
+ # In a notebook, it may be more convenient to write `run = wandb.init()`
185
+ # and manually call `run.finish()` instead of using a `with` block.
186
+ with wandb.init(project=project, config=config) as run:
187
+ # Training code here
188
+
189
+ # Log values to W&B with run.log()
190
+ run.log({"accuracy": 0.9, "loss": 0.1})
191
+ ```
192
+
193
+ Visit [wandb.ai/home](https://wandb.ai/home) to view recorded metrics such as accuracy and loss and how they changed during each training step. Each run object appears in the Runs column with generated names.
194
+
195
+ &nbsp;
196
+
197
+ # Integrations
198
+
199
+ W&B [integrates](https://docs.wandb.ai/models/integrations) with popular ML frameworks and libraries making it fast and easy to set up experiment tracking and data versioning inside existing projects.
200
+
201
+ For developers adding W&B to a new framework, follow the [W&B Developer Guide](https://docs.wandb.ai/models/integrations/add-wandb-to-any-library).
202
+
203
+ &nbsp;
204
+
205
+ # W&B Hosting Options
206
+
207
+ Weights & Biases is available in the cloud or installed on your private infrastructure. Set up a W&B Server in a production environment in one of three ways:
208
+
209
+ 1. [Multi-tenant Cloud](https://docs.wandb.ai/platform/hosting/hosting-options/multi_tenant_cloud?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Fully managed platform deployed in W&B’s Google Cloud Platform (GCP) account in GCP’s North America regions.
210
+ 2. [Dedicated Cloud](https://docs.wandb.ai/platform/hosting/hosting-options/dedicated_cloud?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Single-tenant, fully managed platform deployed in W&B’s AWS, GCP, or Azure cloud accounts. Each Dedicated Cloud instance has its own isolated network, compute and storage from other W&B Dedicated Cloud instances.
211
+ 3. [Self-Managed](https://docs.wandb.ai/platform/hosting/hosting-options/self-managed?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Deploy W&B Server on your AWS, GCP, or Azure cloud account or within your on-premises infrastructure.
212
+
213
+ See the [Hosting documentation](https://docs.wandb.ai/guides/hosting?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting) in the W&B Developer Guide for more information.
214
+
215
+ &nbsp;
216
+
217
+ # Python Version Support
218
+
219
+ We are committed to supporting our minimum required Python version for _at least_ six months after its official end-of-life (EOL) date, as defined by the Python Software Foundation. You can find a list of Python EOL dates [here](https://devguide.python.org/versions/).
220
+
221
+ When we discontinue support for a Python version, we will increment the library’s minor version number to reflect this change.
222
+
223
+ &nbsp;
224
+
225
+ # Contribution guidelines
226
+
227
+ Weights & Biases ❤️ open source, and we welcome contributions from the community! See the [Contribution guide](https://github.com/wandb/wandb/blob/main/CONTRIBUTING.md) for more information on the development workflow and the internals of the wandb library. For wandb bugs and feature requests, visit [GitHub Issues](https://github.com/wandb/wandb/issues) or contact support@wandb.com.
228
+
229
+ &nbsp;
230
+
231
+ # W&B Community
232
+
233
+ Be a part of the growing W&B Community and interact with the W&B team in our [Discord](https://wandb.me/discord). Stay connected with the latest ML updates and tutorials with [W&B Fully Connected](https://wandb.ai/fully-connected).
234
+
235
+ &nbsp;
236
+
237
+ # License
238
+
239
+ [MIT License](https://github.com/wandb/wandb/blob/main/LICENSE)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/REQUESTED ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-manylinux_2_28_x86_64
5
+
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ wandb = wandb.cli.cli:cli
3
+ wb = wandb.cli.cli:cli
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb-0.25.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Weights and Biases, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for integrating `wandb` with [`Keras`](https://keras.io/)."""
2
+
3
+ __all__ = (
4
+ "WandbCallback",
5
+ "WandbMetricsLogger",
6
+ "WandbModelCheckpoint",
7
+ "WandbEvalCallback",
8
+ )
9
+
10
+ from .callbacks import WandbEvalCallback, WandbMetricsLogger, WandbModelCheckpoint
11
+ from .keras import WandbCallback # TODO: legacy callback to be deprecated
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __all__ = ("WandbMetricsLogger", "WandbModelCheckpoint", "WandbEvalCallback")
2
+
3
+ from .metrics_logger import WandbMetricsLogger
4
+ from .model_checkpoint import WandbModelCheckpoint
5
+ from .tables_builder import WandbEvalCallback
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal
4
+
5
+ import tensorflow as tf # type: ignore
6
+ from tensorflow.keras import callbacks
7
+
8
+ import wandb
9
+ from wandb.integration.keras.keras import patch_tf_keras
10
+ from wandb.sdk.lib import telemetry
11
+
12
+ LogStrategy = Literal["epoch", "batch"]
13
+
14
+
15
+ patch_tf_keras()
16
+
17
+
18
+ class WandbMetricsLogger(callbacks.Callback):
19
+ """Logger that sends system metrics to W&B.
20
+
21
+ `WandbMetricsLogger` automatically logs the `logs` dictionary that callback methods
22
+ take as argument to wandb.
23
+
24
+ This callback automatically logs the following to a W&B run page:
25
+ * system (CPU/GPU/TPU) metrics,
26
+ * train and validation metrics defined in `model.compile`,
27
+ * learning rate (both for a fixed value or a learning rate scheduler)
28
+
29
+ Notes:
30
+ If you resume training by passing `initial_epoch` to `model.fit` and you are using a
31
+ learning rate scheduler, make sure to pass `initial_global_step` to
32
+ `WandbMetricsLogger`. The `initial_global_step` is `step_size * initial_step`, where
33
+ `step_size` is number of training steps per epoch. `step_size` can be calculated as
34
+ the product of the cardinality of the training dataset and the batch size.
35
+
36
+ Args:
37
+ log_freq: ("epoch", "batch", or int) if "epoch", logs metrics
38
+ at the end of each epoch. If "batch", logs metrics at the end
39
+ of each batch. If an integer, logs metrics at the end of that
40
+ many batches. Defaults to "epoch".
41
+ initial_global_step: (int) Use this argument to correctly log the
42
+ learning rate when you resume training from some `initial_epoch`,
43
+ and a learning rate scheduler is used. This can be computed as
44
+ `step_size * initial_step`. Defaults to 0.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ log_freq: LogStrategy | int = "epoch",
50
+ initial_global_step: int = 0,
51
+ *args: Any,
52
+ **kwargs: Any,
53
+ ) -> None:
54
+ super().__init__(*args, **kwargs)
55
+
56
+ if wandb.run is None:
57
+ raise wandb.Error(
58
+ "You must call `wandb.init()` before WandbMetricsLogger()"
59
+ )
60
+
61
+ with telemetry.context(run=wandb.run) as tel:
62
+ tel.feature.keras_metrics_logger = True
63
+
64
+ if log_freq == "batch":
65
+ log_freq = 1
66
+
67
+ self.logging_batch_wise = isinstance(log_freq, int)
68
+ self.log_freq: Any = log_freq if self.logging_batch_wise else None
69
+ self.global_batch = 0
70
+ self.global_step = initial_global_step
71
+
72
+ if self.logging_batch_wise:
73
+ # define custom x-axis for batch logging.
74
+ wandb.define_metric("batch/batch_step")
75
+ # set all batch metrics to be logged against batch_step.
76
+ wandb.define_metric("batch/*", step_metric="batch/batch_step")
77
+ else:
78
+ # define custom x-axis for epoch-wise logging.
79
+ wandb.define_metric("epoch/epoch")
80
+ # set all epoch-wise metrics to be logged against epoch.
81
+ wandb.define_metric("epoch/*", step_metric="epoch/epoch")
82
+
83
+ def _get_lr(self) -> float | None:
84
+ if isinstance(
85
+ self.model.optimizer.learning_rate,
86
+ (tf.Variable, tf.Tensor),
87
+ ) or (
88
+ hasattr(self.model.optimizer.learning_rate, "shape")
89
+ and self.model.optimizer.learning_rate.shape == ()
90
+ ):
91
+ return float(self.model.optimizer.learning_rate.numpy().item())
92
+ try:
93
+ return float(
94
+ self.model.optimizer.learning_rate(step=self.global_step).numpy().item()
95
+ )
96
+ except Exception as e:
97
+ wandb.termerror(f"Unable to log learning rate: {e}", repeat=False)
98
+ return None
99
+
100
+ def on_epoch_end(self, epoch: int, logs: dict[str, Any] | None = None) -> None:
101
+ """Called at the end of an epoch."""
102
+ logs = dict() if logs is None else {f"epoch/{k}": v for k, v in logs.items()}
103
+
104
+ logs["epoch/epoch"] = epoch
105
+
106
+ lr = self._get_lr()
107
+ if lr is not None:
108
+ logs["epoch/learning_rate"] = lr
109
+
110
+ wandb.log(logs)
111
+
112
+ def on_batch_end(self, batch: int, logs: dict[str, Any] | None = None) -> None:
113
+ self.global_step += 1
114
+ """An alias for `on_train_batch_end` for backwards compatibility."""
115
+ if self.logging_batch_wise and batch % self.log_freq == 0:
116
+ logs = {f"batch/{k}": v for k, v in logs.items()} if logs else {}
117
+ logs["batch/batch_step"] = self.global_batch
118
+
119
+ lr = self._get_lr()
120
+ if lr is not None:
121
+ logs["batch/learning_rate"] = lr
122
+
123
+ wandb.log(logs)
124
+
125
+ self.global_batch += self.log_freq
126
+
127
+ def on_train_batch_end(
128
+ self, batch: int, logs: dict[str, Any] | None = None
129
+ ) -> None:
130
+ """Called at the end of a training batch in `fit` methods."""
131
+ self.on_batch_end(batch, logs if logs else {})
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import string
5
+ from typing import Any, Literal
6
+
7
+ import tensorflow as tf # type: ignore
8
+ from tensorflow.keras import callbacks # type: ignore
9
+
10
+ import wandb
11
+ from wandb.sdk.lib import telemetry
12
+ from wandb.sdk.lib.paths import StrPath
13
+
14
+ from ..keras import patch_tf_keras
15
+
16
+ Mode = Literal["auto", "min", "max"]
17
+ SaveStrategy = Literal["epoch"]
18
+
19
+ patch_tf_keras()
20
+
21
+
22
+ class WandbModelCheckpoint(callbacks.ModelCheckpoint):
23
+ """A checkpoint that periodically saves a Keras model or model weights.
24
+
25
+ Saved weights are uploaded to W&B as a `wandb.Artifact`.
26
+
27
+ Since this callback is subclassed from `tf.keras.callbacks.ModelCheckpoint`, the
28
+ checkpointing logic is taken care of by the parent callback. You can learn more
29
+ here: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint
30
+
31
+ This callback is to be used in conjunction with training using `model.fit()` to save
32
+ a model or weights (in a checkpoint file) at some interval. The model checkpoints
33
+ will be logged as W&B Artifacts. You can learn more here:
34
+ https://docs.wandb.ai/guides/artifacts
35
+
36
+ This callback provides the following features:
37
+ - Save the model that has achieved "best performance" based on "monitor".
38
+ - Save the model at the end of every epoch regardless of the performance.
39
+ - Save the model at the end of epoch or after a fixed number of training batches.
40
+ - Save only model weights, or save the whole model.
41
+ - Save the model either in SavedModel format or in `.h5` format.
42
+
43
+ Args:
44
+ filepath: (Union[str, os.PathLike]) path to save the model file. `filepath`
45
+ can contain named formatting options, which will be filled by the value
46
+ of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example:
47
+ if `filepath` is `model-{epoch:02d}-{val_loss:.2f}`, then the
48
+ model checkpoints will be saved with the epoch number and the
49
+ validation loss in the filename.
50
+ monitor: (str) The metric name to monitor. Default to "val_loss".
51
+ verbose: (int) Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
52
+ displays messages when the callback takes an action.
53
+ save_best_only: (bool) if `save_best_only=True`, it only saves when the model
54
+ is considered the "best" and the latest best model according to the
55
+ quantity monitored will not be overwritten. If `filepath` doesn't contain
56
+ formatting options like `{epoch}` then `filepath` will be overwritten by
57
+ each new better model locally. The model logged as an artifact will still be
58
+ associated with the correct `monitor`. Artifacts will be uploaded
59
+ continuously and versioned separately as a new best model is found.
60
+ save_weights_only: (bool) if True, then only the model's weights will be saved.
61
+ mode: (Mode) one of {'auto', 'min', 'max'}. For `val_acc`, this should be `max`,
62
+ for `val_loss` this should be `min`, etc.
63
+ save_freq: (Union[SaveStrategy, int]) `epoch` or integer. When using `'epoch'`,
64
+ the callback saves the model after each epoch. When using an integer, the
65
+ callback saves the model at end of this many batches.
66
+ Note that when monitoring validation metrics such as `val_acc` or `val_loss`,
67
+ save_freq must be set to "epoch" as those metrics are only available at the
68
+ end of an epoch.
69
+ initial_value_threshold: (Optional[float]) Floating point initial "best" value of the metric
70
+ to be monitored.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ filepath: StrPath,
76
+ monitor: str = "val_loss",
77
+ verbose: int = 0,
78
+ save_best_only: bool = False,
79
+ save_weights_only: bool = False,
80
+ mode: Mode = "auto",
81
+ save_freq: SaveStrategy | int = "epoch",
82
+ initial_value_threshold: float | None = None,
83
+ **kwargs: Any,
84
+ ) -> None:
85
+ super().__init__(
86
+ filepath=filepath,
87
+ monitor=monitor,
88
+ verbose=verbose,
89
+ save_best_only=save_best_only,
90
+ save_weights_only=save_weights_only,
91
+ mode=mode,
92
+ save_freq=save_freq,
93
+ initial_value_threshold=initial_value_threshold,
94
+ **kwargs,
95
+ )
96
+ if wandb.run is None:
97
+ raise wandb.Error(
98
+ "You must call `wandb.init()` before `WandbModelCheckpoint()`"
99
+ )
100
+ with telemetry.context(run=wandb.run) as tel:
101
+ tel.feature.keras_model_checkpoint = True
102
+
103
+ self.save_weights_only = save_weights_only
104
+
105
+ # User-friendly warning when trying to save the best model.
106
+ if self.save_best_only:
107
+ self._check_filepath()
108
+
109
+ self._is_old_tf_keras_version: bool | None = None
110
+
111
+ def on_train_batch_end(
112
+ self, batch: int, logs: dict[str, float] | None = None
113
+ ) -> None:
114
+ if self._should_save_on_batch(batch):
115
+ if self.is_old_tf_keras_version:
116
+ # Save the model and get filepath
117
+ self._save_model(epoch=self._current_epoch, logs=logs)
118
+ filepath = self._get_file_path(epoch=self._current_epoch, logs=logs)
119
+ else:
120
+ # Save the model and get filepath
121
+ self._save_model(epoch=self._current_epoch, batch=batch, logs=logs)
122
+ filepath = self._get_file_path(
123
+ epoch=self._current_epoch, batch=batch, logs=logs
124
+ )
125
+ # Log the model as artifact
126
+ aliases = ["latest", f"epoch_{self._current_epoch}_batch_{batch}"]
127
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
128
+
129
+ def on_epoch_end(self, epoch: int, logs: dict[str, float] | None = None) -> None:
130
+ super().on_epoch_end(epoch, logs)
131
+ # Check if model checkpoint is created at the end of epoch.
132
+ if self.save_freq == "epoch":
133
+ # Get filepath where the model checkpoint is saved.
134
+ if self.is_old_tf_keras_version:
135
+ filepath = self._get_file_path(epoch=epoch, logs=logs)
136
+ else:
137
+ filepath = self._get_file_path(epoch=epoch, batch=None, logs=logs)
138
+ # Log the model as artifact
139
+ aliases = ["latest", f"epoch_{epoch}"]
140
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
141
+
142
+ def _log_ckpt_as_artifact(
143
+ self, filepath: str, aliases: list[str] | None = None
144
+ ) -> None:
145
+ """Log model checkpoint as W&B Artifact."""
146
+ try:
147
+ assert wandb.run is not None
148
+ model_checkpoint_artifact = wandb.Artifact(
149
+ f"run_{wandb.run.id}_model", type="model"
150
+ )
151
+ if os.path.isfile(filepath):
152
+ model_checkpoint_artifact.add_file(filepath)
153
+ elif os.path.isdir(filepath):
154
+ model_checkpoint_artifact.add_dir(filepath)
155
+ else:
156
+ raise FileNotFoundError(f"No such file or directory {filepath}")
157
+ wandb.log_artifact(model_checkpoint_artifact, aliases=aliases or [])
158
+ except ValueError:
159
+ # This error occurs when `save_best_only=True` and the model
160
+ # checkpoint is not saved for that epoch/batch. Since TF/Keras
161
+ # is giving friendly log, we can avoid clustering the stdout.
162
+ pass
163
+
164
+ def _check_filepath(self) -> None:
165
+ placeholders = []
166
+ for tup in string.Formatter().parse(self.filepath):
167
+ if tup[1] is not None:
168
+ placeholders.append(tup[1])
169
+ if len(placeholders) == 0:
170
+ wandb.termwarn(
171
+ "When using `save_best_only`, ensure that the `filepath` argument "
172
+ "contains formatting placeholders like `{epoch:02d}` or `{batch:02d}`. "
173
+ "This ensures correct interpretation of the logged artifacts.",
174
+ repeat=False,
175
+ )
176
+
177
+ @property
178
+ def is_old_tf_keras_version(self) -> bool | None:
179
+ if self._is_old_tf_keras_version is None:
180
+ from packaging.version import parse
181
+
182
+ try:
183
+ if parse(tf.keras.__version__) < parse("2.6.0"):
184
+ self._is_old_tf_keras_version = True
185
+ else:
186
+ self._is_old_tf_keras_version = False
187
+ except AttributeError:
188
+ self._is_old_tf_keras_version = False
189
+
190
+ return self._is_old_tf_keras_version
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ from typing import Any
5
+
6
+ from tensorflow.keras.callbacks import Callback # type: ignore
7
+
8
+ import wandb
9
+ from wandb.sdk.lib import telemetry
10
+
11
+
12
+ class WandbEvalCallback(Callback, abc.ABC):
13
+ """Abstract base class to build Keras callbacks for model prediction visualization.
14
+
15
+ You can build callbacks for visualizing model predictions `on_epoch_end`
16
+ that can be passed to `model.fit()` for classification, object detection,
17
+ segmentation, etc. tasks.
18
+
19
+ To use this, inherit from this base callback class and implement the
20
+ `add_ground_truth` and `add_model_prediction` methods.
21
+
22
+ The base class will take care of the following:
23
+ - Initialize `data_table` for logging the ground truth and
24
+ `pred_table` for predictions.
25
+ - The data uploaded to `data_table` is used as a reference for the
26
+ `pred_table`. This is to reduce the memory footprint. The `data_table_ref`
27
+ is a list that can be used to access the referenced data.
28
+ Check out the example below to see how it's done.
29
+ - Log the tables to W&B as W&B Artifacts.
30
+ - Each new `pred_table` is logged as a new version with aliases.
31
+
32
+ Example:
33
+ ```python
34
+ class WandbClfEvalCallback(WandbEvalCallback):
35
+ def __init__(self, validation_data, data_table_columns, pred_table_columns):
36
+ super().__init__(data_table_columns, pred_table_columns)
37
+
38
+ self.x = validation_data[0]
39
+ self.y = validation_data[1]
40
+
41
+ def add_ground_truth(self):
42
+ for idx, (image, label) in enumerate(zip(self.x, self.y)):
43
+ self.data_table.add_data(idx, wandb.Image(image), label)
44
+
45
+ def add_model_predictions(self, epoch):
46
+ preds = self.model.predict(self.x, verbose=0)
47
+ preds = tf.argmax(preds, axis=-1)
48
+
49
+ data_table_ref = self.data_table_ref
50
+ table_idxs = data_table_ref.get_index()
51
+
52
+ for idx in table_idxs:
53
+ pred = preds[idx]
54
+ self.pred_table.add_data(
55
+ epoch,
56
+ data_table_ref.data[idx][0],
57
+ data_table_ref.data[idx][1],
58
+ data_table_ref.data[idx][2],
59
+ pred,
60
+ )
61
+
62
+
63
+ model.fit(
64
+ x,
65
+ y,
66
+ epochs=2,
67
+ validation_data=(x, y),
68
+ callbacks=[
69
+ WandbClfEvalCallback(
70
+ validation_data=(x, y),
71
+ data_table_columns=["idx", "image", "label"],
72
+ pred_table_columns=["epoch", "idx", "image", "label", "pred"],
73
+ )
74
+ ],
75
+ )
76
+ ```
77
+
78
+ To have more fine-grained control, you can override the `on_train_begin` and
79
+ `on_epoch_end` methods. If you want to log the samples after N batched, you
80
+ can implement `on_train_batch_end` method.
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ data_table_columns: list[str],
86
+ pred_table_columns: list[str],
87
+ *args: Any,
88
+ **kwargs: Any,
89
+ ) -> None:
90
+ super().__init__(*args, **kwargs)
91
+
92
+ if wandb.run is None:
93
+ raise wandb.Error(
94
+ "You must call `wandb.init()` first before using this callback."
95
+ )
96
+
97
+ with telemetry.context(run=wandb.run) as tel:
98
+ tel.feature.keras_wandb_eval_callback = True
99
+
100
+ self.data_table_columns = data_table_columns
101
+ self.pred_table_columns = pred_table_columns
102
+
103
+ def on_train_begin(self, logs: dict[str, float] | None = None) -> None:
104
+ # Initialize the data_table
105
+ self.init_data_table(column_names=self.data_table_columns)
106
+ # Log the ground truth data
107
+ self.add_ground_truth(logs)
108
+ # Log the data_table as W&B Artifacts
109
+ self.log_data_table()
110
+
111
+ def on_epoch_end(self, epoch: int, logs: dict[str, float] | None = None) -> None:
112
+ # Initialize the pred_table
113
+ self.init_pred_table(column_names=self.pred_table_columns)
114
+ # Log the model prediction
115
+ self.add_model_predictions(epoch, logs)
116
+ # Log the pred_table as W&B Artifacts
117
+ self.log_pred_table()
118
+
119
+ @abc.abstractmethod
120
+ def add_ground_truth(self, logs: dict[str, float] | None = None) -> None:
121
+ """Add ground truth data to `data_table`.
122
+
123
+ Use this method to write the logic for adding validation/training data to
124
+ `data_table` initialized using `init_data_table` method.
125
+
126
+ Example:
127
+ ```python
128
+ for idx, data in enumerate(dataloader):
129
+ self.data_table.add_data(idx, data)
130
+ ```
131
+ This method is called once `on_train_begin` or equivalent hook.
132
+ """
133
+ raise NotImplementedError(f"{self.__class__.__name__}.add_ground_truth")
134
+
135
+ @abc.abstractmethod
136
+ def add_model_predictions(
137
+ self, epoch: int, logs: dict[str, float] | None = None
138
+ ) -> None:
139
+ """Add a prediction from a model to `pred_table`.
140
+
141
+ Use this method to write the logic for adding model prediction for validation/
142
+ training data to `pred_table` initialized using `init_pred_table` method.
143
+
144
+ Example:
145
+ ```python
146
+ # Assuming the dataloader is not shuffling the samples.
147
+ for idx, data in enumerate(dataloader):
148
+ preds = model.predict(data)
149
+ self.pred_table.add_data(
150
+ self.data_table_ref.data[idx][0],
151
+ self.data_table_ref.data[idx][1],
152
+ preds,
153
+ )
154
+ ```
155
+ This method is called `on_epoch_end` or equivalent hook.
156
+ """
157
+ raise NotImplementedError(f"{self.__class__.__name__}.add_model_predictions")
158
+
159
+ def init_data_table(self, column_names: list[str]) -> None:
160
+ """Initialize the W&B Tables for validation data.
161
+
162
+ Call this method `on_train_begin` or equivalent hook. This is followed by adding
163
+ data to the table row or column wise.
164
+
165
+ Args:
166
+ column_names: (list) Column names for W&B Tables.
167
+ """
168
+ self.data_table = wandb.Table(columns=column_names, allow_mixed_types=True)
169
+
170
+ def init_pred_table(self, column_names: list[str]) -> None:
171
+ """Initialize the W&B Tables for model evaluation.
172
+
173
+ Call this method `on_epoch_end` or equivalent hook. This is followed by adding
174
+ data to the table row or column wise.
175
+
176
+ Args:
177
+ column_names: (list) Column names for W&B Tables.
178
+ """
179
+ self.pred_table = wandb.Table(columns=column_names)
180
+
181
+ def log_data_table(
182
+ self, name: str = "val", type: str = "dataset", table_name: str = "val_data"
183
+ ) -> None:
184
+ """Log the `data_table` as W&B artifact and call `use_artifact` on it.
185
+
186
+ This lets the evaluation table use the reference of already uploaded data
187
+ (images, text, scalar, etc.) without re-uploading.
188
+
189
+ Args:
190
+ name: (str) A human-readable name for this artifact, which is how you can
191
+ identify this artifact in the UI or reference it in use_artifact calls.
192
+ (default is 'val')
193
+ type: (str) The type of the artifact, which is used to organize and
194
+ differentiate artifacts. (default is 'dataset')
195
+ table_name: (str) The name of the table as will be displayed in the UI.
196
+ (default is 'val_data').
197
+ """
198
+ data_artifact = wandb.Artifact(name, type=type)
199
+ data_artifact.add(self.data_table, table_name)
200
+
201
+ # Calling `use_artifact` uploads the data to W&B.
202
+ assert wandb.run is not None
203
+ wandb.run.use_artifact(data_artifact)
204
+ data_artifact.wait()
205
+
206
+ # We get the reference table.
207
+ self.data_table_ref = data_artifact.get(table_name)
208
+
209
+ def log_pred_table(
210
+ self,
211
+ type: str = "evaluation",
212
+ table_name: str = "eval_data",
213
+ aliases: list[str] | None = None,
214
+ ) -> None:
215
+ """Log the W&B Tables for model evaluation.
216
+
217
+ The table will be logged multiple times creating new version. Use this
218
+ to compare models at different intervals interactively.
219
+
220
+ Args:
221
+ type: (str) The type of the artifact, which is used to organize and
222
+ differentiate artifacts. (default is 'evaluation')
223
+ table_name: (str) The name of the table as will be displayed in the UI.
224
+ (default is 'eval_data')
225
+ aliases: (List[str]) List of aliases for the prediction table.
226
+ """
227
+ assert wandb.run is not None
228
+ pred_artifact = wandb.Artifact(f"run_{wandb.run.id}_pred", type=type)
229
+ pred_artifact.add(self.pred_table, table_name)
230
+ wandb.run.log_artifact(pred_artifact, aliases=aliases or ["latest"])
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/keras/keras.py ADDED
@@ -0,0 +1,1084 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """keras init."""
2
+
3
+ import logging
4
+ import operator
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from itertools import chain
9
+
10
+ import numpy as np
11
+ import tensorflow as tf
12
+ import tensorflow.keras.backend as K # noqa: N812
13
+
14
+ import wandb
15
+ from wandb.proto.wandb_telemetry_pb2 import Deprecated
16
+ from wandb.sdk.integration_utils.data_logging import ValidationDataLogger
17
+ from wandb.sdk.lib import telemetry
18
+ from wandb.sdk.lib.deprecation import warn_and_record_deprecation
19
+ from wandb.util import add_import_hook
20
+
21
+
22
+ def _check_keras_version():
23
+ from keras import __version__ as keras_version
24
+ from packaging.version import parse
25
+
26
+ if parse(keras_version) < parse("2.4.0"):
27
+ wandb.termwarn(
28
+ f"Keras version {keras_version} is not fully supported. Required keras >= 2.4.0"
29
+ )
30
+
31
+
32
+ def _can_compute_flops() -> bool:
33
+ """FLOPS computation is restricted to TF 2.x as it requires tf.compat.v1."""
34
+ from packaging.version import parse
35
+
36
+ return parse(tf.__version__) >= parse("2.0.0")
37
+
38
+
39
+ if "keras" in sys.modules:
40
+ _check_keras_version()
41
+ else:
42
+ add_import_hook("keras", _check_keras_version)
43
+
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ def is_dataset(data):
49
+ dataset_ops = wandb.util.get_module("tensorflow.python.data.ops.dataset_ops")
50
+ if dataset_ops and hasattr(dataset_ops, "DatasetV2"):
51
+ dataset_types = (dataset_ops.DatasetV2,)
52
+ if hasattr(dataset_ops, "DatasetV1"):
53
+ dataset_types = dataset_types + (dataset_ops.DatasetV1,)
54
+ return isinstance(data, dataset_types)
55
+ else:
56
+ return False
57
+
58
+
59
+ def is_generator_like(data):
60
+ # Checks if data is a generator, Sequence, or Iterator.
61
+
62
+ types = (tf.keras.utils.Sequence,)
63
+ iterator_ops = wandb.util.get_module("tensorflow.python.data.ops.iterator_ops")
64
+ if iterator_ops:
65
+ types = types + (iterator_ops.Iterator,)
66
+ # EagerIterator was in tensorflow < 2
67
+ if hasattr(iterator_ops, "EagerIterator"):
68
+ types = types + (iterator_ops.EagerIterator,)
69
+ elif hasattr(iterator_ops, "IteratorV2"):
70
+ types = types + (iterator_ops.IteratorV2,)
71
+ return hasattr(data, "next") or hasattr(data, "__next__") or isinstance(data, types)
72
+
73
+
74
+ def patch_tf_keras(): # noqa: C901
75
+ from packaging.version import parse
76
+ from tensorflow.python.eager import context
77
+
78
+ if parse("2.6.0") <= parse(tf.__version__) < parse("2.13.0"):
79
+ keras_engine = "keras.engine"
80
+ try:
81
+ from keras.engine import training
82
+ from keras.engine import training_arrays_v1 as training_arrays
83
+ from keras.engine import training_generator_v1 as training_generator
84
+ except (ImportError, AttributeError):
85
+ wandb.termerror("Unable to patch Tensorflow/Keras")
86
+ logger.exception("exception while trying to patch_tf_keras")
87
+ return
88
+ else:
89
+ keras_engine = "tensorflow.python.keras.engine"
90
+
91
+ from tensorflow.python.keras.engine import training
92
+
93
+ try:
94
+ from tensorflow.python.keras.engine import (
95
+ training_arrays_v1 as training_arrays,
96
+ )
97
+ from tensorflow.python.keras.engine import (
98
+ training_generator_v1 as training_generator,
99
+ )
100
+ except (ImportError, AttributeError):
101
+ try:
102
+ from tensorflow.python.keras.engine import (
103
+ training_arrays,
104
+ training_generator,
105
+ )
106
+ except (ImportError, AttributeError):
107
+ wandb.termerror("Unable to patch Tensorflow/Keras")
108
+ logger.exception("exception while trying to patch_tf_keras")
109
+ return
110
+
111
+ # Tensorflow 2.1
112
+ training_v2_1 = wandb.util.get_module("tensorflow.python.keras.engine.training_v2")
113
+ # Tensorflow 2.2
114
+ training_v2_2 = wandb.util.get_module(f"{keras_engine}.training_v1")
115
+
116
+ if training_v2_1:
117
+ old_v2 = training_v2_1.Loop.fit
118
+ elif training_v2_2:
119
+ old_v2 = training.Model.fit
120
+
121
+ old_arrays = training_arrays.fit_loop
122
+ old_generator = training_generator.fit_generator
123
+
124
+ def set_wandb_attrs(cbk, val_data):
125
+ if isinstance(cbk, WandbCallback):
126
+ if is_generator_like(val_data):
127
+ cbk.generator = val_data
128
+ elif is_dataset(val_data):
129
+ if context.executing_eagerly():
130
+ cbk.generator = iter(val_data)
131
+ else:
132
+ wandb.termwarn(
133
+ "Found a validation dataset in graph mode, can't patch Keras."
134
+ )
135
+ elif isinstance(val_data, tuple) and isinstance(val_data[0], tf.Tensor):
136
+ # Graph mode dataset generator
137
+ def gen():
138
+ while True:
139
+ yield K.get_session().run(val_data)
140
+
141
+ cbk.generator = gen()
142
+ else:
143
+ cbk.validation_data = val_data
144
+
145
+ def new_arrays(*args, **kwargs):
146
+ cbks = kwargs.get("callbacks", [])
147
+ val_inputs = kwargs.get("val_inputs")
148
+ val_targets = kwargs.get("val_targets")
149
+ # TODO: these could be generators, why index 0?
150
+ if val_inputs and val_targets:
151
+ for cbk in cbks:
152
+ set_wandb_attrs(cbk, (val_inputs[0], val_targets[0]))
153
+ return old_arrays(*args, **kwargs)
154
+
155
+ def new_generator(*args, **kwargs):
156
+ cbks = kwargs.get("callbacks", [])
157
+ val_data = kwargs.get("validation_data")
158
+ if val_data:
159
+ for cbk in cbks:
160
+ set_wandb_attrs(cbk, val_data)
161
+ return old_generator(*args, **kwargs)
162
+
163
+ def new_v2(*args, **kwargs):
164
+ cbks = kwargs.get("callbacks", [])
165
+ val_data = kwargs.get("validation_data")
166
+ if val_data:
167
+ for cbk in cbks:
168
+ set_wandb_attrs(cbk, val_data)
169
+ return old_v2(*args, **kwargs)
170
+
171
+ training_arrays.orig_fit_loop = old_arrays
172
+ training_arrays.fit_loop = new_arrays
173
+ training_generator.orig_fit_generator = old_generator
174
+ training_generator.fit_generator = new_generator
175
+ wandb.patched["keras"].append([f"{keras_engine}.training_arrays", "fit_loop"])
176
+ wandb.patched["keras"].append(
177
+ [f"{keras_engine}.training_generator", "fit_generator"]
178
+ )
179
+
180
+ if training_v2_1:
181
+ training_v2_1.Loop.fit = new_v2
182
+ wandb.patched["keras"].append(
183
+ ["tensorflow.python.keras.engine.training_v2.Loop", "fit"]
184
+ )
185
+ elif training_v2_2:
186
+ training.Model.fit = new_v2
187
+ wandb.patched["keras"].append([f"{keras_engine}.training.Model", "fit"])
188
+
189
+
190
+ def _array_has_dtype(array):
191
+ return hasattr(array, "dtype")
192
+
193
+
194
+ def _update_if_numeric(metrics, key, values):
195
+ if not _array_has_dtype(values):
196
+ _warn_not_logging(key)
197
+ return
198
+
199
+ if not is_numeric_array(values):
200
+ _warn_not_logging_non_numeric(key)
201
+ return
202
+
203
+ metrics[key] = wandb.Histogram(values)
204
+
205
+
206
+ def is_numeric_array(array):
207
+ return np.issubdtype(array.dtype, np.number)
208
+
209
+
210
+ def _warn_not_logging_non_numeric(name):
211
+ wandb.termwarn(
212
+ f"Non-numeric values found in layer: {name}, not logging this layer",
213
+ repeat=False,
214
+ )
215
+
216
+
217
+ def _warn_not_logging(name):
218
+ wandb.termwarn(
219
+ f"Layer {name} has undetermined datatype not logging this layer",
220
+ repeat=False,
221
+ )
222
+
223
+
224
+ tf_logger = tf.get_logger()
225
+
226
+ patch_tf_keras()
227
+
228
+
229
+ ### For gradient logging ###
230
+
231
+
232
+ def _get_custom_optimizer_parent_class():
233
+ from packaging.version import parse
234
+
235
+ if parse(tf.__version__) >= parse("2.9.0"):
236
+ custom_optimizer_parent_class = tf.keras.optimizers.legacy.Optimizer
237
+ else:
238
+ custom_optimizer_parent_class = tf.keras.optimizers.Optimizer
239
+
240
+ return custom_optimizer_parent_class
241
+
242
+
243
+ _custom_optimizer_parent_class = _get_custom_optimizer_parent_class()
244
+
245
+
246
+ class _CustomOptimizer(_custom_optimizer_parent_class):
247
+ def __init__(self):
248
+ super().__init__(name="CustomOptimizer")
249
+ self._resource_apply_dense = tf.function(self._resource_apply_dense)
250
+ self._resource_apply_sparse = tf.function(self._resource_apply_sparse)
251
+
252
+ def _resource_apply_dense(self, grad, var):
253
+ var.assign(grad)
254
+
255
+ # this needs to be implemented to prevent a NotImplementedError when
256
+ # using Lookup layers.
257
+ def _resource_apply_sparse(self, grad, var, indices):
258
+ pass
259
+
260
+ def get_config(self):
261
+ return super().get_config()
262
+
263
+
264
+ class _GradAccumulatorCallback(tf.keras.callbacks.Callback):
265
+ """Accumulates gradients during a fit() call when used in conjunction with the CustomOptimizer above."""
266
+
267
+ def set_model(self, model):
268
+ super().set_model(model)
269
+ self.og_weights = model.get_weights()
270
+ self.grads = [np.zeros(tuple(w.shape)) for w in model.trainable_weights]
271
+
272
+ def on_batch_end(self, batch, logs=None):
273
+ for g, w in zip(self.grads, self.model.trainable_weights):
274
+ g += w.numpy()
275
+ self.model.set_weights(self.og_weights)
276
+
277
+ def get_grads(self):
278
+ return [g.copy() for g in self.grads]
279
+
280
+
281
+ ###
282
+
283
+
284
+ class WandbCallback(tf.keras.callbacks.Callback):
285
+ """`WandbCallback` automatically integrates keras with wandb.
286
+
287
+ Example:
288
+ ```python
289
+ model.fit(
290
+ X_train,
291
+ y_train,
292
+ validation_data=(X_test, y_test),
293
+ callbacks=[WandbCallback()],
294
+ )
295
+ ```
296
+
297
+ `WandbCallback` will automatically log history data from any
298
+ metrics collected by keras: loss and anything passed into `keras_model.compile()`.
299
+
300
+ `WandbCallback` will set summary metrics for the run associated with the "best" training
301
+ step, where "best" is defined by the `monitor` and `mode` attributes. This defaults
302
+ to the epoch with the minimum `val_loss`. `WandbCallback` will by default save the model
303
+ associated with the best `epoch`.
304
+
305
+ `WandbCallback` can optionally log gradient and parameter histograms.
306
+
307
+ `WandbCallback` can optionally save training and validation data for wandb to visualize.
308
+
309
+ Args:
310
+ monitor: (str) name of metric to monitor. Defaults to `val_loss`.
311
+ mode: (str) one of {`auto`, `min`, `max`}.
312
+ `min` - save model when monitor is minimized
313
+ `max` - save model when monitor is maximized
314
+ `auto` - try to guess when to save the model (default).
315
+ save_model:
316
+ True - save a model when monitor beats all previous epochs
317
+ False - don't save models
318
+ save_graph: (boolean) if True save model graph to wandb (default to True).
319
+ save_weights_only: (boolean) if True, then only the model's weights will be
320
+ saved (`model.save_weights(filepath)`), else the full model
321
+ is saved (`model.save(filepath)`).
322
+ log_weights: (boolean) if True save histograms of the model's layer's weights.
323
+ log_gradients: (boolean) if True log histograms of the training gradients
324
+ training_data: (tuple) Same format `(X,y)` as passed to `model.fit`. This is needed
325
+ for calculating gradients - this is mandatory if `log_gradients` is `True`.
326
+ validation_data: (tuple) Same format `(X,y)` as passed to `model.fit`. A set of data
327
+ for wandb to visualize. If this is set, every epoch, wandb will
328
+ make a small number of predictions and save the results for later visualization. In case
329
+ you are working with image data, please also set `input_type` and `output_type` in order
330
+ to log correctly.
331
+ generator: (generator) a generator that returns validation data for wandb to visualize. This
332
+ generator should return tuples `(X,y)`. Either `validate_data` or generator should
333
+ be set for wandb to visualize specific data examples. In case you are working with image data,
334
+ please also set `input_type` and `output_type` in order to log correctly.
335
+ validation_steps: (int) if `validation_data` is a generator, how many
336
+ steps to run the generator for the full validation set.
337
+ labels: (list) If you are visualizing your data with wandb this list of labels
338
+ will convert numeric output to understandable string if you are building a
339
+ multiclass classifier. If you are making a binary classifier you can pass in
340
+ a list of two labels ["label for false", "label for true"]. If `validate_data`
341
+ and generator are both false, this won't do anything.
342
+ predictions: (int) the number of predictions to make for visualization each epoch, max
343
+ is 100.
344
+ input_type: (string) type of the model input to help visualization. can be one of:
345
+ (`image`, `images`, `segmentation_mask`, `auto`).
346
+ output_type: (string) type of the model output to help visualization. can be one of:
347
+ (`image`, `images`, `segmentation_mask`, `label`).
348
+ log_evaluation: (boolean) if True, save a Table containing validation data and the
349
+ model's predictions at each epoch. See `validation_indexes`,
350
+ `validation_row_processor`, and `output_row_processor` for additional details.
351
+ class_colors: ([float, float, float]) if the input or output is a segmentation mask,
352
+ an array containing an rgb tuple (range 0-1) for each class.
353
+ log_batch_frequency: (integer) if None, callback will log every epoch.
354
+ If set to integer, callback will log training metrics every `log_batch_frequency`
355
+ batches.
356
+ log_best_prefix: (string) if None, no extra summary metrics will be saved.
357
+ If set to a string, the monitored metric and epoch will be prepended with this value
358
+ and stored as summary metrics.
359
+ validation_indexes: ([wandb.data_types._TableLinkMixin]) an ordered list of index keys to associate
360
+ with each validation example. If log_evaluation is True and `validation_indexes` is provided,
361
+ then a Table of validation data will not be created and instead each prediction will
362
+ be associated with the row represented by the `TableLinkMixin`. The most common way to obtain
363
+ such keys are is use `Table.get_index()` which will return a list of row keys.
364
+ validation_row_processor: (Callable) a function to apply to the validation data, commonly used to visualize the data.
365
+ The function will receive an `ndx` (int) and a `row` (dict). If your model has a single input,
366
+ then `row["input"]` will be the input data for the row. Else, it will be keyed based on the name of the
367
+ input slot. If your fit function takes a single target, then `row["target"]` will be the target data for the row. Else,
368
+ it will be keyed based on the name of the output slots. For example, if your input data is a single ndarray,
369
+ but you wish to visualize the data as an Image, then you can provide `lambda ndx, row: {"img": wandb.Image(row["input"])}`
370
+ as the processor. Ignored if log_evaluation is False or `validation_indexes` are present.
371
+ output_row_processor: (Callable) same as `validation_row_processor`, but applied to the model's output. `row["output"]` will contain
372
+ the results of the model output.
373
+ infer_missing_processors: (bool) Determines if `validation_row_processor` and `output_row_processor`
374
+ should be inferred if missing. Defaults to True. If `labels` are provided, we will attempt to infer classification-type
375
+ processors where appropriate.
376
+ log_evaluation_frequency: (int) Determines the frequency which evaluation results will be logged. Default 0 (only at the end of training).
377
+ Set to 1 to log every epoch, 2 to log every other epoch, and so on. Has no effect when log_evaluation is False.
378
+ compute_flops: (bool) Compute the FLOPs of your Keras Sequential or Functional model in GigaFLOPs unit.
379
+ """
380
+
381
+ def __init__(
382
+ self,
383
+ monitor="val_loss",
384
+ verbose=0,
385
+ mode="auto",
386
+ save_weights_only=False,
387
+ log_weights=False,
388
+ log_gradients=False,
389
+ save_model=True,
390
+ training_data=None,
391
+ validation_data=None,
392
+ labels=None,
393
+ predictions=36,
394
+ generator=None,
395
+ input_type=None,
396
+ output_type=None,
397
+ log_evaluation=False,
398
+ validation_steps=None,
399
+ class_colors=None,
400
+ log_batch_frequency=None,
401
+ log_best_prefix="best_",
402
+ save_graph=True,
403
+ validation_indexes=None,
404
+ validation_row_processor=None,
405
+ prediction_row_processor=None,
406
+ infer_missing_processors=True,
407
+ log_evaluation_frequency=0,
408
+ compute_flops=False,
409
+ **kwargs,
410
+ ):
411
+ if wandb.run is None:
412
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
413
+
414
+ warn_and_record_deprecation(
415
+ feature=Deprecated(keras_callback=True),
416
+ message=(
417
+ "WandbCallback is deprecated and will be removed in a future release. "
418
+ "Please use the WandbMetricsLogger, WandbModelCheckpoint, and WandbEvalCallback "
419
+ "callbacks instead. "
420
+ "See https://docs.wandb.ai/guides/integrations/keras for more information."
421
+ ),
422
+ )
423
+
424
+ with telemetry.context(run=wandb.run) as tel:
425
+ tel.feature.keras = True
426
+ self.validation_data = None
427
+ # This is kept around for legacy reasons
428
+ if validation_data is not None:
429
+ if is_generator_like(validation_data):
430
+ generator = validation_data
431
+ else:
432
+ self.validation_data = validation_data
433
+ if labels is None:
434
+ labels = []
435
+ self.labels = labels
436
+ self.predictions = min(predictions, 100)
437
+
438
+ self.monitor = monitor
439
+ self.verbose = verbose
440
+ self.save_weights_only = save_weights_only
441
+ self.save_graph = save_graph
442
+
443
+ wandb.save("model-best.h5")
444
+ self.filepath = os.path.join(wandb.run.dir, "model-best.h5")
445
+ self.save_model = save_model
446
+ if save_model:
447
+ warn_and_record_deprecation(
448
+ feature=Deprecated(keras_callback__save_model=True),
449
+ message=(
450
+ "The save_model argument by default saves the model in the HDF5 format that cannot save "
451
+ "custom objects like subclassed models and custom layers. This behavior will be deprecated "
452
+ "in a future release in favor of the SavedModel format. Meanwhile, the HDF5 model is saved "
453
+ "as W&B files and the SavedModel as W&B Artifacts."
454
+ ),
455
+ )
456
+
457
+ self.save_model_as_artifact = True
458
+ self.log_weights = log_weights
459
+ self.log_gradients = log_gradients
460
+ self.training_data = training_data
461
+ self.generator = generator
462
+ self._graph_rendered = False
463
+
464
+ data_type = kwargs.get("data_type")
465
+ if data_type is not None:
466
+ warn_and_record_deprecation(
467
+ feature=Deprecated(keras_callback__data_type=True),
468
+ message=(
469
+ "The data_type argument of wandb.keras.WandbCallback is deprecated "
470
+ "and will be removed in a future release. Please use input_type instead.\n"
471
+ "Setting input_type = data_type."
472
+ ),
473
+ )
474
+ input_type = data_type
475
+ self.input_type = input_type
476
+ self.output_type = output_type
477
+ self.log_evaluation = log_evaluation
478
+ self.validation_steps = validation_steps
479
+ self.class_colors = np.array(class_colors) if class_colors is not None else None
480
+ self.log_batch_frequency = log_batch_frequency
481
+ self.log_best_prefix = log_best_prefix
482
+ self.compute_flops = compute_flops
483
+
484
+ self._prediction_batch_size = None
485
+
486
+ if self.log_gradients:
487
+ if int(tf.__version__.split(".")[0]) < 2:
488
+ raise Exception("Gradient logging requires tensorflow 2.0 or higher.")
489
+ if self.training_data is None:
490
+ raise ValueError(
491
+ "training_data argument is required for gradient logging."
492
+ )
493
+ if isinstance(self.training_data, (list, tuple)):
494
+ if len(self.training_data) != 2:
495
+ raise ValueError("training data must be a tuple of length two")
496
+ self._training_data_x, self._training_data_y = self.training_data
497
+ else:
498
+ self._training_data_x = (
499
+ self.training_data
500
+ ) # generator, tf.data.Dataset etc
501
+ self._training_data_y = None
502
+
503
+ # From Keras
504
+ if mode not in ["auto", "min", "max"]:
505
+ wandb.termwarn(
506
+ f"WandbCallback mode {mode} is unknown, fallback to auto mode."
507
+ )
508
+ mode = "auto"
509
+
510
+ if mode == "min":
511
+ self.monitor_op = operator.lt
512
+ self.best = float("inf")
513
+ elif mode == "max":
514
+ self.monitor_op = operator.gt
515
+ self.best = float("-inf")
516
+ else:
517
+ if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
518
+ self.monitor_op = operator.gt
519
+ self.best = float("-inf")
520
+ else:
521
+ self.monitor_op = operator.lt
522
+ self.best = float("inf")
523
+ # Get the previous best metric for resumed runs
524
+ previous_best = wandb.run.summary.get(f"{self.log_best_prefix}{self.monitor}")
525
+ if previous_best is not None:
526
+ self.best = previous_best
527
+
528
+ self._validation_data_logger = None
529
+ self._validation_indexes = validation_indexes
530
+ self._validation_row_processor = validation_row_processor
531
+ self._prediction_row_processor = prediction_row_processor
532
+ self._infer_missing_processors = infer_missing_processors
533
+ self._log_evaluation_frequency = log_evaluation_frequency
534
+ self._model_trained_since_last_eval = False
535
+
536
+ def _build_grad_accumulator_model(self):
537
+ inputs = self.model.inputs
538
+ outputs = self.model(inputs)
539
+ grad_acc_model = tf.keras.models.Model(inputs, outputs)
540
+ grad_acc_model.compile(loss=self.model.loss, optimizer=_CustomOptimizer())
541
+
542
+ # make sure magic doesn't think this is a user model
543
+ grad_acc_model._wandb_internal_model = True
544
+
545
+ self._grad_accumulator_model = grad_acc_model
546
+ self._grad_accumulator_callback = _GradAccumulatorCallback()
547
+
548
+ def _implements_train_batch_hooks(self):
549
+ return self.log_batch_frequency is not None
550
+
551
+ def _implements_test_batch_hooks(self):
552
+ return self.log_batch_frequency is not None
553
+
554
+ def _implements_predict_batch_hooks(self):
555
+ return self.log_batch_frequency is not None
556
+
557
+ def set_params(self, params):
558
+ self.params = params
559
+
560
+ def set_model(self, model):
561
+ super().set_model(model)
562
+ if self.input_type == "auto" and len(model.inputs) == 1:
563
+ self.input_type = wandb.util.guess_data_type(
564
+ model.inputs[0].shape, risky=True
565
+ )
566
+ if self.input_type and self.output_type is None and len(model.outputs) == 1:
567
+ self.output_type = wandb.util.guess_data_type(model.outputs[0].shape)
568
+ if self.log_gradients:
569
+ self._build_grad_accumulator_model()
570
+
571
+ def _attempt_evaluation_log(self, commit=True):
572
+ if self.log_evaluation and self._validation_data_logger:
573
+ try:
574
+ if not self.model:
575
+ wandb.termwarn("WandbCallback unable to read model from trainer")
576
+ else:
577
+ self._validation_data_logger.log_predictions(
578
+ predictions=self._validation_data_logger.make_predictions(
579
+ self.model.predict
580
+ ),
581
+ commit=commit,
582
+ )
583
+ self._model_trained_since_last_eval = False
584
+ except Exception as e:
585
+ wandb.termwarn("Error during prediction logging for epoch: " + str(e))
586
+
587
+ def on_epoch_end(self, epoch, logs=None):
588
+ if logs is None:
589
+ logs = {}
590
+ if self.log_weights:
591
+ wandb.log(self._log_weights(), commit=False)
592
+
593
+ if self.log_gradients:
594
+ wandb.log(self._log_gradients(), commit=False)
595
+
596
+ if self.input_type in (
597
+ "image",
598
+ "images",
599
+ "segmentation_mask",
600
+ ) or self.output_type in ("image", "images", "segmentation_mask"):
601
+ if self.generator:
602
+ self.validation_data = next(self.generator)
603
+ if self.validation_data is None:
604
+ wandb.termwarn(
605
+ "No validation_data set, pass a generator to the callback."
606
+ )
607
+ elif self.validation_data and len(self.validation_data) > 0:
608
+ wandb.log(
609
+ {"examples": self._log_images(num_images=self.predictions)},
610
+ commit=False,
611
+ )
612
+
613
+ if (
614
+ self._log_evaluation_frequency > 0
615
+ and epoch % self._log_evaluation_frequency == 0
616
+ ):
617
+ self._attempt_evaluation_log(commit=False)
618
+
619
+ wandb.log({"epoch": epoch}, commit=False)
620
+ wandb.log(logs, commit=True)
621
+
622
+ self.current = logs.get(self.monitor)
623
+ if self.current and self.monitor_op(self.current, self.best):
624
+ if self.log_best_prefix:
625
+ wandb.run.summary[f"{self.log_best_prefix}{self.monitor}"] = (
626
+ self.current
627
+ )
628
+ wandb.run.summary["{}{}".format(self.log_best_prefix, "epoch")] = epoch
629
+ if self.verbose and not self.save_model:
630
+ wandb.termlog(
631
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}"
632
+ )
633
+ if self.save_model:
634
+ self._save_model(epoch)
635
+
636
+ if self.save_model and self.save_model_as_artifact:
637
+ self._save_model_as_artifact(epoch)
638
+
639
+ self.best = self.current
640
+
641
+ # This is what keras used pre tensorflow.keras
642
+ def on_batch_begin(self, batch, logs=None):
643
+ pass
644
+
645
+ # This is what keras used pre tensorflow.keras
646
+ def on_batch_end(self, batch, logs=None):
647
+ if self.save_graph and not self._graph_rendered:
648
+ # Couldn't do this in train_begin because keras may still not be built
649
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
650
+ self._graph_rendered = True
651
+
652
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
653
+ wandb.log(logs, commit=True)
654
+
655
+ def on_train_batch_begin(self, batch, logs=None):
656
+ self._model_trained_since_last_eval = True
657
+
658
+ def on_train_batch_end(self, batch, logs=None):
659
+ if self.save_graph and not self._graph_rendered:
660
+ # Couldn't do this in train_begin because keras may still not be built
661
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
662
+ self._graph_rendered = True
663
+
664
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
665
+ wandb.log(logs, commit=True)
666
+
667
+ def on_test_begin(self, logs=None):
668
+ pass
669
+
670
+ def on_test_end(self, logs=None):
671
+ pass
672
+
673
+ def on_test_batch_begin(self, batch, logs=None):
674
+ pass
675
+
676
+ def on_test_batch_end(self, batch, logs=None):
677
+ pass
678
+
679
+ def on_train_begin(self, logs=None):
680
+ if self.log_evaluation:
681
+ try:
682
+ validation_data = None
683
+ if self.validation_data:
684
+ validation_data = self.validation_data
685
+ elif self.generator:
686
+ if not self.validation_steps:
687
+ wandb.termwarn(
688
+ "WandbCallback is unable to log validation data. "
689
+ "When using a generator for validation_data, you must pass validation_steps"
690
+ )
691
+ else:
692
+ x = None
693
+ y_true = None
694
+ for _ in range(self.validation_steps):
695
+ bx, by_true = next(self.generator)
696
+ if x is None:
697
+ x, y_true = bx, by_true
698
+ else:
699
+ x, y_true = (
700
+ np.append(x, bx, axis=0),
701
+ np.append(y_true, by_true, axis=0),
702
+ )
703
+ validation_data = (x, y_true)
704
+ else:
705
+ wandb.termwarn(
706
+ "WandbCallback is unable to read validation_data from trainer "
707
+ "and therefore cannot log validation data. Ensure Keras is properly "
708
+ "patched by calling `from wandb.keras import WandbCallback` at the top of your script."
709
+ )
710
+ if validation_data:
711
+ self._validation_data_logger = ValidationDataLogger(
712
+ inputs=validation_data[0],
713
+ targets=validation_data[1],
714
+ indexes=self._validation_indexes,
715
+ validation_row_processor=self._validation_row_processor,
716
+ prediction_row_processor=self._prediction_row_processor,
717
+ class_labels=self.labels,
718
+ infer_missing_processors=self._infer_missing_processors,
719
+ )
720
+ except Exception as e:
721
+ wandb.termwarn(
722
+ "Error initializing ValidationDataLogger in WandbCallback. "
723
+ f"Skipping logging validation data. Error: {str(e)}"
724
+ )
725
+
726
+ if self.compute_flops and _can_compute_flops():
727
+ try:
728
+ wandb.summary["GFLOPs"] = self.get_flops()
729
+ except Exception:
730
+ logger.exception("Error computing FLOPs")
731
+ wandb.termwarn("Unable to compute FLOPs for this model.")
732
+
733
+ def on_train_end(self, logs=None):
734
+ if self._model_trained_since_last_eval:
735
+ self._attempt_evaluation_log()
736
+
737
+ def on_predict_begin(self, logs=None):
738
+ pass
739
+
740
+ def on_predict_end(self, logs=None):
741
+ pass
742
+
743
+ def on_predict_batch_begin(self, batch, logs=None):
744
+ pass
745
+
746
+ def on_predict_batch_end(self, batch, logs=None):
747
+ pass
748
+
749
+ def _logits_to_captions(self, logits):
750
+ if logits[0].shape[-1] == 1:
751
+ # Scalar output from the model
752
+ # TODO: handle validation_y
753
+ if len(self.labels) == 2:
754
+ # User has named true and false
755
+ captions = [
756
+ self.labels[1] if logits[0] > 0.5 else self.labels[0]
757
+ for logit in logits
758
+ ]
759
+ else:
760
+ if len(self.labels) != 0:
761
+ wandb.termwarn(
762
+ "keras model is producing a single output, "
763
+ 'so labels should be a length two array: ["False label", "True label"].'
764
+ )
765
+ captions = [logit[0] for logit in logits]
766
+ else:
767
+ # Vector output from the model
768
+ # TODO: handle validation_y
769
+ labels = np.argmax(np.stack(logits), axis=1)
770
+
771
+ if len(self.labels) > 0:
772
+ # User has named the categories in self.labels
773
+ captions = []
774
+ for label in labels:
775
+ try:
776
+ captions.append(self.labels[label])
777
+ except IndexError:
778
+ captions.append(label)
779
+ else:
780
+ captions = labels
781
+ return captions
782
+
783
+ def _masks_to_pixels(self, masks):
784
+ # if its a binary mask, just return it as grayscale instead of picking the argmax
785
+ if len(masks[0].shape) == 2 or masks[0].shape[-1] == 1:
786
+ return masks
787
+ class_colors = (
788
+ self.class_colors
789
+ if self.class_colors is not None
790
+ else np.array(wandb.util.class_colors(masks[0].shape[2]))
791
+ )
792
+ imgs = class_colors[np.argmax(masks, axis=-1)]
793
+ return imgs
794
+
795
+ def _log_images(self, num_images=36):
796
+ validation_X = self.validation_data[0] # noqa: N806
797
+ validation_y = self.validation_data[1]
798
+
799
+ validation_length = len(validation_X)
800
+
801
+ if validation_length > num_images:
802
+ # pick some data at random
803
+ indices = np.random.choice(validation_length, num_images, replace=False)
804
+ else:
805
+ indices = range(validation_length)
806
+
807
+ test_data = []
808
+ test_output = []
809
+ for i in indices:
810
+ test_example = validation_X[i]
811
+ test_data.append(test_example)
812
+ test_output.append(validation_y[i])
813
+
814
+ if self.model.stateful:
815
+ predictions = self.model.predict(np.stack(test_data), batch_size=1)
816
+ self.model.reset_states()
817
+ else:
818
+ predictions = self.model.predict(
819
+ np.stack(test_data), batch_size=self._prediction_batch_size
820
+ )
821
+ if len(predictions) != len(test_data):
822
+ self._prediction_batch_size = 1
823
+ predictions = self.model.predict(
824
+ np.stack(test_data), batch_size=self._prediction_batch_size
825
+ )
826
+
827
+ if self.input_type == "label":
828
+ if self.output_type in ("image", "images", "segmentation_mask"):
829
+ captions = self._logits_to_captions(test_data)
830
+ output_image_data = (
831
+ self._masks_to_pixels(predictions)
832
+ if self.output_type == "segmentation_mask"
833
+ else predictions
834
+ )
835
+ reference_image_data = (
836
+ self._masks_to_pixels(test_output)
837
+ if self.output_type == "segmentation_mask"
838
+ else test_output
839
+ )
840
+ output_images = [
841
+ wandb.Image(data, caption=captions[i], grouping=2)
842
+ for i, data in enumerate(output_image_data)
843
+ ]
844
+ reference_images = [
845
+ wandb.Image(data, caption=captions[i])
846
+ for i, data in enumerate(reference_image_data)
847
+ ]
848
+ return list(chain.from_iterable(zip(output_images, reference_images)))
849
+ elif self.input_type in ("image", "images", "segmentation_mask"):
850
+ input_image_data = (
851
+ self._masks_to_pixels(test_data)
852
+ if self.input_type == "segmentation_mask"
853
+ else test_data
854
+ )
855
+ if self.output_type == "label":
856
+ # we just use the predicted label as the caption for now
857
+ captions = self._logits_to_captions(predictions)
858
+ return [
859
+ wandb.Image(data, caption=captions[i])
860
+ for i, data in enumerate(test_data)
861
+ ]
862
+ elif self.output_type in ("image", "images", "segmentation_mask"):
863
+ output_image_data = (
864
+ self._masks_to_pixels(predictions)
865
+ if self.output_type == "segmentation_mask"
866
+ else predictions
867
+ )
868
+ reference_image_data = (
869
+ self._masks_to_pixels(test_output)
870
+ if self.output_type == "segmentation_mask"
871
+ else test_output
872
+ )
873
+ input_images = [
874
+ wandb.Image(data, grouping=3)
875
+ for i, data in enumerate(input_image_data)
876
+ ]
877
+ output_images = [
878
+ wandb.Image(data) for i, data in enumerate(output_image_data)
879
+ ]
880
+ reference_images = [
881
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
882
+ ]
883
+ return list(
884
+ chain.from_iterable(
885
+ zip(input_images, output_images, reference_images)
886
+ )
887
+ )
888
+ else:
889
+ # unknown output, just log the input images
890
+ return [wandb.Image(img) for img in test_data]
891
+ elif self.output_type in ("image", "images", "segmentation_mask"):
892
+ # unknown input, just log the predicted and reference outputs without captions
893
+ output_image_data = (
894
+ self._masks_to_pixels(predictions)
895
+ if self.output_type == "segmentation_mask"
896
+ else predictions
897
+ )
898
+ reference_image_data = (
899
+ self._masks_to_pixels(test_output)
900
+ if self.output_type == "segmentation_mask"
901
+ else test_output
902
+ )
903
+ output_images = [
904
+ wandb.Image(data, grouping=2)
905
+ for i, data in enumerate(output_image_data)
906
+ ]
907
+ reference_images = [
908
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
909
+ ]
910
+ return list(chain.from_iterable(zip(output_images, reference_images)))
911
+
912
+ def _log_weights(self):
913
+ metrics = {}
914
+ for layer in self.model.layers:
915
+ weights = layer.get_weights()
916
+ if len(weights) == 1:
917
+ _update_if_numeric(
918
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
919
+ )
920
+ elif len(weights) == 2:
921
+ _update_if_numeric(
922
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
923
+ )
924
+ _update_if_numeric(
925
+ metrics, "parameters/" + layer.name + ".bias", weights[1]
926
+ )
927
+ return metrics
928
+
929
+ def _log_gradients(self):
930
+ # Suppress callback warnings grad accumulator
931
+ og_level = tf_logger.level
932
+ tf_logger.setLevel("ERROR")
933
+
934
+ self._grad_accumulator_model.fit(
935
+ self._training_data_x,
936
+ self._training_data_y,
937
+ verbose=0,
938
+ callbacks=[self._grad_accumulator_callback],
939
+ )
940
+ tf_logger.setLevel(og_level)
941
+ weights = self.model.trainable_weights
942
+ grads = self._grad_accumulator_callback.grads
943
+ metrics = {}
944
+ for weight, grad in zip(weights, grads):
945
+ metrics["gradients/" + weight.name.split(":")[0] + ".gradient"] = (
946
+ wandb.Histogram(grad)
947
+ )
948
+ return metrics
949
+
950
+ def _log_dataframe(self):
951
+ x, y_true, y_pred = None, None, None
952
+
953
+ if self.validation_data:
954
+ x, y_true = self.validation_data[0], self.validation_data[1]
955
+ y_pred = self.model.predict(x)
956
+ elif self.generator:
957
+ if not self.validation_steps:
958
+ wandb.termwarn(
959
+ "when using a generator for validation data with dataframes, "
960
+ "you must pass validation_steps. skipping"
961
+ )
962
+ return None
963
+
964
+ for _ in range(self.validation_steps):
965
+ bx, by_true = next(self.generator)
966
+ by_pred = self.model.predict(bx)
967
+ if x is None:
968
+ x, y_true, y_pred = bx, by_true, by_pred
969
+ else:
970
+ x, y_true, y_pred = (
971
+ np.append(x, bx, axis=0),
972
+ np.append(y_true, by_true, axis=0),
973
+ np.append(y_pred, by_pred, axis=0),
974
+ )
975
+
976
+ if self.input_type in ("image", "images") and self.output_type == "label":
977
+ return wandb.image_categorizer_dataframe(
978
+ x=x, y_true=y_true, y_pred=y_pred, labels=self.labels
979
+ )
980
+ elif (
981
+ self.input_type in ("image", "images")
982
+ and self.output_type == "segmentation_mask"
983
+ ):
984
+ return wandb.image_segmentation_dataframe(
985
+ x=x,
986
+ y_true=y_true,
987
+ y_pred=y_pred,
988
+ labels=self.labels,
989
+ class_colors=self.class_colors,
990
+ )
991
+ else:
992
+ wandb.termwarn(
993
+ f"unknown dataframe type for input_type={self.input_type} and output_type={self.output_type}"
994
+ )
995
+ return None
996
+
997
+ def _save_model(self, epoch):
998
+ if wandb.run.disabled:
999
+ return
1000
+ if self.verbose > 0:
1001
+ wandb.termlog(
1002
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}, "
1003
+ f"saving model to {self.filepath}"
1004
+ )
1005
+
1006
+ try:
1007
+ if self.save_weights_only:
1008
+ self.model.save_weights(self.filepath, overwrite=True)
1009
+ else:
1010
+ self.model.save(self.filepath, overwrite=True)
1011
+ # Was getting `RuntimeError: Unable to create link` in TF 1.13.1
1012
+ # also saw `TypeError: can't pickle _thread.RLock objects`
1013
+ except (ImportError, RuntimeError, TypeError, AttributeError):
1014
+ logger.exception("Error saving model in the h5py format")
1015
+ wandb.termerror(
1016
+ "Can't save model in the h5py format. The model will be saved as "
1017
+ "as an W&B Artifact in the 'tf' format."
1018
+ )
1019
+
1020
+ def _save_model_as_artifact(self, epoch):
1021
+ if wandb.run.disabled:
1022
+ return
1023
+
1024
+ # Save the model in the SavedModel format.
1025
+ # TODO: Replace this manual artifact creation with the `log_model` method
1026
+ # after `log_model` is released from beta.
1027
+ self.model.save(self.filepath[:-3], overwrite=True, save_format="tf")
1028
+
1029
+ # Log the model as artifact.
1030
+ name = wandb.util.make_artifact_name_safe(f"model-{wandb.run.name}")
1031
+ model_artifact = wandb.Artifact(name, type="model")
1032
+ model_artifact.add_dir(self.filepath[:-3])
1033
+ wandb.run.log_artifact(model_artifact, aliases=["latest", f"epoch_{epoch}"])
1034
+
1035
+ # Remove the SavedModel from wandb dir as we don't want to log it to save memory.
1036
+ shutil.rmtree(self.filepath[:-3])
1037
+
1038
+ def get_flops(self) -> float:
1039
+ """Calculate FLOPS [GFLOPs] for a tf.keras.Model or tf.keras.Sequential model in inference mode.
1040
+
1041
+ It uses tf.compat.v1.profiler under the hood.
1042
+ """
1043
+ if not hasattr(self, "model"):
1044
+ raise wandb.Error("self.model must be set before using this method.")
1045
+
1046
+ if not isinstance(
1047
+ self.model, (tf.keras.models.Sequential, tf.keras.models.Model)
1048
+ ):
1049
+ raise TypeError(
1050
+ "Calculating FLOPS is only supported for "
1051
+ "`tf.keras.Model` and `tf.keras.Sequential` instances."
1052
+ )
1053
+
1054
+ from tensorflow.python.framework.convert_to_constants import (
1055
+ convert_variables_to_constants_v2_as_graph,
1056
+ )
1057
+
1058
+ # Compute FLOPs for one sample
1059
+ batch_size = 1
1060
+ inputs = [
1061
+ tf.TensorSpec([batch_size] + inp.shape[1:], inp.dtype)
1062
+ for inp in self.model.inputs
1063
+ ]
1064
+
1065
+ # convert tf.keras model into frozen graph to count FLOPs about operations used at inference
1066
+ real_model = tf.function(self.model).get_concrete_function(inputs)
1067
+ frozen_func, _ = convert_variables_to_constants_v2_as_graph(real_model)
1068
+
1069
+ # Calculate FLOPs with tf.profiler
1070
+ run_meta = tf.compat.v1.RunMetadata()
1071
+ opts = (
1072
+ tf.compat.v1.profiler.ProfileOptionBuilder(
1073
+ tf.compat.v1.profiler.ProfileOptionBuilder().float_operation()
1074
+ )
1075
+ .with_empty_output()
1076
+ .build()
1077
+ )
1078
+
1079
+ flops = tf.compat.v1.profiler.profile(
1080
+ graph=frozen_func.graph, run_meta=run_meta, cmd="scope", options=opts
1081
+ )
1082
+
1083
+ # convert to GFLOPs
1084
+ return (flops.total_float_ops / 1e9) / 2
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ __all__ = ["wandb_log", "unpatch_kfp"]
2
+
3
+ from .kfp_patch import patch_kfp, unpatch_kfp
4
+ from .wandb_logging import wandb_log
5
+
6
+ patch_kfp()
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/helpers.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+
4
+ def add_wandb_visualization(run, mlpipeline_ui_metadata_path):
5
+ """NOTE: To use this, you must modify your component to have an output called `mlpipeline_ui_metadata_path` AND call `wandb.init` yourself inside that component.
6
+
7
+ Example usage:
8
+
9
+ def my_component(..., mlpipeline_ui_metadata_path: OutputPath()):
10
+ import wandb
11
+ from wandb.integration.kfp.helpers import add_wandb_visualization
12
+
13
+ with wandb.init() as run:
14
+ add_wandb_visualization(run, mlpipeline_ui_metadata_path)
15
+
16
+ ... # the rest of your code here
17
+ """
18
+
19
+ def get_iframe_html(run):
20
+ return f'<iframe src="{run.url}?kfp=true" style="border:none;width:100%;height:100%;min-width:900px;min-height:600px;"></iframe>'
21
+
22
+ iframe_html = get_iframe_html(run)
23
+ metadata = {
24
+ "outputs": [{"type": "markdown", "storage": "inline", "source": iframe_html}]
25
+ }
26
+
27
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
28
+ json.dump(metadata, metadata_file)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import itertools
5
+ import textwrap
6
+ from collections.abc import Mapping
7
+ from typing import Callable
8
+
9
+ import wandb
10
+
11
+ try:
12
+ from kfp import __version__ as kfp_version
13
+ from kfp.components import structures
14
+ from kfp.components._components import _create_task_factory_from_component_spec
15
+ from kfp.components._python_op import _func_to_component_spec
16
+ from packaging.version import parse
17
+
18
+ MIN_KFP_VERSION = "1.6.1"
19
+
20
+ if parse(kfp_version) < parse(MIN_KFP_VERSION):
21
+ wandb.termwarn(
22
+ f"Your version of kfp {kfp_version} may not work. This integration requires kfp>={MIN_KFP_VERSION}"
23
+ )
24
+
25
+ except ImportError:
26
+ wandb.termerror("kfp not found! Please `pip install kfp`")
27
+
28
+ from .wandb_logging import wandb_log
29
+
30
+ decorator_code = inspect.getsource(wandb_log)
31
+ wandb_logging_extras = f"""
32
+ import typing
33
+ from typing import NamedTuple
34
+
35
+ import collections
36
+ from collections import namedtuple
37
+
38
+ import kfp
39
+ from kfp import components
40
+ from kfp.components import InputPath, OutputPath
41
+
42
+ import wandb
43
+
44
+ {decorator_code}
45
+ """
46
+
47
+
48
+ def full_path_exists(full_func):
49
+ def get_parent_child_pairs(full_func):
50
+ components = full_func.split(".")
51
+ parents, children = [], []
52
+ for i, _ in enumerate(components[:-1], 1):
53
+ parent = ".".join(components[:i])
54
+ child = components[i]
55
+ parents.append(parent)
56
+ children.append(child)
57
+ return zip(parents, children)
58
+
59
+ for parent, child in get_parent_child_pairs(full_func):
60
+ module = wandb.util.get_module(parent)
61
+ if not module or not hasattr(module, child) or getattr(module, child) is None:
62
+ return False
63
+ return True
64
+
65
+
66
+ def patch(module_name, func):
67
+ module = wandb.util.get_module(module_name)
68
+ success = False
69
+
70
+ full_func = f"{module_name}.{func.__name__}"
71
+ if not full_path_exists(full_func):
72
+ wandb.termerror(
73
+ f"Failed to patch {module_name}.{func.__name__}! Please check if this package/module is installed!"
74
+ )
75
+ else:
76
+ wandb.patched.setdefault(module.__name__, [])
77
+ # if already patched, do not patch again
78
+ if [module, func.__name__] not in wandb.patched[module.__name__]:
79
+ setattr(module, f"orig_{func.__name__}", getattr(module, func.__name__))
80
+ setattr(module, func.__name__, func)
81
+ wandb.patched[module.__name__].append([module, func.__name__])
82
+ success = True
83
+
84
+ return success
85
+
86
+
87
+ def unpatch(module_name):
88
+ if module_name in wandb.patched:
89
+ for module, func in wandb.patched[module_name]:
90
+ setattr(module, func, getattr(module, f"orig_{func}"))
91
+ wandb.patched[module_name] = []
92
+
93
+
94
+ def unpatch_kfp():
95
+ unpatch("kfp.components")
96
+ unpatch("kfp.components._python_op")
97
+ unpatch("wandb.integration.kfp")
98
+
99
+
100
+ def patch_kfp():
101
+ to_patch = [
102
+ (
103
+ "kfp.components",
104
+ create_component_from_func,
105
+ ),
106
+ (
107
+ "kfp.components._python_op",
108
+ create_component_from_func,
109
+ ),
110
+ (
111
+ "kfp.components._python_op",
112
+ _get_function_source_definition,
113
+ ),
114
+ ("kfp.components._python_op", strip_type_hints),
115
+ ]
116
+
117
+ successes = []
118
+ for module_name, func in to_patch:
119
+ success = patch(module_name, func)
120
+ successes.append(success)
121
+ if not all(successes):
122
+ wandb.termerror(
123
+ "Failed to patch one or more kfp functions. Patching @wandb_log decorator to no-op."
124
+ )
125
+ patch("wandb.integration.kfp", wandb_log)
126
+
127
+
128
+ def wandb_log(
129
+ func=None,
130
+ # /, # py38 only
131
+ log_component_file=True,
132
+ ):
133
+ """Wrap a standard python function and log to W&B.
134
+
135
+ NOTE: Because patching failed, this decorator is a no-op.
136
+ """
137
+ from functools import wraps
138
+
139
+ def decorator(func):
140
+ @wraps(func)
141
+ def wrapper(*args, **kwargs):
142
+ return func(*args, **kwargs)
143
+
144
+ return wrapper
145
+
146
+ if func is None:
147
+ return decorator
148
+ else:
149
+ return decorator(func)
150
+
151
+
152
+ def _get_function_source_definition(func: Callable) -> str:
153
+ """Get the source code of a function.
154
+
155
+ This function is modified from KFP. The original source is below:
156
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L300-L319.
157
+ """
158
+ func_code = inspect.getsource(func)
159
+
160
+ # Function might be defined in some indented scope (e.g. in another
161
+ # function). We need to handle this and properly dedent the function source
162
+ # code
163
+ func_code = textwrap.dedent(func_code)
164
+ func_code_lines = func_code.split("\n")
165
+
166
+ # For wandb, allow decorators (so we can use the @wandb_log decorator)
167
+ func_code_lines = itertools.dropwhile(
168
+ lambda x: not (x.startswith(("def", "@wandb_log"))),
169
+ func_code_lines,
170
+ )
171
+
172
+ if not func_code_lines:
173
+ raise ValueError(
174
+ f'Failed to dedent and clean up the source of function "{func.__name__}". '
175
+ "It is probably not properly indented."
176
+ )
177
+
178
+ return "\n".join(func_code_lines)
179
+
180
+
181
+ def create_component_from_func(
182
+ func: Callable,
183
+ output_component_file: str | None = None,
184
+ base_image: str | None = None,
185
+ packages_to_install: list[str] | None = None,
186
+ annotations: Mapping[str, str] | None = None,
187
+ ):
188
+ '''Convert a Python function to a component and returns a task factory.
189
+
190
+ The returned task factory accepts arguments and returns a task object.
191
+
192
+ This function is modified from KFP. The original source is below:
193
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L998-L1110.
194
+
195
+ Args:
196
+ func: The python function to convert
197
+ base_image: Optional. Specify a custom Docker container image to use in the component. For lightweight components, the image needs to have python 3.5+. Default is the python image corresponding to the current python environment.
198
+ output_component_file: Optional. Write a component definition to a local file. The produced component file can be loaded back by calling :code:`load_component_from_file` or :code:`load_component_from_uri`.
199
+ packages_to_install: Optional. List of [versioned] python packages to pip install before executing the user function.
200
+ annotations: Optional. Allows adding arbitrary key-value data to the component specification.
201
+
202
+ Returns:
203
+ A factory function with a strongly-typed signature taken from the python function.
204
+ Once called with the required arguments, the factory constructs a task instance that can run the original function in a container.
205
+
206
+ Examples:
207
+ The function name and docstring are used as component name and description. Argument and return annotations are used as component input/output types::
208
+
209
+ def add(a: float, b: float) -> float:
210
+ """Return sum of two arguments"""
211
+ return a + b
212
+
213
+
214
+ # add_op is a task factory function that creates a task object when given arguments
215
+ add_op = create_component_from_func(
216
+ func=add,
217
+ base_image="python:3.7", # Optional
218
+ output_component_file="add.component.yaml", # Optional
219
+ packages_to_install=["pandas==0.24"], # Optional
220
+ )
221
+
222
+ # The component spec can be accessed through the .component_spec attribute:
223
+ add_op.component_spec.save("add.component.yaml")
224
+
225
+ # The component function can be called with arguments to create a task:
226
+ add_task = add_op(1, 3)
227
+
228
+ # The resulting task has output references, corresponding to the component outputs.
229
+ # When the function only has a single anonymous return value, the output name is "Output":
230
+ sum_output_ref = add_task.outputs["Output"]
231
+
232
+ # These task output references can be passed to other component functions, constructing a computation graph:
233
+ task2 = add_op(sum_output_ref, 5)
234
+
235
+
236
+ :code:`create_component_from_func` function can also be used as decorator::
237
+
238
+ @create_component_from_func
239
+ def add_op(a: float, b: float) -> float:
240
+ """Return sum of two arguments"""
241
+ return a + b
242
+
243
+ To declare a function with multiple return values, use the :code:`NamedTuple` return annotation syntax::
244
+
245
+ from typing import NamedTuple
246
+
247
+
248
+ def add_multiply_two_numbers(a: float, b: float) -> NamedTuple(
249
+ "Outputs", [("sum", float), ("product", float)]
250
+ ):
251
+ """Return sum and product of two arguments"""
252
+ return (a + b, a * b)
253
+
254
+
255
+ add_multiply_op = create_component_from_func(add_multiply_two_numbers)
256
+
257
+ # The component function can be called with arguments to create a task:
258
+ add_multiply_task = add_multiply_op(1, 3)
259
+
260
+ # The resulting task has output references, corresponding to the component outputs:
261
+ sum_output_ref = add_multiply_task.outputs["sum"]
262
+
263
+ # These task output references can be passed to other component functions, constructing a computation graph:
264
+ task2 = add_multiply_op(sum_output_ref, 5)
265
+
266
+ Bigger data should be read from files and written to files.
267
+ Use the :py:class:`kfp.components.InputPath` parameter annotation to tell the system that the function wants to consume the corresponding input data as a file. The system will download the data, write it to a local file and then pass the **path** of that file to the function.
268
+ Use the :py:class:`kfp.components.OutputPath` parameter annotation to tell the system that the function wants to produce the corresponding output data as a file. The system will prepare and pass the **path** of a file where the function should write the output data. After the function exits, the system will upload the data to the storage system so that it can be passed to downstream components.
269
+
270
+ You can specify the type of the consumed/produced data by specifying the type argument to :py:class:`kfp.components.InputPath` and :py:class:`kfp.components.OutputPath`. The type can be a python type or an arbitrary type name string. :code:`OutputPath('CatBoostModel')` means that the function states that the data it has written to a file has type :code:`CatBoostModel`. :code:`InputPath('CatBoostModel')` means that the function states that it expect the data it reads from a file to have type 'CatBoostModel'. When the pipeline author connects inputs to outputs the system checks whether the types match.
271
+ Every kind of data can be consumed as a file input. Conversely, bigger data should not be consumed by value as all value inputs pass through the command line.
272
+
273
+ Example of a component function declaring file input and output::
274
+
275
+ def catboost_train_classifier(
276
+ training_data_path: InputPath(
277
+ "CSV"
278
+ ), # Path to input data file of type "CSV"
279
+ trained_model_path: OutputPath(
280
+ "CatBoostModel"
281
+ ), # Path to output data file of type "CatBoostModel"
282
+ number_of_trees: int = 100, # Small output of type "Integer"
283
+ ) -> NamedTuple(
284
+ "Outputs",
285
+ [
286
+ ("Accuracy", float), # Small output of type "Float"
287
+ ("Precision", float), # Small output of type "Float"
288
+ ("JobUri", "URI"), # Small output of type "URI"
289
+ ],
290
+ ):
291
+ """Train CatBoost classification model"""
292
+ ...
293
+
294
+ return (accuracy, precision, recall)
295
+ '''
296
+ core_packages = ["wandb", "kfp"]
297
+
298
+ if not packages_to_install:
299
+ packages_to_install = core_packages
300
+ else:
301
+ packages_to_install += core_packages
302
+
303
+ component_spec = _func_to_component_spec(
304
+ func=func,
305
+ extra_code=wandb_logging_extras,
306
+ base_image=base_image,
307
+ packages_to_install=packages_to_install,
308
+ )
309
+ if annotations:
310
+ component_spec.metadata = structures.MetadataSpec(
311
+ annotations=annotations,
312
+ )
313
+
314
+ if output_component_file:
315
+ component_spec.save(output_component_file)
316
+
317
+ return _create_task_factory_from_component_spec(component_spec)
318
+
319
+
320
+ def strip_type_hints(source_code: str) -> str:
321
+ """Strip type hints from source code.
322
+
323
+ This function is modified from KFP. The original source is below:
324
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L237-L248.
325
+ """
326
+ # For wandb, do not strip type hints
327
+
328
+ # try:
329
+ # return _strip_type_hints_using_lib2to3(source_code)
330
+ # except Exception as ex:
331
+ # print('Error when stripping type annotations: ' + str(ex))
332
+
333
+ # try:
334
+ # return _strip_type_hints_using_strip_hints(source_code)
335
+ # except Exception as ex:
336
+ # print('Error when stripping type annotations: ' + str(ex))
337
+
338
+ return source_code
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def wandb_log( # noqa: C901
2
+ func=None,
3
+ # /, # py38 only
4
+ log_component_file=True,
5
+ ):
6
+ """Wrap a standard python function and log to W&B."""
7
+ import json
8
+ import os
9
+ from functools import wraps
10
+ from inspect import Parameter, signature
11
+
12
+ from kfp import components
13
+ from kfp.components import (
14
+ InputArtifact,
15
+ InputBinaryFile,
16
+ InputPath,
17
+ InputTextFile,
18
+ OutputArtifact,
19
+ OutputBinaryFile,
20
+ OutputPath,
21
+ OutputTextFile,
22
+ )
23
+
24
+ import wandb
25
+ from wandb.sdk.lib import telemetry as wb_telemetry
26
+
27
+ output_types = (OutputArtifact, OutputBinaryFile, OutputPath, OutputTextFile)
28
+ input_types = (InputArtifact, InputBinaryFile, InputPath, InputTextFile)
29
+
30
+ def isinstance_namedtuple(x):
31
+ t = type(x)
32
+ b = t.__bases__
33
+ if len(b) != 1 or b[0] is not tuple:
34
+ return False
35
+ f = getattr(t, "_fields", None)
36
+ if not isinstance(f, tuple):
37
+ return False
38
+ return all(isinstance(n, str) for n in f)
39
+
40
+ def get_iframe_html(run):
41
+ return f'<iframe src="{run.url}?kfp=true" style="border:none;width:100%;height:100%;min-width:900px;min-height:600px;"></iframe>'
42
+
43
+ def get_link_back_to_kubeflow():
44
+ wandb_kubeflow_url = os.getenv("WANDB_KUBEFLOW_URL")
45
+ return f"{wandb_kubeflow_url}/#/runs/details/{{workflow.uid}}"
46
+
47
+ def log_input_scalar(name, data, run=None):
48
+ run.config[name] = data
49
+ wandb.termlog(f"Setting config: {name} to {data}")
50
+
51
+ def log_input_artifact(name, data, type, run=None):
52
+ artifact = wandb.Artifact(name, type=type)
53
+ artifact.add_file(data)
54
+ run.use_artifact(artifact)
55
+ wandb.termlog(f"Using artifact: {name}")
56
+
57
+ def log_output_scalar(name, data, run=None):
58
+ if isinstance_namedtuple(data):
59
+ for k, v in zip(data._fields, data):
60
+ run.log({f"{func.__name__}.{k}": v})
61
+ else:
62
+ run.log({name: data})
63
+
64
+ def log_output_artifact(name, data, type, run=None):
65
+ artifact = wandb.Artifact(name, type=type)
66
+ artifact.add_file(data)
67
+ run.log_artifact(artifact)
68
+ wandb.termlog(f"Logging artifact: {name}")
69
+
70
+ def _log_component_file(func, run=None):
71
+ name = func.__name__
72
+ output_component_file = f"{name}.yml"
73
+ components._python_op.func_to_component_file(func, output_component_file)
74
+ artifact = wandb.Artifact(name, type="kubeflow_component_file")
75
+ artifact.add_file(output_component_file)
76
+ run.log_artifact(artifact)
77
+ wandb.termlog(f"Logging component file: {output_component_file}")
78
+
79
+ # Add `mlpipeline_ui_metadata_path` to signature to show W&B run in "ML Visualizations tab"
80
+ sig = signature(func)
81
+ no_default = []
82
+ has_default = []
83
+
84
+ for param in sig.parameters.values():
85
+ if param.default is param.empty:
86
+ no_default.append(param)
87
+ else:
88
+ has_default.append(param)
89
+
90
+ new_params = tuple(
91
+ (
92
+ *no_default,
93
+ Parameter(
94
+ "mlpipeline_ui_metadata_path",
95
+ annotation=OutputPath(),
96
+ kind=Parameter.POSITIONAL_OR_KEYWORD,
97
+ ),
98
+ *has_default,
99
+ )
100
+ )
101
+ new_sig = sig.replace(parameters=new_params)
102
+ new_anns = {param.name: param.annotation for param in new_params}
103
+ if "return" in func.__annotations__:
104
+ new_anns["return"] = func.__annotations__["return"]
105
+
106
+ def decorator(func):
107
+ input_scalars = {}
108
+ input_artifacts = {}
109
+ output_scalars = {}
110
+ output_artifacts = {}
111
+
112
+ for name, ann in func.__annotations__.items():
113
+ if name == "return":
114
+ output_scalars[name] = ann
115
+ elif isinstance(ann, output_types):
116
+ output_artifacts[name] = ann
117
+ elif isinstance(ann, input_types):
118
+ input_artifacts[name] = ann
119
+ else:
120
+ input_scalars[name] = ann
121
+
122
+ @wraps(func)
123
+ def wrapper(*args, **kwargs):
124
+ bound = new_sig.bind(*args, **kwargs)
125
+ bound.apply_defaults()
126
+
127
+ mlpipeline_ui_metadata_path = bound.arguments["mlpipeline_ui_metadata_path"]
128
+ del bound.arguments["mlpipeline_ui_metadata_path"]
129
+
130
+ with wandb.init(
131
+ job_type=func.__name__,
132
+ group="{{workflow.annotations.pipelines.kubeflow.org/run_name}}",
133
+ ) as run:
134
+ # Link back to the kfp UI
135
+ kubeflow_url = get_link_back_to_kubeflow()
136
+ run.notes = kubeflow_url
137
+ run.config["LINK_TO_KUBEFLOW_RUN"] = kubeflow_url
138
+
139
+ iframe_html = get_iframe_html(run)
140
+ metadata = {
141
+ "outputs": [
142
+ {
143
+ "type": "markdown",
144
+ "storage": "inline",
145
+ "source": iframe_html,
146
+ }
147
+ ]
148
+ }
149
+
150
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
151
+ json.dump(metadata, metadata_file)
152
+
153
+ if log_component_file:
154
+ _log_component_file(func, run=run)
155
+
156
+ for name, _ in input_scalars.items():
157
+ log_input_scalar(name, kwargs[name], run)
158
+
159
+ for name, ann in input_artifacts.items():
160
+ log_input_artifact(name, kwargs[name], ann.type, run)
161
+
162
+ with wb_telemetry.context(run=run) as tel:
163
+ tel.feature.kfp_wandb_log = True
164
+
165
+ result = func(*bound.args, **bound.kwargs)
166
+
167
+ for name, _ in output_scalars.items():
168
+ log_output_scalar(name, result, run)
169
+
170
+ for name, ann in output_artifacts.items():
171
+ log_output_artifact(name, kwargs[name], ann.type, run)
172
+
173
+ return result
174
+
175
+ wrapper.__signature__ = new_sig
176
+ wrapper.__annotations__ = new_anns
177
+ return wrapper
178
+
179
+ if func is None:
180
+ return decorator
181
+ else:
182
+ return decorator(func)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/langchain/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __all__ = ("WandbTracer",)
2
+
3
+ from .wandb_tracer import WandbTracer
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains an integration with the LangChain library.
2
+
3
+ Specifically, it exposes a `WandbTracer` class that can be used to stream
4
+ LangChain activity to W&B. The intended usage pattern is to call
5
+ `tracer = WandbTracer()` at the top of the script/notebook, and call
6
+ `tracer.finish()` at the end of the script/notebook.
7
+ This will stream all LangChain activity to W&B.
8
+
9
+ Technical Note:
10
+ LangChain is in very rapid development - meaning their APIs and schemas are actively changing.
11
+ As a matter of precaution, any call to LangChain apis, or use of their returned data is wrapped
12
+ in a try/except block. This is to ensure that if a breaking change is introduced, the W&B
13
+ integration will not break user code. The one exception to the rule is at import time. If
14
+ LangChain is not installed, or the symbols are not in the same place, the appropriate error
15
+ will be raised when importing this module.
16
+ """
17
+
18
+ from packaging import version
19
+
20
+ import wandb.util
21
+ from wandb.proto.wandb_telemetry_pb2 import Deprecated
22
+ from wandb.sdk.lib.deprecation import warn_and_record_deprecation
23
+
24
+ langchain = wandb.util.get_module(
25
+ name="langchain",
26
+ required="To use the LangChain WandbTracer you need to have the `langchain` python "
27
+ "package installed. Please install it with `pip install langchain`.",
28
+ )
29
+
30
+ if version.parse(langchain.__version__) < version.parse("0.0.188"):
31
+ raise ValueError(
32
+ "The Weights & Biases Langchain integration does not support versions 0.0.187 and lower. "
33
+ "To ensure proper functionality, please use version 0.0.188 or higher."
34
+ )
35
+
36
+ # isort: off
37
+ from langchain.callbacks.tracers import WandbTracer # noqa: E402
38
+
39
+
40
+ class WandbTracer(WandbTracer):
41
+ def __init__(self, *args, **kwargs):
42
+ super().__init__(*args, **kwargs)
43
+ warn_and_record_deprecation(
44
+ feature=Deprecated(langchain_tracer=True),
45
+ message="This feature is deprecated and has been moved to `langchain`. Enable tracing by setting "
46
+ "LANGCHAIN_WANDB_TRACING=true in your environment. See the documentation at "
47
+ "https://python.langchain.com/docs/ecosystem/integrations/agent_with_wandb_tracing for guidance. "
48
+ "Replace your current import with `from langchain.callbacks.tracers import WandbTracer`.",
49
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightgbm/__init__.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """W&B callback for lightgbm.
2
+
3
+ Really simple callback to get logging for each tree
4
+
5
+ Example usage:
6
+
7
+ param_list = [("eta", 0.08), ("max_depth", 6), ("subsample", 0.8), ("colsample_bytree", 0.8), ("alpha", 8), ("num_class", 10)]
8
+ config.update(dict(param_list))
9
+ lgb = lgb.train(param_list, d_train, callbacks=[wandb_callback()])
10
+ """
11
+
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Callable
14
+
15
+ import lightgbm # type: ignore
16
+ from lightgbm import Booster
17
+
18
+ import wandb
19
+ from wandb.sdk.lib import telemetry as wb_telemetry
20
+
21
+ MINIMIZE_METRICS = [
22
+ "l1",
23
+ "l2",
24
+ "rmse",
25
+ "mape",
26
+ "huber",
27
+ "fair",
28
+ "poisson",
29
+ "gamma",
30
+ "binary_logloss",
31
+ ]
32
+
33
+ MAXIMIZE_METRICS = ["map", "auc", "average_precision"]
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ from typing import Any, NamedTuple, Union
38
+
39
+ # Note: upstream lightgbm has this defined incorrectly
40
+ _EvalResultTuple = Union[
41
+ tuple[str, str, float, bool], tuple[str, str, float, bool, float]
42
+ ]
43
+
44
+ class CallbackEnv(NamedTuple):
45
+ model: Any
46
+ params: dict
47
+ iteration: int
48
+ begin_interation: int
49
+ end_iteration: int
50
+ evaluation_result_list: list[_EvalResultTuple]
51
+
52
+
53
+ def _define_metric(data: str, metric_name: str) -> None:
54
+ """Capture model performance at the best step.
55
+
56
+ instead of the last step, of training in your `wandb.summary`
57
+ """
58
+ if "loss" in str.lower(metric_name):
59
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
60
+ elif str.lower(metric_name) in MINIMIZE_METRICS:
61
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
62
+ elif str.lower(metric_name) in MAXIMIZE_METRICS:
63
+ wandb.define_metric(f"{data}_{metric_name}", summary="max")
64
+
65
+
66
+ def _checkpoint_artifact(
67
+ model: "Booster", iteration: int, aliases: "list[str]"
68
+ ) -> None:
69
+ """Upload model checkpoint as W&B artifact."""
70
+ # NOTE: type ignore required because wandb.run is improperly inferred as None type
71
+ model_name = f"model_{wandb.run.id}" # type: ignore
72
+ model_path = Path(wandb.run.dir) / f"model_ckpt_{iteration}.txt" # type: ignore
73
+
74
+ model.save_model(model_path, num_iteration=iteration)
75
+
76
+ model_artifact = wandb.Artifact(name=model_name, type="model")
77
+ model_artifact.add_file(str(model_path))
78
+ wandb.log_artifact(model_artifact, aliases=aliases)
79
+
80
+
81
+ def _log_feature_importance(model: "Booster") -> None:
82
+ """Log feature importance."""
83
+ feat_imps = model.feature_importance()
84
+ feats = model.feature_name()
85
+ fi_data = [[feat, feat_imp] for feat, feat_imp in zip(feats, feat_imps)]
86
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
87
+ wandb.log(
88
+ {
89
+ "Feature Importance": wandb.plot.bar(
90
+ table, "Feature", "Importance", title="Feature Importance"
91
+ )
92
+ },
93
+ commit=False,
94
+ )
95
+
96
+
97
+ class _WandbCallback:
98
+ """Internal class to handle `wandb_callback` logic.
99
+
100
+ This callback is adapted form the LightGBM's `_RecordEvaluationCallback`.
101
+ """
102
+
103
+ def __init__(self, log_params: bool = True, define_metric: bool = True) -> None:
104
+ self.order = 20
105
+ self.before_iteration = False
106
+ self.log_params = log_params
107
+ self.define_metric_bool = define_metric
108
+
109
+ def _init(self, env: "CallbackEnv") -> None:
110
+ with wb_telemetry.context() as tel:
111
+ tel.feature.lightgbm_wandb_callback = True
112
+
113
+ # log the params as W&B config.
114
+ if self.log_params:
115
+ wandb.config.update(env.params)
116
+
117
+ # use `define_metric` to set the wandb summary to the best metric value.
118
+ for item in env.evaluation_result_list:
119
+ if self.define_metric_bool:
120
+ if len(item) == 4:
121
+ data_name, eval_name = item[:2]
122
+ _define_metric(data_name, eval_name)
123
+ else:
124
+ data_name, eval_name = item[1].split()
125
+ _define_metric(data_name, f"{eval_name}-mean")
126
+ _define_metric(data_name, f"{eval_name}-stdv")
127
+
128
+ def __call__(self, env: "CallbackEnv") -> None:
129
+ if env.iteration == env.begin_iteration: # type: ignore
130
+ self._init(env)
131
+
132
+ for item in env.evaluation_result_list:
133
+ if len(item) == 4:
134
+ data_name, eval_name, result = item[:3]
135
+ wandb.log(
136
+ {data_name + "_" + eval_name: result},
137
+ commit=False,
138
+ )
139
+ else:
140
+ data_name, eval_name = item[1].split()
141
+ res_mean = item[2]
142
+ res_stdv = item[4]
143
+ wandb.log(
144
+ {
145
+ data_name + "_" + eval_name + "-mean": res_mean,
146
+ data_name + "_" + eval_name + "-stdv": res_stdv,
147
+ },
148
+ commit=False,
149
+ )
150
+
151
+ # call `commit=True` to log the data as a single W&B step.
152
+ wandb.log({"iteration": env.iteration}, commit=True)
153
+
154
+
155
+ def wandb_callback(log_params: bool = True, define_metric: bool = True) -> Callable:
156
+ """Automatically integrates LightGBM with wandb.
157
+
158
+ Args:
159
+ log_params: (boolean) if True (default) logs params passed to lightgbm.train as W&B config
160
+ define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`
161
+
162
+ Passing `wandb_callback` to LightGBM will:
163
+ - log params passed to lightgbm.train as W&B config (default).
164
+ - log evaluation metrics collected by LightGBM, such as rmse, accuracy etc to Weights & Biases
165
+ - Capture the best metric in `wandb.summary` when `define_metric=True` (default).
166
+
167
+ Use `log_summary` as an extension of this callback.
168
+
169
+ Example:
170
+ ```python
171
+ params = {
172
+ "boosting_type": "gbdt",
173
+ "objective": "regression",
174
+ }
175
+ gbm = lgb.train(
176
+ params,
177
+ lgb_train,
178
+ num_boost_round=10,
179
+ valid_sets=lgb_eval,
180
+ valid_names=("validation"),
181
+ callbacks=[wandb_callback()],
182
+ )
183
+ ```
184
+ """
185
+ return _WandbCallback(log_params, define_metric)
186
+
187
+
188
+ def log_summary(
189
+ model: Booster, feature_importance: bool = True, save_model_checkpoint: bool = False
190
+ ) -> None:
191
+ """Log useful metrics about lightgbm model after training is done.
192
+
193
+ Args:
194
+ model: (Booster) is an instance of lightgbm.basic.Booster.
195
+ feature_importance: (boolean) if True (default), logs the feature importance plot.
196
+ save_model_checkpoint: (boolean) if True saves the best model and upload as W&B artifacts.
197
+
198
+ Using this along with `wandb_callback` will:
199
+
200
+ - log `best_iteration` and `best_score` as `wandb.summary`.
201
+ - log feature importance plot.
202
+ - save and upload your best trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
203
+
204
+ Example:
205
+ ```python
206
+ params = {
207
+ "boosting_type": "gbdt",
208
+ "objective": "regression",
209
+ }
210
+ gbm = lgb.train(
211
+ params,
212
+ lgb_train,
213
+ num_boost_round=10,
214
+ valid_sets=lgb_eval,
215
+ valid_names=("validation"),
216
+ callbacks=[wandb_callback()],
217
+ )
218
+
219
+ log_summary(gbm)
220
+ ```
221
+ """
222
+ if wandb.run is None:
223
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
224
+
225
+ if not isinstance(model, Booster):
226
+ raise wandb.Error("Model should be an instance of lightgbm.basic.Booster")
227
+
228
+ wandb.run.summary["best_iteration"] = model.best_iteration
229
+ wandb.run.summary["best_score"] = model.best_score
230
+
231
+ # Log feature importance
232
+ if feature_importance:
233
+ _log_feature_importance(model)
234
+
235
+ if save_model_checkpoint:
236
+ _checkpoint_artifact(model, model.best_iteration, aliases=["best"])
237
+
238
+ with wb_telemetry.context() as tel:
239
+ tel.feature.lightgbm_log_summary = True
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from wandb.integration.lightning.fabric.logger import WandbLogger
2
+
3
+ __all__ = ("WandbLogger",)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from argparse import Namespace
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any, Literal
8
+
9
+ from packaging import version
10
+ from typing_extensions import override
11
+
12
+ import wandb
13
+ from wandb import Artifact
14
+ from wandb.sdk.lib import telemetry
15
+
16
+ try:
17
+ import lightning
18
+ import torch.nn as nn
19
+ from lightning.fabric.loggers.logger import Logger, rank_zero_experiment
20
+ from lightning.fabric.utilities.exceptions import MisconfigurationException
21
+ from lightning.fabric.utilities.logger import (
22
+ _add_prefix,
23
+ _convert_params,
24
+ _sanitize_callable_params,
25
+ )
26
+ from lightning.fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn
27
+ from lightning.fabric.utilities.types import _PATH
28
+ from torch import Tensor
29
+ from torch.nn import Module
30
+
31
+ if version.parse(lightning.__version__) > version.parse("2.1.3"):
32
+ wandb.termwarn(
33
+ """This integration is tested and supported for lightning Fabric 2.1.3.
34
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `lightning-fabric`.""",
35
+ repeat=False,
36
+ )
37
+
38
+ if TYPE_CHECKING:
39
+ from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint
40
+
41
+ except ImportError as e:
42
+ wandb.Error(e)
43
+
44
+
45
+ class WandbLogger(Logger):
46
+ r"""Log using `Weights and Biases <https://docs.wandb.ai/integrations/lightning>`_.
47
+
48
+ **Installation and set-up**
49
+
50
+ Install with pip:
51
+
52
+ .. code-block:: bash
53
+
54
+ pip install wandb
55
+
56
+ Create a `WandbLogger` instance:
57
+
58
+ .. code-block:: python
59
+
60
+ from lightning.fabric.loggers import WandbLogger
61
+
62
+ wandb_logger = WandbLogger(project="MNIST")
63
+
64
+ Pass the logger instance to the `Trainer`:
65
+
66
+ .. code-block:: python
67
+
68
+ trainer = Trainer(logger=wandb_logger)
69
+
70
+ A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`.
71
+
72
+ **Log metrics**
73
+
74
+ Log from :class:`~lightning.pytorch.core.LightningModule`:
75
+
76
+ .. code-block:: python
77
+
78
+ class LitModule(LightningModule):
79
+ def training_step(self, batch, batch_idx):
80
+ self.log("train/loss", loss)
81
+
82
+ Use directly wandb module:
83
+
84
+ .. code-block:: python
85
+
86
+ wandb.log({"train/loss": loss})
87
+
88
+ **Log hyper-parameters**
89
+
90
+ Save :class:`~lightning.pytorch.core.LightningModule` parameters:
91
+
92
+ .. code-block:: python
93
+
94
+ class LitModule(LightningModule):
95
+ def __init__(self, *args, **kwarg):
96
+ self.save_hyperparameters()
97
+
98
+ Add other config parameters:
99
+
100
+ .. code-block:: python
101
+
102
+ # add one parameter
103
+ wandb_logger.experiment.config["key"] = value
104
+
105
+ # add multiple parameters
106
+ wandb_logger.experiment.config.update({key1: val1, key2: val2})
107
+
108
+ # use directly wandb module
109
+ wandb.config["key"] = value
110
+ wandb.config.update()
111
+
112
+ **Log gradients, parameters and model topology**
113
+
114
+ Call the `watch` method for automatically tracking gradients:
115
+
116
+ .. code-block:: python
117
+
118
+ # log gradients and model topology
119
+ wandb_logger.watch(model)
120
+
121
+ # log gradients, parameter histogram and model topology
122
+ wandb_logger.watch(model, log="all")
123
+
124
+ # change log frequency of gradients and parameters (100 steps by default)
125
+ wandb_logger.watch(model, log_freq=500)
126
+
127
+ # do not log graph (in case of errors)
128
+ wandb_logger.watch(model, log_graph=False)
129
+
130
+ The `watch` method adds hooks to the model which can be removed at the end of training:
131
+
132
+ .. code-block:: python
133
+
134
+ wandb_logger.experiment.unwatch(model)
135
+
136
+ **Log model checkpoints**
137
+
138
+ Log model checkpoints at the end of training:
139
+
140
+ .. code-block:: python
141
+
142
+ wandb_logger = WandbLogger(log_model=True)
143
+
144
+ Log model checkpoints as they get created during training:
145
+
146
+ .. code-block:: python
147
+
148
+ wandb_logger = WandbLogger(log_model="all")
149
+
150
+ Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`:
151
+
152
+ .. code-block:: python
153
+
154
+ # log model only if `val_accuracy` increases
155
+ wandb_logger = WandbLogger(log_model="all")
156
+ checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
157
+ trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])
158
+
159
+ `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint:
160
+
161
+ .. code-block:: python
162
+
163
+ # reference can be retrieved in artifacts panel
164
+ # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
165
+ checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"
166
+
167
+ # download checkpoint locally (if not already cached)
168
+ run = wandb.init(project="MNIST")
169
+ artifact = run.use_artifact(checkpoint_reference, type="model")
170
+ artifact_dir = artifact.download()
171
+
172
+ # load checkpoint
173
+ model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")
174
+
175
+ **Log media**
176
+
177
+ Log text with:
178
+
179
+ .. code-block:: python
180
+
181
+ # using columns and data
182
+ columns = ["input", "label", "prediction"]
183
+ data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
184
+ wandb_logger.log_text(key="samples", columns=columns, data=data)
185
+
186
+ # using a pandas DataFrame
187
+ wandb_logger.log_text(key="samples", dataframe=my_dataframe)
188
+
189
+ Log images with:
190
+
191
+ .. code-block:: python
192
+
193
+ # using tensors, numpy arrays or PIL images
194
+ wandb_logger.log_image(key="samples", images=[img1, img2])
195
+
196
+ # adding captions
197
+ wandb_logger.log_image(
198
+ key="samples", images=[img1, img2], caption=["tree", "person"]
199
+ )
200
+
201
+ # using file path
202
+ wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])
203
+
204
+ More arguments can be passed for logging segmentation masks and bounding boxes. Refer to
205
+ `Image Overlays documentation <https://docs.wandb.ai/guides/track/log/media#image-overlays>`_.
206
+
207
+ **Log Tables**
208
+
209
+ `W&B Tables <https://docs.wandb.ai/guides/tables/visualize-tables>`_ can be used to log,
210
+ query and analyze tabular data.
211
+
212
+ They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing,
213
+ understanding and sharing any form of data, from datasets to model predictions.
214
+
215
+ .. code-block:: python
216
+
217
+ columns = ["caption", "image", "sound"]
218
+ data = [
219
+ ["cheese", wandb.Image(img_1), wandb.Audio(snd_1)],
220
+ ["wine", wandb.Image(img_2), wandb.Audio(snd_2)],
221
+ ]
222
+ wandb_logger.log_table(key="samples", columns=columns, data=data)
223
+
224
+
225
+ **Downloading and Using Artifacts**
226
+
227
+ To download an artifact without starting a run, call the ``download_artifact``
228
+ function on the class:
229
+
230
+ .. code-block:: python
231
+
232
+ artifact_dir = wandb_logger.download_artifact(artifact="path/to/artifact")
233
+
234
+ To download an artifact and link it to an ongoing run call the ``download_artifact``
235
+ function on the logger instance:
236
+
237
+ .. code-block:: python
238
+
239
+ class MyModule(LightningModule):
240
+ def any_lightning_module_function_or_hook(self):
241
+ self.logger.download_artifact(artifact="path/to/artifact")
242
+
243
+ To link an artifact from a previous run you can use ``use_artifact`` function:
244
+
245
+ .. code-block:: python
246
+
247
+ wandb_logger.use_artifact(artifact="path/to/artifact")
248
+
249
+ See Also:
250
+ - `Demo in Google Colab <http://wandb.me/lightning>`__ with hyperparameter search and model logging
251
+ - `W&B Documentation <https://docs.wandb.ai/integrations/lightning>`__
252
+
253
+ Args:
254
+ name: Display name for the run.
255
+ save_dir: Path where data is saved.
256
+ version: Sets the version, mainly used to resume a previous run.
257
+ offline: Run offline (data can be streamed later to wandb servers).
258
+ dir: Same as save_dir.
259
+ id: Same as version.
260
+ anonymous: Enables or explicitly disables anonymous logging.
261
+ project: The name of the project to which this run will belong. If not set, the environment variable
262
+ `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``.
263
+ log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint`
264
+ as W&B artifacts. `latest` and `best` aliases are automatically set.
265
+
266
+ * if ``log_model == 'all'``, checkpoints are logged during training.
267
+ * if ``log_model == True``, checkpoints are logged at the end of training, except when
268
+ `~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1``
269
+ which also logs every checkpoint during training.
270
+ * if ``log_model == False`` (default), no checkpoint is logged.
271
+
272
+ prefix: A string to put at the beginning of metric keys.
273
+ experiment: WandB experiment object. Automatically set when creating a run.
274
+ checkpoint_name: Name of the model checkpoint artifact being logged.
275
+ log_checkpoint_on: When to log model checkpoints as W&B artifacts. Only used if ``log_model`` is ``True``.
276
+ Options: ``"success"``, ``"all"``. Default: ``"success"``.
277
+ \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc.
278
+
279
+ Raises:
280
+ ModuleNotFoundError:
281
+ If required WandB package is not installed on the device.
282
+ MisconfigurationException:
283
+ If both ``log_model`` and ``offline`` is set to ``True``.
284
+
285
+ """
286
+
287
+ LOGGER_JOIN_CHAR = "-"
288
+
289
+ def __init__(
290
+ self,
291
+ name: str | None = None,
292
+ save_dir: _PATH = ".",
293
+ version: str | None = None,
294
+ offline: bool = False,
295
+ dir: _PATH | None = None,
296
+ id: str | None = None,
297
+ anonymous: bool | None = None,
298
+ project: str | None = None,
299
+ log_model: Literal["all"] | bool = False,
300
+ experiment: wandb.Run | None = None,
301
+ prefix: str = "",
302
+ checkpoint_name: str | None = None,
303
+ log_checkpoint_on: Literal["success"] | Literal["all"] = "success",
304
+ **kwargs: Any,
305
+ ) -> None:
306
+ if offline and log_model:
307
+ raise MisconfigurationException(
308
+ f"Providing log_model={log_model} and offline={offline} is an invalid configuration"
309
+ " since model checkpoints cannot be uploaded in offline mode.\n"
310
+ "Hint: Set `offline=False` to log your model."
311
+ )
312
+
313
+ super().__init__()
314
+ self._offline = offline
315
+ self._log_model = log_model
316
+ self._prefix = prefix
317
+ self._experiment = experiment
318
+ self._logged_model_time: dict[str, float] = {}
319
+ self._checkpoint_callback: ModelCheckpoint | None = None
320
+
321
+ # paths are processed as strings
322
+ if save_dir is not None:
323
+ save_dir = os.fspath(save_dir)
324
+ elif dir is not None:
325
+ dir = os.fspath(dir)
326
+
327
+ project = project or os.environ.get("WANDB_PROJECT", "lightning_fabric_logs")
328
+
329
+ # set wandb init arguments
330
+ self._wandb_init: dict[str, Any] = {
331
+ "name": name,
332
+ "project": project,
333
+ "dir": save_dir or dir,
334
+ "id": version or id,
335
+ "resume": "allow",
336
+ "anonymous": ("allow" if anonymous else None),
337
+ }
338
+ self._wandb_init.update(**kwargs)
339
+ # extract parameters
340
+ self._project = self._wandb_init.get("project")
341
+ self._save_dir = self._wandb_init.get("dir")
342
+ self._name = self._wandb_init.get("name")
343
+ self._id = self._wandb_init.get("id")
344
+ self._checkpoint_name = checkpoint_name
345
+ self._log_checkpoint_on = log_checkpoint_on
346
+
347
+ def __getstate__(self) -> dict[str, Any]:
348
+ # Hack: If the 'spawn' launch method is used, the logger will get pickled and this `__getstate__` gets called.
349
+ # We create an experiment here in the main process, and attach to it in the worker process.
350
+ # Using wandb-service, we persist the same experiment even if multiple `Trainer.fit/test/validate` calls
351
+ # are made.
352
+ _ = self.experiment
353
+
354
+ state = self.__dict__.copy()
355
+ # args needed to reload correct experiment
356
+ if self._experiment is not None:
357
+ state["_id"] = getattr(self._experiment, "id", None)
358
+ state["_attach_id"] = getattr(self._experiment, "_attach_id", None)
359
+ state["_name"] = self._experiment.name
360
+
361
+ # cannot be pickled
362
+ state["_experiment"] = None
363
+ return state
364
+
365
+ @property
366
+ @rank_zero_experiment
367
+ def experiment(self) -> wandb.Run:
368
+ r"""Actual wandb object.
369
+
370
+ To use wandb features in your :class:`~lightning.pytorch.core.LightningModule`, do the
371
+ following.
372
+
373
+ Example::
374
+
375
+ .. code-block:: python
376
+
377
+ self.logger.experiment.some_wandb_function()
378
+
379
+ """
380
+ if self._experiment is None:
381
+ if self._offline:
382
+ os.environ["WANDB_MODE"] = "dryrun"
383
+
384
+ attach_id = getattr(self, "_attach_id", None)
385
+ if wandb.run is not None:
386
+ # wandb process already created in this instance
387
+ rank_zero_warn(
388
+ "There is a wandb run already in progress and newly created instances of `WandbLogger` will reuse"
389
+ " this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`."
390
+ )
391
+ self._experiment = wandb.run
392
+ elif attach_id is not None and hasattr(wandb, "_attach"):
393
+ # attach to wandb process referenced
394
+ self._experiment = wandb._attach(attach_id)
395
+ else:
396
+ # create new wandb process
397
+ self._experiment = wandb.init(**self._wandb_init)
398
+
399
+ # define default x-axis
400
+ if isinstance(self._experiment, wandb.Run) and getattr(
401
+ self._experiment, "define_metric", None
402
+ ):
403
+ self._experiment.define_metric("trainer/global_step")
404
+ self._experiment.define_metric(
405
+ "*", step_metric="trainer/global_step", step_sync=True
406
+ )
407
+
408
+ self._experiment._label(repo="lightning_fabric_logger") # pylint: disable=protected-access
409
+ with telemetry.context(run=self._experiment) as tel:
410
+ tel.feature.lightning_fabric_logger = True
411
+ return self._experiment
412
+
413
+ def watch(
414
+ self,
415
+ model: nn.Module,
416
+ log: str = "gradients",
417
+ log_freq: int = 100,
418
+ log_graph: bool = True,
419
+ ) -> None:
420
+ self.experiment.watch(model, log=log, log_freq=log_freq, log_graph=log_graph)
421
+
422
+ @override
423
+ @rank_zero_only
424
+ def log_hyperparams(self, params: dict[str, Any] | Namespace) -> None: # type: ignore[override]
425
+ params = _convert_params(params)
426
+ params = _sanitize_callable_params(params)
427
+ self.experiment.config.update(params, allow_val_change=True)
428
+
429
+ @override
430
+ @rank_zero_only
431
+ def log_metrics(
432
+ self, metrics: Mapping[str, float], step: int | None = None
433
+ ) -> None:
434
+ assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0"
435
+
436
+ metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR)
437
+ if step is not None:
438
+ self.experiment.log(dict(metrics, **{"trainer/global_step": step}))
439
+ else:
440
+ self.experiment.log(metrics)
441
+
442
+ @rank_zero_only
443
+ def log_table(
444
+ self,
445
+ key: str,
446
+ columns: list[str] | None = None,
447
+ data: list[list[Any]] | None = None,
448
+ dataframe: Any = None,
449
+ step: int | None = None,
450
+ ) -> None:
451
+ """Log a Table containing any object type (text, image, audio, video, molecule, html, etc).
452
+
453
+ Can be defined either with `columns` and `data` or with `dataframe`.
454
+
455
+ """
456
+ metrics = {key: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
457
+ self.log_metrics(metrics, step)
458
+
459
+ @rank_zero_only
460
+ def log_text(
461
+ self,
462
+ key: str,
463
+ columns: list[str] | None = None,
464
+ data: list[list[str]] | None = None,
465
+ dataframe: Any = None,
466
+ step: int | None = None,
467
+ ) -> None:
468
+ """Log text as a Table.
469
+
470
+ Can be defined either with `columns` and `data` or with `dataframe`.
471
+
472
+ """
473
+ self.log_table(key, columns, data, dataframe, step)
474
+
475
+ @rank_zero_only
476
+ def log_html(
477
+ self, key: str, htmls: list[Any], step: int | None = None, **kwargs: Any
478
+ ) -> None:
479
+ """Log html files.
480
+
481
+ Optional kwargs are lists passed to each html (ex: inject).
482
+
483
+ """
484
+ if not isinstance(htmls, list):
485
+ raise TypeError(f'Expected a list as "htmls", found {type(htmls)}')
486
+ n = len(htmls)
487
+ for k, v in kwargs.items():
488
+ if len(v) != n:
489
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
490
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
491
+
492
+ metrics = {
493
+ key: [wandb.Html(html, **kwarg) for html, kwarg in zip(htmls, kwarg_list)]
494
+ }
495
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
496
+
497
+ @rank_zero_only
498
+ def log_image(
499
+ self, key: str, images: list[Any], step: int | None = None, **kwargs: Any
500
+ ) -> None:
501
+ """Log images (tensors, numpy arrays, PIL Images or file paths).
502
+
503
+ Optional kwargs are lists passed to each image (ex: caption, masks, boxes).
504
+
505
+ """
506
+ if not isinstance(images, list):
507
+ raise TypeError(f'Expected a list as "images", found {type(images)}')
508
+ n = len(images)
509
+ for k, v in kwargs.items():
510
+ if len(v) != n:
511
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
512
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
513
+
514
+ metrics = {
515
+ key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)]
516
+ }
517
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
518
+
519
+ @rank_zero_only
520
+ def log_audio(
521
+ self, key: str, audios: list[Any], step: int | None = None, **kwargs: Any
522
+ ) -> None:
523
+ r"""Log audios (numpy arrays, or file paths).
524
+
525
+ Args:
526
+ key: The key to be used for logging the audio files
527
+ audios: The list of audio file paths, or numpy arrays to be logged
528
+ step: The step number to be used for logging the audio files
529
+ \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).
530
+
531
+ Optional kwargs are lists passed to each audio (ex: caption, sample_rate).
532
+
533
+ """
534
+ if not isinstance(audios, list):
535
+ raise TypeError(f'Expected a list as "audios", found {type(audios)}')
536
+ n = len(audios)
537
+ for k, v in kwargs.items():
538
+ if len(v) != n:
539
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
540
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
541
+
542
+ metrics = {
543
+ key: [
544
+ wandb.Audio(audio, **kwarg) for audio, kwarg in zip(audios, kwarg_list)
545
+ ]
546
+ }
547
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
548
+
549
+ @rank_zero_only
550
+ def log_video(
551
+ self, key: str, videos: list[Any], step: int | None = None, **kwargs: Any
552
+ ) -> None:
553
+ """Log videos (numpy arrays, or file paths).
554
+
555
+ Args:
556
+ key: The key to be used for logging the video files
557
+ videos: The list of video file paths, or numpy arrays to be logged
558
+ step: The step number to be used for logging the video files
559
+ **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).
560
+
561
+ Optional kwargs are lists passed to each video (ex: caption, fps, format).
562
+
563
+ """
564
+ if not isinstance(videos, list):
565
+ raise TypeError(f'Expected a list as "videos", found {type(videos)}')
566
+ n = len(videos)
567
+ for k, v in kwargs.items():
568
+ if len(v) != n:
569
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
570
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
571
+
572
+ metrics = {
573
+ key: [
574
+ wandb.Video(video, **kwarg) for video, kwarg in zip(videos, kwarg_list)
575
+ ]
576
+ }
577
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
578
+
579
+ @property
580
+ @override
581
+ def save_dir(self) -> str | None:
582
+ """Gets the save directory.
583
+
584
+ Returns:
585
+ The path to the save directory.
586
+
587
+ """
588
+ return self._save_dir
589
+
590
+ @property
591
+ @override
592
+ def name(self) -> str | None:
593
+ """The project name of this experiment.
594
+
595
+ Returns:
596
+ The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s
597
+ name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead.
598
+
599
+ """
600
+ return self._project
601
+
602
+ @property
603
+ @override
604
+ def version(self) -> str | None:
605
+ """Gets the id of the experiment.
606
+
607
+ Returns:
608
+ The id of the experiment if the experiment exists else the id given to the constructor.
609
+
610
+ """
611
+ # don't create an experiment if we don't have one
612
+ return self._experiment.id if self._experiment else self._id
613
+
614
+ @property
615
+ def log_dir(self) -> str | None:
616
+ """Gets the save directory.
617
+
618
+ Returns:
619
+ The path to the save directory.
620
+
621
+ """
622
+ return self.save_dir
623
+
624
+ @property
625
+ def group_separator(self) -> str:
626
+ """Return the default separator used by the logger to group the data into subfolders."""
627
+ return self.LOGGER_JOIN_CHAR
628
+
629
+ @property
630
+ def root_dir(self) -> str | None:
631
+ """Return the root directory.
632
+
633
+ Return the root directory where all versions of an experiment get saved, or `None` if the logger does not
634
+ save data locally.
635
+ """
636
+ return self.save_dir.parent if self.save_dir else None
637
+
638
+ def log_graph(self, model: Module, input_array: Tensor | None = None) -> None:
639
+ """Record model graph.
640
+
641
+ Args:
642
+ model: the model with an implementation of ``forward``.
643
+ input_array: input passes to `model.forward`
644
+
645
+ This is a noop function and does not perform any operation.
646
+ """
647
+ return
648
+
649
+ @override
650
+ def after_save_checkpoint(self, checkpoint_callback: ModelCheckpoint) -> None:
651
+ # log checkpoints as artifacts
652
+ if (
653
+ self._log_model == "all"
654
+ or self._log_model is True
655
+ and checkpoint_callback.save_top_k == -1
656
+ ):
657
+ # TODO: Replace with new Fabric Checkpoints system
658
+ self._scan_and_log_pytorch_checkpoints(checkpoint_callback)
659
+ elif self._log_model is True:
660
+ self._checkpoint_callback = checkpoint_callback
661
+
662
+ @staticmethod
663
+ @rank_zero_only
664
+ def download_artifact(
665
+ artifact: str,
666
+ save_dir: _PATH | None = None,
667
+ artifact_type: str | None = None,
668
+ use_artifact: bool | None = True,
669
+ ) -> str:
670
+ """Downloads an artifact from the wandb server.
671
+
672
+ Args:
673
+ artifact: The path of the artifact to download.
674
+ save_dir: The directory to save the artifact to.
675
+ artifact_type: The type of artifact to download.
676
+ use_artifact: Whether to add an edge between the artifact graph.
677
+
678
+ Returns:
679
+ The path to the downloaded artifact.
680
+
681
+ """
682
+ if wandb.run is not None and use_artifact:
683
+ artifact = wandb.run.use_artifact(artifact)
684
+ else:
685
+ api = wandb.Api()
686
+ artifact = api.artifact(artifact, type=artifact_type)
687
+
688
+ save_dir = None if save_dir is None else os.fspath(save_dir)
689
+ return artifact.download(root=save_dir)
690
+
691
+ def use_artifact(self, artifact: str, artifact_type: str | None = None) -> Artifact:
692
+ """Logs to the wandb dashboard that the mentioned artifact is used by the run.
693
+
694
+ Args:
695
+ artifact: The path of the artifact.
696
+ artifact_type: The type of artifact being used.
697
+
698
+ Returns:
699
+ wandb Artifact object for the artifact.
700
+
701
+ """
702
+ return self.experiment.use_artifact(artifact, type=artifact_type)
703
+
704
+ @override
705
+ @rank_zero_only
706
+ def save(self) -> None:
707
+ """Save log data."""
708
+ self.experiment.log({}, commit=True)
709
+
710
+ @override
711
+ @rank_zero_only
712
+ def finalize(self, status: str) -> None:
713
+ if self._log_checkpoint_on == "success" and status != "success":
714
+ # Currently, checkpoints only get logged on success
715
+ return
716
+ # log checkpoints as artifacts
717
+ if (
718
+ self._checkpoint_callback
719
+ and self._experiment is not None
720
+ and self._log_checkpoint_on in ["success", "all"]
721
+ ):
722
+ self._scan_and_log_pytorch_checkpoints(self._checkpoint_callback)
723
+
724
+ def _scan_and_log_pytorch_checkpoints(
725
+ self, checkpoint_callback: ModelCheckpoint
726
+ ) -> None:
727
+ from lightning.pytorch.loggers.utilities import _scan_checkpoints
728
+
729
+ # get checkpoints to be saved with associated score
730
+ checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time)
731
+
732
+ # log iteratively all new checkpoints
733
+ for t, p, s, _ in checkpoints:
734
+ metadata = {
735
+ "score": s.item() if isinstance(s, Tensor) else s,
736
+ "original_filename": Path(p).name,
737
+ checkpoint_callback.__class__.__name__: {
738
+ k: getattr(checkpoint_callback, k)
739
+ for k in [
740
+ "monitor",
741
+ "mode",
742
+ "save_last",
743
+ "save_top_k",
744
+ "save_weights_only",
745
+ "_every_n_train_steps",
746
+ ]
747
+ # ensure it does not break if `ModelCheckpoint` args change
748
+ if hasattr(checkpoint_callback, k)
749
+ },
750
+ }
751
+ if not self._checkpoint_name:
752
+ self._checkpoint_name = f"model-{self.experiment.id}"
753
+ artifact = wandb.Artifact(
754
+ name=self._checkpoint_name, type="model", metadata=metadata
755
+ )
756
+ artifact.add_file(p, name="model.ckpt")
757
+ aliases = (
758
+ ["latest", "best"]
759
+ if p == checkpoint_callback.best_model_path
760
+ else ["latest"]
761
+ )
762
+ self.experiment.log_model(artifact, aliases=aliases)
763
+ # remember logged models - timestamp needed in case filename didn't change (lastkckpt or custom name)
764
+ self._logged_model_time[p] = t
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """W&B Integration for Metaflow.
2
+
3
+ Defines a custom step and flow decorator `wandb_log` that automatically logs
4
+ flow parameters and artifacts to W&B.
5
+ """
6
+
7
+ from .metaflow import wandb_log, wandb_track, wandb_use
8
+
9
+ __all__ = ["wandb_log", "wandb_track", "wandb_use"]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for Pandas datatypes.
2
+
3
+ May raise MissingDependencyError on import.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing_extensions import Any, TypeIs
9
+
10
+ import wandb
11
+
12
+ from . import errors
13
+
14
+ try:
15
+ import pandas as pd
16
+ except ImportError as e:
17
+ warning = (
18
+ "`pandas` not installed >>"
19
+ " @wandb_log(datasets=True) may not auto log your dataset!"
20
+ )
21
+ raise errors.MissingDependencyError(warning=warning) from e
22
+
23
+
24
+ def is_dataframe(data: Any) -> TypeIs[pd.DataFrame]:
25
+ """Returns whether the data is a Pandas DataFrame."""
26
+ return isinstance(data, pd.DataFrame)
27
+
28
+
29
+ def use_dataframe(
30
+ name: str,
31
+ run: wandb.Run | None,
32
+ testing: bool = False,
33
+ ) -> str | None:
34
+ """Log a dependency on a DataFrame input.
35
+
36
+ Args:
37
+ name: Name of the input.
38
+ run: The run to update.
39
+ testing: True in unit tests.
40
+ """
41
+ if testing:
42
+ return "datasets"
43
+ assert run
44
+
45
+ wandb.termlog(f"Using artifact: {name} (Pandas DataFrame)")
46
+ run.use_artifact(f"{name}:latest")
47
+ return None
48
+
49
+
50
+ def track_dataframe(
51
+ name: str,
52
+ data: pd.DataFrame,
53
+ run: wandb.Run | None,
54
+ testing: bool = False,
55
+ ) -> str | None:
56
+ """Log a DataFrame output as an artifact.
57
+
58
+ Args:
59
+ name: The output's name.
60
+ data: The output's value.
61
+ run: The run to update.
62
+ testing: True in unit tests.
63
+ """
64
+ if testing:
65
+ return "pd.DataFrame"
66
+ assert run
67
+
68
+ artifact = wandb.Artifact(name, type="dataset")
69
+ with artifact.new_file(f"{name}.parquet", "wb") as f:
70
+ data.to_parquet(f, engine="pyarrow")
71
+
72
+ wandb.termlog(f"Logging artifact: {name} (Pandas DataFrame)")
73
+ run.log_artifact(artifact)
74
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_pytorch.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for PyTorch datatypes.
2
+
3
+ May raise MissingDependencyError on import.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing_extensions import Any, TypeIs
9
+
10
+ import wandb
11
+
12
+ from . import errors
13
+
14
+ try:
15
+ import torch
16
+ import torch.nn as nn
17
+ except ImportError as e:
18
+ warning = (
19
+ "`torch` (PyTorch) not installed >>"
20
+ " @wandb_log(models=True) may not auto log your model!"
21
+ )
22
+ raise errors.MissingDependencyError(warning=warning) from e
23
+
24
+
25
+ def is_nn_module(data: Any) -> TypeIs[nn.Module]:
26
+ """Returns whether the data is a PyTorch nn.Module."""
27
+ return isinstance(data, nn.Module)
28
+
29
+
30
+ def use_nn_module(
31
+ name: str,
32
+ run: wandb.Run | None,
33
+ testing: bool = False,
34
+ ) -> str | None:
35
+ """Log a dependency on a PyTorch model input.
36
+
37
+ Args:
38
+ name: Name of the input.
39
+ run: The run to update.
40
+ testing: True in unit tests.
41
+ """
42
+ if testing:
43
+ return "models"
44
+ assert run
45
+
46
+ wandb.termlog(f"Using artifact: {name} (PyTorch nn.Module)")
47
+ run.use_artifact(f"{name}:latest")
48
+ return None
49
+
50
+
51
+ def track_nn_module(
52
+ name: str,
53
+ data: nn.Module,
54
+ run: wandb.Run | None,
55
+ testing: bool = False,
56
+ ) -> str | None:
57
+ """Log a PyTorch model output as an artifact.
58
+
59
+ Args:
60
+ name: The output's name.
61
+ data: The output's value.
62
+ run: The run to update.
63
+ testing: True in unit tests.
64
+ """
65
+ if testing:
66
+ return "nn.Module"
67
+ assert run
68
+
69
+ artifact = wandb.Artifact(name, type="model")
70
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
71
+ torch.save(data, f)
72
+
73
+ wandb.termlog(f"Logging artifact: {name} (PyTorch nn.Module)")
74
+ run.log_artifact(artifact)
75
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/data_sklearn.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for sklearn datatypes.
2
+
3
+ May raise MissingDependencyError on import.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import pickle
9
+
10
+ from typing_extensions import Any, TypeIs
11
+
12
+ import wandb
13
+
14
+ from . import errors
15
+
16
+ try:
17
+ from sklearn.base import BaseEstimator
18
+ except ImportError as e:
19
+ warning = (
20
+ "`sklearn` not installed >>"
21
+ " @wandb_log(models=True) may not auto log your model!"
22
+ )
23
+ raise errors.MissingDependencyError(warning=warning) from e
24
+
25
+
26
+ def is_estimator(data: Any) -> TypeIs[BaseEstimator]:
27
+ """Returns whether the data is an sklearn BaseEstimator."""
28
+ return isinstance(data, BaseEstimator)
29
+
30
+
31
+ def use_estimator(
32
+ name: str,
33
+ run: wandb.Run | None,
34
+ testing: bool = False,
35
+ ) -> str | None:
36
+ """Log a dependency on an sklearn estimator.
37
+
38
+ Args:
39
+ name: Name of the input.
40
+ run: The run to update.
41
+ testing: True in unit tests.
42
+ """
43
+ if testing:
44
+ return "models"
45
+ assert run
46
+
47
+ wandb.termlog(f"Using artifact: {name} (sklearn BaseEstimator)")
48
+ run.use_artifact(f"{name}:latest")
49
+ return None
50
+
51
+
52
+ def track_estimator(
53
+ name: str,
54
+ data: BaseEstimator,
55
+ run: wandb.Run | None,
56
+ testing: bool = False,
57
+ ) -> str | None:
58
+ """Log an sklearn estimator output as an artifact.
59
+
60
+ Args:
61
+ name: The output's name.
62
+ data: The output's value.
63
+ run: The run to update.
64
+ testing: True in unit tests.
65
+ """
66
+ if testing:
67
+ return "BaseEstimator"
68
+ assert run
69
+
70
+ artifact = wandb.Artifact(name, type="model")
71
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
72
+ pickle.dump(data, f)
73
+
74
+ wandb.termlog(f"Logging artifact: {name} (sklearn BaseEstimator)")
75
+ run.log_artifact(artifact)
76
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/errors.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wandb
2
+
3
+
4
+ class MissingDependencyError(Exception):
5
+ """An optional dependency is missing."""
6
+
7
+ def __init__(self, *args: object, warning: str) -> None:
8
+ super().__init__(*args)
9
+ self._wb_warning = warning
10
+
11
+ def warn(self) -> None:
12
+ """Print a warning for the problem."""
13
+ wandb.termwarn(self._wb_warning)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/metaflow/metaflow.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import pickle
5
+ from functools import wraps
6
+ from pathlib import Path
7
+
8
+ import wandb
9
+ from wandb.sdk.lib import telemetry as wb_telemetry
10
+
11
+ from . import errors
12
+
13
+ try:
14
+ from metaflow import current
15
+ except ImportError as e:
16
+ raise Exception(
17
+ "Error: `metaflow` not installed >> This integration requires metaflow!"
18
+ " To fix, please `pip install -Uqq metaflow`"
19
+ ) from e
20
+
21
+
22
+ try:
23
+ from . import data_pandas
24
+ except errors.MissingDependencyError as e:
25
+ e.warn()
26
+ data_pandas = None
27
+
28
+ try:
29
+ from . import data_pytorch
30
+ except errors.MissingDependencyError as e:
31
+ e.warn()
32
+ data_pytorch = None
33
+
34
+ try:
35
+ from . import data_sklearn
36
+ except errors.MissingDependencyError as e:
37
+ e.warn()
38
+ data_sklearn = None
39
+
40
+
41
+ class ArtifactProxy:
42
+ def __init__(self, flow):
43
+ # do this to avoid recursion problem with __setattr__
44
+ self.__dict__.update(
45
+ {
46
+ "flow": flow,
47
+ "inputs": {},
48
+ "outputs": {},
49
+ "base": set(dir(flow)),
50
+ "params": {p: getattr(flow, p) for p in current.parameter_names},
51
+ }
52
+ )
53
+
54
+ def __setattr__(self, key, val):
55
+ self.outputs[key] = val
56
+ return setattr(self.flow, key, val)
57
+
58
+ def __getattr__(self, key):
59
+ if key not in self.base and key not in self.outputs:
60
+ self.inputs[key] = getattr(self.flow, key)
61
+ return getattr(self.flow, key)
62
+
63
+
64
+ def _track_scalar(
65
+ name: str,
66
+ data: dict | list | set | str | int | float | bool,
67
+ run,
68
+ testing: bool = False,
69
+ ) -> str | None:
70
+ if testing:
71
+ return "scalar"
72
+
73
+ run.log({name: data})
74
+ return None
75
+
76
+
77
+ def _track_path(
78
+ name: str,
79
+ data: Path,
80
+ run,
81
+ testing: bool = False,
82
+ ) -> str | None:
83
+ if testing:
84
+ return "Path"
85
+
86
+ artifact = wandb.Artifact(name, type="dataset")
87
+ if data.is_dir():
88
+ artifact.add_dir(data)
89
+ elif data.is_file():
90
+ artifact.add_file(data)
91
+ run.log_artifact(artifact)
92
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
93
+ return None
94
+
95
+
96
+ def _track_generic(
97
+ name: str,
98
+ data,
99
+ run,
100
+ testing: bool = False,
101
+ ) -> str | None:
102
+ if testing:
103
+ return "generic"
104
+
105
+ artifact = wandb.Artifact(name, type="other")
106
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
107
+ pickle.dump(data, f)
108
+ run.log_artifact(artifact)
109
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
110
+ return None
111
+
112
+
113
+ def wandb_track(
114
+ name: str,
115
+ data,
116
+ datasets: bool = False,
117
+ models: bool = False,
118
+ others: bool = False,
119
+ run: wandb.Run | None = None,
120
+ testing: bool = False,
121
+ ) -> str | None:
122
+ """Track data as wandb artifacts based on type and flags."""
123
+ # Check for pandas DataFrame
124
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
125
+ return data_pandas.track_dataframe(name, data, run, testing)
126
+
127
+ # Check for PyTorch Module
128
+ if data_pytorch and data_pytorch.is_nn_module(data) and models:
129
+ return data_pytorch.track_nn_module(name, data, run, testing)
130
+
131
+ # Check for scikit-learn BaseEstimator
132
+ if data_sklearn and data_sklearn.is_estimator(data) and models:
133
+ return data_sklearn.track_estimator(name, data, run, testing)
134
+
135
+ # Check for Path objects
136
+ if isinstance(data, Path) and datasets:
137
+ return _track_path(name, data, run, testing)
138
+
139
+ # Check for scalar types
140
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
141
+ return _track_scalar(name, data, run, testing)
142
+
143
+ # Generic fallback
144
+ if others:
145
+ return _track_generic(name, data, run, testing)
146
+
147
+ # No action taken
148
+ return None
149
+
150
+
151
+ def wandb_use(
152
+ name: str,
153
+ data,
154
+ datasets: bool = False,
155
+ models: bool = False,
156
+ others: bool = False,
157
+ run=None,
158
+ testing: bool = False,
159
+ ) -> str | None:
160
+ """Use wandb artifacts based on data type and flags."""
161
+ # Skip scalar types - nothing to use
162
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
163
+ return None
164
+
165
+ try:
166
+ # Check for pandas DataFrame
167
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
168
+ return data_pandas.use_dataframe(name, run, testing)
169
+
170
+ # Check for PyTorch Module
171
+ elif data_pytorch and data_pytorch.is_nn_module(data) and models:
172
+ return data_pytorch.use_nn_module(name, run, testing)
173
+
174
+ # Check for scikit-learn BaseEstimator
175
+ elif data_sklearn and data_sklearn.is_estimator(data) and models:
176
+ return data_sklearn.use_estimator(name, run, testing)
177
+
178
+ # Check for Path objects
179
+ elif isinstance(data, Path) and datasets:
180
+ return _use_path(name, data, run, testing)
181
+
182
+ # Generic fallback
183
+ elif others:
184
+ return _use_generic(name, data, run, testing)
185
+
186
+ else:
187
+ return None
188
+
189
+ except wandb.CommError:
190
+ wandb.termwarn(
191
+ f"This artifact ({name}, {type(data)}) does not exist in the wandb datastore!"
192
+ " If you created an instance inline (e.g. sklearn.ensemble.RandomForestClassifier),"
193
+ " then you can safely ignore this. Otherwise you may want to check your internet connection!"
194
+ )
195
+ return None
196
+
197
+
198
+ def _use_path(
199
+ name: str,
200
+ data: Path,
201
+ run,
202
+ testing: bool = False,
203
+ ) -> str | None:
204
+ if testing:
205
+ return "datasets"
206
+
207
+ run.use_artifact(f"{name}:latest")
208
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
209
+ return None
210
+
211
+
212
+ def _use_generic(
213
+ name: str,
214
+ data,
215
+ run,
216
+ testing: bool = False,
217
+ ) -> str | None:
218
+ if testing:
219
+ return "others"
220
+
221
+ run.use_artifact(f"{name}:latest")
222
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
223
+ return None
224
+
225
+
226
+ def coalesce(*arg):
227
+ return next((a for a in arg if a is not None), None)
228
+
229
+
230
+ def wandb_log(
231
+ func=None,
232
+ /,
233
+ datasets: bool = False,
234
+ models: bool = False,
235
+ others: bool = False,
236
+ settings: wandb.Settings | None = None,
237
+ ):
238
+ """Automatically log parameters and artifacts to W&B.
239
+
240
+ This decorator can be applied to a flow, step, or both:
241
+
242
+ - Decorating a step enables or disables logging within that step
243
+ - Decorating a flow is equivalent to decorating all steps
244
+ - Decorating a step after decorating its flow overwrites the flow decoration
245
+
246
+ Args:
247
+ func: The step method or flow class to decorate.
248
+ datasets: Whether to log `pd.DataFrame` and `pathlib.Path`
249
+ types. Defaults to False.
250
+ models: Whether to log `nn.Module` and `sklearn.base.BaseEstimator`
251
+ types. Defaults to False.
252
+ others: If `True`, log anything pickle-able. Defaults to False.
253
+ settings: Custom settings to pass to `wandb.init`.
254
+ If `run_group` is `None`, it is set to `{flow_name}/{run_id}`.
255
+ If `run_job_type` is `None`, it is set to `{run_job_type}/{step_name}`.
256
+ """
257
+
258
+ @wraps(func)
259
+ def decorator(func):
260
+ # If you decorate a class, apply the decoration to all methods in that class
261
+ if inspect.isclass(func):
262
+ cls = func
263
+ for attr in cls.__dict__:
264
+ if callable(getattr(cls, attr)) and not hasattr(attr, "_base_func"):
265
+ setattr(cls, attr, decorator(getattr(cls, attr)))
266
+ return cls
267
+
268
+ # prefer the earliest decoration (i.e. method decoration overrides class decoration)
269
+ if hasattr(func, "_base_func"):
270
+ return func
271
+
272
+ @wraps(func)
273
+ def wrapper(self, *args, settings=settings, **kwargs):
274
+ if not isinstance(settings, wandb.sdk.wandb_settings.Settings):
275
+ settings = wandb.Settings()
276
+
277
+ settings.update_from_dict(
278
+ {
279
+ "run_group": coalesce(
280
+ settings.run_group, f"{current.flow_name}/{current.run_id}"
281
+ ),
282
+ "run_job_type": coalesce(settings.run_job_type, current.step_name),
283
+ }
284
+ )
285
+
286
+ with wandb.init(settings=settings) as run:
287
+ with wb_telemetry.context(run=run) as tel:
288
+ tel.feature.metaflow = True
289
+ proxy = ArtifactProxy(self)
290
+ run.config.update(proxy.params)
291
+ func(proxy, *args, **kwargs)
292
+
293
+ for name, data in proxy.inputs.items():
294
+ wandb_use(
295
+ name,
296
+ data,
297
+ datasets=datasets,
298
+ models=models,
299
+ others=others,
300
+ run=run,
301
+ )
302
+
303
+ for name, data in proxy.outputs.items():
304
+ wandb_track(
305
+ name,
306
+ data,
307
+ datasets=datasets,
308
+ models=models,
309
+ others=others,
310
+ run=run,
311
+ )
312
+
313
+ wrapper._base_func = func
314
+
315
+ # Add for testing visibility
316
+ wrapper._kwargs = {
317
+ "datasets": datasets,
318
+ "models": models,
319
+ "others": others,
320
+ "settings": settings,
321
+ }
322
+ return wrapper
323
+
324
+ if func is None:
325
+ return decorator
326
+ else:
327
+ return decorator(func)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __all__ = ("autolog", "WandbLogger")
2
+
3
+ from .openai import autolog
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import datetime
5
+ import io
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ import time
11
+ from typing import Any
12
+
13
+ from packaging.version import parse
14
+
15
+ import wandb
16
+ from wandb import util
17
+ from wandb.data_types import Table
18
+ from wandb.sdk.lib import telemetry
19
+
20
+ openai = util.get_module(
21
+ name="openai",
22
+ required="This integration requires `openai`. To install, please run `pip install openai`",
23
+ lazy=False,
24
+ )
25
+
26
+ if parse(openai.__version__) < parse("1.12.0"):
27
+ raise wandb.Error(
28
+ f"This integration requires openai version 1.12.0 and above. Your current version is {openai.__version__} "
29
+ "To fix, please `pip install -U openai`"
30
+ )
31
+
32
+ from openai import OpenAI # noqa: E402
33
+ from openai.types.fine_tuning import FineTuningJob # noqa: E402
34
+ from openai.types.fine_tuning.fine_tuning_job import ( # noqa: E402
35
+ Error,
36
+ Hyperparameters,
37
+ )
38
+
39
+ np = util.get_module(
40
+ name="numpy",
41
+ required="`numpy` not installed >> This integration requires numpy! To fix, please `pip install numpy`",
42
+ lazy=False,
43
+ )
44
+
45
+ pd = util.get_module(
46
+ name="pandas",
47
+ required="`pandas` not installed >> This integration requires pandas! To fix, please `pip install pandas`",
48
+ lazy=False,
49
+ )
50
+
51
+
52
+ class WandbLogger:
53
+ """Log OpenAI fine-tunes to [Weights & Biases](https://wandb.me/openai-docs)."""
54
+
55
+ _wandb_api: wandb.Api | None = None
56
+ _logged_in: bool = False
57
+ openai_client: OpenAI | None = None
58
+ _run: wandb.Run | None = None
59
+
60
+ @classmethod
61
+ def sync(
62
+ cls,
63
+ fine_tune_job_id: str | None = None,
64
+ openai_client: OpenAI | None = None,
65
+ num_fine_tunes: int | None = None,
66
+ project: str = "OpenAI-Fine-Tune",
67
+ entity: str | None = None,
68
+ overwrite: bool = False,
69
+ wait_for_job_success: bool = True,
70
+ log_datasets: bool = True,
71
+ model_artifact_name: str = "model-metadata",
72
+ model_artifact_type: str = "model",
73
+ **kwargs_wandb_init: dict[str, Any],
74
+ ) -> str:
75
+ """Sync fine-tunes to Weights & Biases.
76
+
77
+ :param fine_tune_job_id: The id of the fine-tune (optional)
78
+ :param openai_client: Pass the `OpenAI()` client (optional)
79
+ :param num_fine_tunes: Number of most recent fine-tunes to log when an fine_tune_job_id is not provided. By default, every fine-tune is synced.
80
+ :param project: Name of the project where you're sending runs. By default, it is "GPT-3".
81
+ :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.
82
+ :param overwrite: Forces logging and overwrite existing wandb run of the same fine-tune.
83
+ :param wait_for_job_success: Waits for the fine-tune to be complete and then log metrics to W&B. By default, it is True.
84
+ :param model_artifact_name: Name of the model artifact that is logged
85
+ :param model_artifact_type: Type of the model artifact that is logged
86
+ """
87
+ if openai_client is None:
88
+ openai_client = OpenAI()
89
+ cls.openai_client = openai_client
90
+
91
+ if fine_tune_job_id:
92
+ wandb.termlog("Retrieving fine-tune job...")
93
+ fine_tune = openai_client.fine_tuning.jobs.retrieve(
94
+ fine_tuning_job_id=fine_tune_job_id
95
+ )
96
+ fine_tunes = [fine_tune]
97
+ else:
98
+ # get list of fine_tune to log
99
+ fine_tunes = openai_client.fine_tuning.jobs.list()
100
+ if not fine_tunes or fine_tunes.data is None:
101
+ wandb.termwarn("No fine-tune has been retrieved")
102
+ return
103
+ # Select the `num_fine_tunes` from the `fine_tunes.data` list.
104
+ # If `num_fine_tunes` is None, it selects all items in the list (from start to end).
105
+ # If for example, `num_fine_tunes` is 5, it selects the last 5 items in the list.
106
+ # Note that the last items in the list are the latest fine-tune jobs.
107
+ fine_tunes = fine_tunes.data[
108
+ -num_fine_tunes if num_fine_tunes is not None else None :
109
+ ]
110
+
111
+ # log starting from oldest fine_tune
112
+ show_individual_warnings = (
113
+ fine_tune_job_id is not None or num_fine_tunes is not None
114
+ )
115
+ fine_tune_logged = []
116
+ for fine_tune in fine_tunes:
117
+ fine_tune_id = fine_tune.id
118
+ # check run with the given `fine_tune_id` has not been logged already
119
+ run_path = f"{project}/{fine_tune_id}"
120
+ if entity is not None:
121
+ run_path = f"{entity}/{run_path}"
122
+ wandb_run = cls._get_wandb_run(run_path)
123
+ if wandb_run:
124
+ wandb_status = wandb_run.summary.get("status")
125
+ if show_individual_warnings:
126
+ if wandb_status == "succeeded" and not overwrite:
127
+ wandb.termwarn(
128
+ f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}. "
129
+ "Use `overwrite=True` if you want to overwrite previous run"
130
+ )
131
+ elif wandb_status != "succeeded" or overwrite:
132
+ if wandb_status != "succeeded":
133
+ wandb.termwarn(
134
+ f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully"
135
+ )
136
+ wandb.termlog(
137
+ f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten"
138
+ )
139
+ overwrite = True
140
+ if wandb_status == "succeeded" and not overwrite:
141
+ return
142
+
143
+ # check if the user has not created a wandb run externally
144
+ if wandb.run is None:
145
+ cls._run = wandb.init(
146
+ job_type="fine-tune",
147
+ project=project,
148
+ entity=entity,
149
+ name=fine_tune_id,
150
+ id=fine_tune_id,
151
+ **kwargs_wandb_init,
152
+ )
153
+ else:
154
+ # if a run exits - created externally
155
+ cls._run = wandb.run
156
+
157
+ if wait_for_job_success:
158
+ fine_tune = cls._wait_for_job_success(fine_tune)
159
+
160
+ cls._log_fine_tune(
161
+ fine_tune,
162
+ project,
163
+ entity,
164
+ overwrite,
165
+ show_individual_warnings,
166
+ log_datasets,
167
+ model_artifact_name,
168
+ model_artifact_type,
169
+ **kwargs_wandb_init,
170
+ )
171
+
172
+ if not show_individual_warnings and not any(fine_tune_logged):
173
+ wandb.termwarn("No new successful fine-tunes were found")
174
+
175
+ return "🎉 wandb sync completed successfully"
176
+
177
+ @classmethod
178
+ def _wait_for_job_success(cls, fine_tune: FineTuningJob) -> FineTuningJob:
179
+ wandb.termlog("Waiting for the OpenAI fine-tuning job to finish training...")
180
+ wandb.termlog(
181
+ "To avoid blocking, you can call `WandbLogger.sync` with `wait_for_job_success=False` after OpenAI training completes."
182
+ )
183
+ while True:
184
+ if fine_tune.status == "succeeded":
185
+ wandb.termlog(
186
+ "Fine-tuning finished, logging metrics, model metadata, and run metadata to Weights & Biases"
187
+ )
188
+ return fine_tune
189
+ if fine_tune.status == "failed":
190
+ wandb.termwarn(
191
+ f"Fine-tune {fine_tune.id} has failed and will not be logged"
192
+ )
193
+ return fine_tune
194
+ if fine_tune.status == "cancelled":
195
+ wandb.termwarn(
196
+ f"Fine-tune {fine_tune.id} was cancelled and will not be logged"
197
+ )
198
+ return fine_tune
199
+ time.sleep(10)
200
+ fine_tune = cls.openai_client.fine_tuning.jobs.retrieve(
201
+ fine_tuning_job_id=fine_tune.id
202
+ )
203
+
204
+ @classmethod
205
+ def _log_fine_tune(
206
+ cls,
207
+ fine_tune: FineTuningJob,
208
+ project: str,
209
+ entity: str | None,
210
+ overwrite: bool,
211
+ show_individual_warnings: bool,
212
+ log_datasets: bool,
213
+ model_artifact_name: str,
214
+ model_artifact_type: str,
215
+ **kwargs_wandb_init: dict[str, Any],
216
+ ):
217
+ fine_tune_id = fine_tune.id
218
+ status = fine_tune.status
219
+
220
+ with telemetry.context(run=cls._run) as tel:
221
+ tel.feature.openai_finetuning = True
222
+
223
+ # check run completed successfully
224
+ if status != "succeeded":
225
+ if show_individual_warnings:
226
+ wandb.termwarn(
227
+ f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged'
228
+ )
229
+ return
230
+
231
+ # check results are present
232
+ try:
233
+ results_id = fine_tune.result_files[0]
234
+ try:
235
+ encoded_results = cls.openai_client.files.content(
236
+ file_id=results_id
237
+ ).read()
238
+ results = base64.b64decode(encoded_results).decode("utf-8")
239
+ except Exception:
240
+ # attempt to read as text, works for older jobs
241
+ results = cls.openai_client.files.content(file_id=results_id).text
242
+ except openai.NotFoundError:
243
+ if show_individual_warnings:
244
+ wandb.termwarn(
245
+ f"Fine-tune {fine_tune_id} has no results and will not be logged"
246
+ )
247
+ return
248
+
249
+ # update the config
250
+ cls._run.config.update(cls._get_config(fine_tune))
251
+
252
+ # log results
253
+ df_results = pd.read_csv(io.StringIO(results))
254
+ for _, row in df_results.iterrows():
255
+ metrics = {k: v for k, v in row.items() if not np.isnan(v)}
256
+ step = metrics.pop("step")
257
+ if step is not None:
258
+ step = int(step)
259
+ cls._run.log(metrics, step=step)
260
+ fine_tuned_model = fine_tune.fine_tuned_model
261
+ if fine_tuned_model is not None:
262
+ cls._run.summary["fine_tuned_model"] = fine_tuned_model
263
+
264
+ # training/validation files and fine-tune details
265
+ cls._log_artifacts(
266
+ fine_tune,
267
+ project,
268
+ entity,
269
+ log_datasets,
270
+ overwrite,
271
+ model_artifact_name,
272
+ model_artifact_type,
273
+ )
274
+
275
+ # mark run as complete
276
+ cls._run.summary["status"] = "succeeded"
277
+
278
+ cls._run.finish()
279
+ return True
280
+
281
+ @classmethod
282
+ def _ensure_logged_in(cls):
283
+ if not cls._logged_in:
284
+ if wandb.login():
285
+ cls._logged_in = True
286
+ else:
287
+ raise Exception(
288
+ "It appears you are not currently logged in to Weights & Biases. "
289
+ "Please run `wandb login` in your terminal or `wandb.login()` in a notebook. "
290
+ "Create a new API key at https://wandb.ai/settings and store it securely."
291
+ )
292
+
293
+ @classmethod
294
+ def _get_wandb_run(cls, run_path: str):
295
+ cls._ensure_logged_in()
296
+ try:
297
+ if cls._wandb_api is None:
298
+ cls._wandb_api = wandb.Api()
299
+ return cls._wandb_api.run(run_path)
300
+ except Exception:
301
+ return None
302
+
303
+ @classmethod
304
+ def _get_wandb_artifact(cls, artifact_path: str):
305
+ cls._ensure_logged_in()
306
+ try:
307
+ if cls._wandb_api is None:
308
+ cls._wandb_api = wandb.Api()
309
+ return cls._wandb_api.artifact(artifact_path)
310
+ except Exception:
311
+ return None
312
+
313
+ @classmethod
314
+ def _get_config(cls, fine_tune: FineTuningJob) -> dict[str, Any]:
315
+ config = dict(fine_tune)
316
+ config["result_files"] = config["result_files"][0]
317
+ if config.get("created_at"):
318
+ config["created_at"] = datetime.datetime.fromtimestamp(
319
+ config["created_at"]
320
+ ).strftime("%Y-%m-%d %H:%M:%S")
321
+ if config.get("finished_at"):
322
+ config["finished_at"] = datetime.datetime.fromtimestamp(
323
+ config["finished_at"]
324
+ ).strftime("%Y-%m-%d %H:%M:%S")
325
+ if config.get("hyperparameters"):
326
+ config["hyperparameters"] = cls.sanitize(config["hyperparameters"])
327
+ if config.get("error"):
328
+ config["error"] = cls.sanitize(config["error"])
329
+ return config
330
+
331
+ @classmethod
332
+ def _unpack_hyperparameters(cls, hyperparameters: Hyperparameters):
333
+ # `Hyperparameters` object is not unpacking properly using `vars` or `__dict__`,
334
+ # vars(hyperparameters) return {n_epochs: n} only.
335
+ hyperparams = {}
336
+ try:
337
+ hyperparams["n_epochs"] = hyperparameters.n_epochs
338
+ hyperparams["batch_size"] = hyperparameters.batch_size
339
+ hyperparams["learning_rate_multiplier"] = (
340
+ hyperparameters.learning_rate_multiplier
341
+ )
342
+ except Exception:
343
+ # If unpacking fails, return the object to be logged as config
344
+ return None
345
+
346
+ return hyperparams
347
+
348
+ @staticmethod
349
+ def sanitize(input: Any) -> dict | list | str:
350
+ valid_types = [bool, int, float, str]
351
+ if isinstance(input, (Hyperparameters, Error)):
352
+ return dict(input)
353
+ if isinstance(input, dict):
354
+ return {
355
+ k: v if type(v) in valid_types else str(v) for k, v in input.items()
356
+ }
357
+ elif isinstance(input, list):
358
+ return [v if type(v) in valid_types else str(v) for v in input]
359
+ else:
360
+ return str(input)
361
+
362
+ @classmethod
363
+ def _log_artifacts(
364
+ cls,
365
+ fine_tune: FineTuningJob,
366
+ project: str,
367
+ entity: str | None,
368
+ log_datasets: bool,
369
+ overwrite: bool,
370
+ model_artifact_name: str,
371
+ model_artifact_type: str,
372
+ ) -> None:
373
+ if log_datasets:
374
+ wandb.termlog("Logging training/validation files...")
375
+ # training/validation files
376
+ training_file = fine_tune.training_file if fine_tune.training_file else None
377
+ validation_file = (
378
+ fine_tune.validation_file if fine_tune.validation_file else None
379
+ )
380
+ for file, prefix, artifact_type in (
381
+ (training_file, "train", "training_files"),
382
+ (validation_file, "valid", "validation_files"),
383
+ ):
384
+ if file is not None:
385
+ cls._log_artifact_inputs(
386
+ file, prefix, artifact_type, project, entity, overwrite
387
+ )
388
+
389
+ # fine-tune details
390
+ fine_tune_id = fine_tune.id
391
+ artifact = wandb.Artifact(
392
+ model_artifact_name,
393
+ type=model_artifact_type,
394
+ metadata=dict(fine_tune),
395
+ )
396
+
397
+ with artifact.new_file("model_metadata.json", mode="w", encoding="utf-8") as f:
398
+ dict_fine_tune = dict(fine_tune)
399
+ dict_fine_tune["hyperparameters"] = cls.sanitize(
400
+ dict_fine_tune["hyperparameters"]
401
+ )
402
+ dict_fine_tune["error"] = cls.sanitize(dict_fine_tune["error"])
403
+ dict_fine_tune = cls.sanitize(dict_fine_tune)
404
+ json.dump(dict_fine_tune, f, indent=2)
405
+ cls._run.log_artifact(
406
+ artifact,
407
+ aliases=["latest", fine_tune_id],
408
+ )
409
+
410
+ @classmethod
411
+ def _log_artifact_inputs(
412
+ cls,
413
+ file_id: str | None,
414
+ prefix: str,
415
+ artifact_type: str,
416
+ project: str,
417
+ entity: str | None,
418
+ overwrite: bool,
419
+ ) -> None:
420
+ # get input artifact
421
+ artifact_name = f"{prefix}-{file_id}"
422
+ # sanitize name to valid wandb artifact name
423
+ artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name)
424
+ artifact_alias = file_id
425
+ artifact_path = f"{project}/{artifact_name}:{artifact_alias}"
426
+ if entity is not None:
427
+ artifact_path = f"{entity}/{artifact_path}"
428
+ artifact = cls._get_wandb_artifact(artifact_path)
429
+
430
+ # create artifact if file not already logged previously
431
+ if artifact is None or overwrite:
432
+ # get file content
433
+ try:
434
+ file_content = cls.openai_client.files.content(file_id=file_id)
435
+ except openai.NotFoundError:
436
+ wandb.termerror(
437
+ f"File {file_id} could not be retrieved. Make sure you have OpenAI permissions to download training/validation files"
438
+ )
439
+ return
440
+
441
+ artifact = wandb.Artifact(artifact_name, type=artifact_type)
442
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
443
+ tmp_file.write(file_content.content)
444
+ tmp_file_path = tmp_file.name
445
+ artifact.add_file(tmp_file_path, file_id)
446
+ os.unlink(tmp_file_path)
447
+
448
+ # create a Table
449
+ try:
450
+ table, n_items = cls._make_table(file_content.text)
451
+ # Add table to the artifact.
452
+ artifact.add(table, file_id)
453
+ # Add the same table to the workspace.
454
+ cls._run.log({f"{prefix}_data": table})
455
+ # Update the run config and artifact metadata
456
+ cls._run.config.update({f"n_{prefix}": n_items})
457
+ artifact.metadata["items"] = n_items
458
+ except Exception as e:
459
+ wandb.termerror(
460
+ f"Issue saving {file_id} as a Table to Artifacts, exception:\n '{e}'"
461
+ )
462
+ else:
463
+ # log number of items
464
+ cls._run.config.update({f"n_{prefix}": artifact.metadata.get("items")})
465
+
466
+ cls._run.use_artifact(artifact, aliases=["latest", artifact_alias])
467
+
468
+ @classmethod
469
+ def _make_table(cls, file_content: str) -> tuple[Table, int]:
470
+ table = wandb.Table(columns=["role: system", "role: user", "role: assistant"])
471
+
472
+ df = pd.read_json(io.StringIO(file_content), orient="records", lines=True)
473
+ for _idx, message in df.iterrows():
474
+ messages = message.messages
475
+ assert len(messages) == 3
476
+ table.add_data(
477
+ messages[0]["content"],
478
+ messages[1]["content"],
479
+ messages[2]["content"],
480
+ )
481
+
482
+ return table, len(df)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/openai.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from wandb.sdk.integration_utils.auto_logging import AutologAPI
4
+
5
+ from .resolver import OpenAIRequestResponseResolver
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ autolog = AutologAPI(
11
+ name="OpenAI",
12
+ symbols=(
13
+ "Edit.create",
14
+ "Completion.create",
15
+ "ChatCompletion.create",
16
+ "Edit.acreate",
17
+ "Completion.acreate",
18
+ "ChatCompletion.acreate",
19
+ ),
20
+ resolver=OpenAIRequestResponseResolver(),
21
+ telemetry_feature="openai_autolog",
22
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/openai/resolver.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import io
5
+ import logging
6
+ from collections.abc import Sequence
7
+ from dataclasses import asdict, dataclass
8
+ from typing import Any
9
+
10
+ import wandb
11
+ from wandb.sdk.data_types import trace_tree
12
+ from wandb.sdk.integration_utils.auto_logging import Response
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ @dataclass
18
+ class UsageMetrics:
19
+ elapsed_time: float = None
20
+ prompt_tokens: int = None
21
+ completion_tokens: int = None
22
+ total_tokens: int = None
23
+
24
+
25
+ @dataclass
26
+ class Metrics:
27
+ usage: UsageMetrics = None
28
+ stats: wandb.Table = None
29
+ trace: trace_tree.WBTraceTree = None
30
+
31
+
32
+ usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())}
33
+
34
+
35
+ class OpenAIRequestResponseResolver:
36
+ def __init__(self):
37
+ self.define_metrics_called = False
38
+
39
+ def __call__(
40
+ self,
41
+ args: Sequence[Any],
42
+ kwargs: dict[str, Any],
43
+ response: Response,
44
+ start_time: float, # pass to comply with the protocol, but use response["created"] instead
45
+ time_elapsed: float,
46
+ ) -> dict[str, Any] | None:
47
+ request = kwargs
48
+
49
+ if not self.define_metrics_called:
50
+ # define metrics on first call
51
+ for key in usage_metric_keys:
52
+ wandb.define_metric(key, step_metric="_timestamp")
53
+ self.define_metrics_called = True
54
+
55
+ try:
56
+ if response.get("object") == "edit":
57
+ return self._resolve_edit(request, response, time_elapsed)
58
+ elif response.get("object") == "text_completion":
59
+ return self._resolve_completion(request, response, time_elapsed)
60
+ elif response.get("object") == "chat.completion":
61
+ return self._resolve_chat_completion(request, response, time_elapsed)
62
+ else:
63
+ # todo: properly treat failed requests
64
+ logger.info(
65
+ f"Unsupported OpenAI response object: {response.get('object')}"
66
+ )
67
+ except Exception as e:
68
+ logger.warning(f"Failed to resolve request/response: {e}")
69
+ return None
70
+
71
+ @staticmethod
72
+ def results_to_trace_tree(
73
+ request: dict[str, Any],
74
+ response: Response,
75
+ results: list[trace_tree.Result],
76
+ time_elapsed: float,
77
+ ) -> trace_tree.WBTraceTree:
78
+ """Converts the request, response, and results into a trace tree.
79
+
80
+ params:
81
+ request: The request dictionary
82
+ response: The response object
83
+ results: A list of results object
84
+ time_elapsed: The time elapsed in seconds
85
+ returns:
86
+ A wandb trace tree object.
87
+ """
88
+ start_time_ms = int(round(response["created"] * 1000))
89
+ end_time_ms = start_time_ms + int(round(time_elapsed * 1000))
90
+ span = trace_tree.Span(
91
+ name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}",
92
+ attributes=dict(response), # type: ignore
93
+ start_time_ms=start_time_ms,
94
+ end_time_ms=end_time_ms,
95
+ span_kind=trace_tree.SpanKind.LLM,
96
+ results=results,
97
+ )
98
+ model_obj = {"request": request, "response": response, "_kind": "openai"}
99
+ return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj)
100
+
101
+ def _resolve_edit(
102
+ self,
103
+ request: dict[str, Any],
104
+ response: Response,
105
+ time_elapsed: float,
106
+ ) -> dict[str, Any]:
107
+ """Resolves the request and response objects for `openai.Edit`."""
108
+ request_str = (
109
+ f"\n\n**Instruction**: {request['instruction']}\n\n"
110
+ f"**Input**: {request['input']}\n"
111
+ )
112
+ choices = [
113
+ f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"]
114
+ ]
115
+
116
+ return self._resolve_metrics(
117
+ request=request,
118
+ response=response,
119
+ request_str=request_str,
120
+ choices=choices,
121
+ time_elapsed=time_elapsed,
122
+ )
123
+
124
+ def _resolve_completion(
125
+ self,
126
+ request: dict[str, Any],
127
+ response: Response,
128
+ time_elapsed: float,
129
+ ) -> dict[str, Any]:
130
+ """Resolves the request and response objects for `openai.Completion`."""
131
+ request_str = f"\n\n**Prompt**: {request['prompt']}\n"
132
+ choices = [
133
+ f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"]
134
+ ]
135
+
136
+ return self._resolve_metrics(
137
+ request=request,
138
+ response=response,
139
+ request_str=request_str,
140
+ choices=choices,
141
+ time_elapsed=time_elapsed,
142
+ )
143
+
144
+ def _resolve_chat_completion(
145
+ self,
146
+ request: dict[str, Any],
147
+ response: Response,
148
+ time_elapsed: float,
149
+ ) -> dict[str, Any]:
150
+ """Resolves the request and response objects for `openai.Completion`."""
151
+ prompt = io.StringIO()
152
+ for message in request["messages"]:
153
+ prompt.write(f"\n\n**{message['role']}**: {message['content']}\n")
154
+ request_str = prompt.getvalue()
155
+
156
+ choices = [
157
+ f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n"
158
+ for choice in response["choices"]
159
+ ]
160
+
161
+ return self._resolve_metrics(
162
+ request=request,
163
+ response=response,
164
+ request_str=request_str,
165
+ choices=choices,
166
+ time_elapsed=time_elapsed,
167
+ )
168
+
169
+ def _resolve_metrics(
170
+ self,
171
+ request: dict[str, Any],
172
+ response: Response,
173
+ request_str: str,
174
+ choices: list[str],
175
+ time_elapsed: float,
176
+ ) -> dict[str, Any]:
177
+ """Resolves the request and response objects for `openai.Completion`."""
178
+ results = [
179
+ trace_tree.Result(
180
+ inputs={"request": request_str},
181
+ outputs={"response": choice},
182
+ )
183
+ for choice in choices
184
+ ]
185
+ metrics = self._get_metrics_to_log(request, response, results, time_elapsed)
186
+ return self._convert_metrics_to_dict(metrics)
187
+
188
+ @staticmethod
189
+ def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics:
190
+ """Gets the usage stats from the response object."""
191
+ if response.get("usage"):
192
+ usage_stats = UsageMetrics(**response["usage"])
193
+ else:
194
+ usage_stats = UsageMetrics()
195
+ usage_stats.elapsed_time = time_elapsed
196
+ return usage_stats
197
+
198
+ def _get_metrics_to_log(
199
+ self,
200
+ request: dict[str, Any],
201
+ response: Response,
202
+ results: list[Any],
203
+ time_elapsed: float,
204
+ ) -> Metrics:
205
+ model = response.get("model") or request.get("model")
206
+ usage_metrics = self._get_usage_metrics(response, time_elapsed)
207
+
208
+ usage = []
209
+ for result in results:
210
+ row = {
211
+ "request": result.inputs["request"],
212
+ "response": result.outputs["response"],
213
+ "model": model,
214
+ "start_time": datetime.datetime.fromtimestamp(response["created"]),
215
+ "end_time": datetime.datetime.fromtimestamp(
216
+ response["created"] + time_elapsed
217
+ ),
218
+ "request_id": response.get("id", None),
219
+ "api_type": response.get("api_type", "openai"),
220
+ "session_id": wandb.run.id,
221
+ }
222
+ row.update(asdict(usage_metrics))
223
+ usage.append(row)
224
+ usage_table = wandb.Table(
225
+ columns=list(usage[0].keys()),
226
+ data=[(item.values()) for item in usage],
227
+ )
228
+
229
+ trace = self.results_to_trace_tree(request, response, results, time_elapsed)
230
+
231
+ metrics = Metrics(stats=usage_table, trace=trace, usage=usage_metrics)
232
+ return metrics
233
+
234
+ @staticmethod
235
+ def _convert_metrics_to_dict(metrics: Metrics) -> dict[str, Any]:
236
+ """Converts metrics to a dict."""
237
+ metrics_dict = {
238
+ "stats": metrics.stats,
239
+ "trace": metrics.trace,
240
+ }
241
+ usage_stats = {f"usage/{k}": v for k, v in asdict(metrics.usage).items()}
242
+ metrics_dict.update(usage_stats)
243
+ return metrics_dict
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .prodigy import upload_dataset
2
+
3
+ __all__ = ["upload_dataset"]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/prodigy/prodigy.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prodigy integration for W&B.
2
+
3
+ User can upload Prodigy annotated datasets directly
4
+ from the local database to W&B in Tables format.
5
+
6
+ Example usage:
7
+
8
+ ```python
9
+ import wandb
10
+ from wandb.integration.prodigy import upload_dataset
11
+
12
+ run = wandb.init(project="prodigy")
13
+ upload_dataset("name_of_dataset")
14
+ wandb.finish()
15
+ ```
16
+ """
17
+
18
+ import base64
19
+ import collections.abc
20
+ import io
21
+ import urllib
22
+ from copy import deepcopy
23
+
24
+ import pandas as pd
25
+ from PIL import Image
26
+
27
+ import wandb
28
+ from wandb import util
29
+ from wandb.plot.utils import test_missing
30
+ from wandb.sdk.lib import telemetry as wb_telemetry
31
+
32
+
33
+ def named_entity(docs):
34
+ """Create a named entity visualization.
35
+
36
+ Taken from https://github.com/wandb/wandb/blob/main/wandb/plots/named_entity.py.
37
+ """
38
+ spacy = util.get_module(
39
+ "spacy",
40
+ required="part_of_speech requires the spacy library, install with `pip install spacy`",
41
+ )
42
+
43
+ util.get_module(
44
+ "en_core_web_md",
45
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
46
+ )
47
+
48
+ # Test for required packages and missing & non-integer values in docs data
49
+ if test_missing(docs=docs):
50
+ html = spacy.displacy.render(
51
+ docs, style="ent", page=True, minify=True, jupyter=False
52
+ )
53
+ wandb_html = wandb.Html(html)
54
+ return wandb_html
55
+
56
+
57
+ def merge(dict1, dict2):
58
+ """Return a new dictionary by merging two dictionaries recursively."""
59
+ result = deepcopy(dict1)
60
+
61
+ for key, value in dict2.items():
62
+ if isinstance(value, collections.abc.Mapping):
63
+ result[key] = merge(result.get(key, {}), value)
64
+ else:
65
+ result[key] = deepcopy(dict2[key])
66
+
67
+ return result
68
+
69
+
70
+ def get_schema(list_data_dict, struct, array_dict_types):
71
+ """Get a schema of the dataset's structure and data types."""
72
+ # Get the structure of the JSON objects in the database
73
+ # This is similar to getting a JSON schema but with slightly different format
74
+ for _i, item in enumerate(list_data_dict):
75
+ # If the list contains dict objects
76
+ for k, v in item.items():
77
+ # Check if key already exists in template
78
+ if k not in struct:
79
+ if isinstance(v, list):
80
+ if len(v) > 0 and isinstance(v[0], list):
81
+ # nested list structure
82
+ struct[k] = type(v) # type list
83
+ elif len(v) > 0 and not (isinstance(v[0], (list, dict))):
84
+ # list of singular values
85
+ struct[k] = type(v) # type list
86
+ else:
87
+ # list of dicts
88
+ array_dict_types.append(
89
+ k
90
+ ) # keep track of keys that are type list[dict]
91
+ struct[k] = {}
92
+ struct[k] = get_schema(v, struct[k], array_dict_types)
93
+ elif isinstance(v, dict):
94
+ struct[k] = {}
95
+ struct[k] = get_schema([v], struct[k], array_dict_types)
96
+ else:
97
+ struct[k] = type(v)
98
+ else:
99
+ # Get the value of struct[k] which is the current template
100
+ # Find new keys and then merge the two templates together
101
+ cur_struct = struct[k]
102
+ if isinstance(v, list):
103
+ if len(v) > 0 and isinstance(v[0], list):
104
+ # nested list coordinate structure
105
+ # if the value in the item is currently None, then update
106
+ if v is not None:
107
+ struct[k] = type(v) # type list
108
+ elif len(v) > 0 and not (isinstance(v[0], (list, dict))):
109
+ # single list with values
110
+ # if the value in the item is currently None, then update
111
+ if v is not None:
112
+ struct[k] = type(v) # type list
113
+ else:
114
+ array_dict_types.append(
115
+ k
116
+ ) # keep track of keys that are type list[dict]
117
+ struct[k] = {}
118
+ struct[k] = get_schema(v, struct[k], array_dict_types)
119
+ # merge cur_struct and struct[k], remove duplicates
120
+ struct[k] = merge(struct[k], cur_struct)
121
+ elif isinstance(v, dict):
122
+ struct[k] = {}
123
+ struct[k] = get_schema([v], struct[k], array_dict_types)
124
+ # merge cur_struct and struct[k], remove duplicates
125
+ struct[k] = merge(struct[k], cur_struct)
126
+ else:
127
+ # if the value in the item is currently None, then update
128
+ if v is not None:
129
+ struct[k] = type(v)
130
+
131
+ return struct
132
+
133
+
134
+ def standardize(item, structure, array_dict_types):
135
+ """Standardize all rows/entries in dataset to fit the schema.
136
+
137
+ Will look for missing values and fill it in so all rows have
138
+ the same items and structure.
139
+ """
140
+ for k, v in structure.items():
141
+ if k not in item:
142
+ # If the structure/field does not exist
143
+ if isinstance(v, dict) and (k not in array_dict_types):
144
+ # If key k is of type dict, and not not a type list[dict]
145
+ item[k] = {}
146
+ standardize(item[k], v, array_dict_types)
147
+ elif isinstance(v, dict) and (k in array_dict_types):
148
+ # If key k is of type dict, and is actually of type list[dict],
149
+ # just treat as a list and set to None by default
150
+ item[k] = None
151
+ else:
152
+ # Assign a default type
153
+ item[k] = v()
154
+ else:
155
+ # If the structure/field already exists and is a list or dict
156
+ if isinstance(item[k], list):
157
+ # ignore if item is a nested list structure or list of non-dicts
158
+ condition = (
159
+ not (len(item[k]) > 0 and isinstance(item[k][0], list))
160
+ ) and (
161
+ not (
162
+ len(item[k]) > 0 and not (isinstance(item[k][0], (list, dict)))
163
+ )
164
+ )
165
+ if condition:
166
+ for sub_item in item[k]:
167
+ standardize(sub_item, v, array_dict_types)
168
+ elif isinstance(item[k], dict):
169
+ standardize(item[k], v, array_dict_types)
170
+
171
+
172
+ def create_table(data):
173
+ """Create a W&B Table.
174
+
175
+ - Create/decode images from URL/Base64
176
+ - Uses spacy to translate NER span data to visualizations.
177
+ """
178
+ # create table object from columns
179
+ table_df = pd.DataFrame(data)
180
+ columns = list(table_df.columns)
181
+ if ("spans" in table_df.columns) and ("text" in table_df.columns):
182
+ columns.append("spans_visual")
183
+ if "image" in columns:
184
+ columns.append("image_visual")
185
+ main_table = wandb.Table(columns=columns)
186
+
187
+ # Convert to dictionary format to maintain order during processing
188
+ matrix = table_df.to_dict(orient="records")
189
+
190
+ # Import en_core_web_md if exists
191
+ en_core_web_md = util.get_module(
192
+ "en_core_web_md",
193
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
194
+ )
195
+ nlp = en_core_web_md.load(disable=["ner"])
196
+
197
+ # Go through each individual row
198
+ for _i, document in enumerate(matrix):
199
+ # Text NER span visualizations
200
+ if ("spans_visual" in columns) and ("text" in columns):
201
+ # Add visuals for spans
202
+ document["spans_visual"] = None
203
+ doc = nlp(document["text"])
204
+ ents = []
205
+ if ("spans" in document) and (document["spans"] is not None):
206
+ for span in document["spans"]:
207
+ if ("start" in span) and ("end" in span) and ("label" in span):
208
+ charspan = doc.char_span(
209
+ span["start"], span["end"], span["label"]
210
+ )
211
+ ents.append(charspan)
212
+ doc.ents = ents
213
+ document["spans_visual"] = named_entity(docs=doc)
214
+
215
+ # Convert image link to wandb Image
216
+ if "image" in columns:
217
+ # Turn into wandb image
218
+ document["image_visual"] = None
219
+ if ("image" in document) and (document["image"] is not None):
220
+ isurl = urllib.parse.urlparse(document["image"]).scheme in (
221
+ "http",
222
+ "https",
223
+ )
224
+ isbase64 = ("data:" in document["image"]) and (
225
+ ";base64" in document["image"]
226
+ )
227
+ if isurl:
228
+ # is url
229
+ try:
230
+ im = Image.open(urllib.request.urlopen(document["image"]))
231
+ document["image_visual"] = wandb.Image(im)
232
+ except urllib.error.URLError:
233
+ wandb.termwarn(f"Image URL {document['image']} is invalid.")
234
+ document["image_visual"] = None
235
+ elif isbase64:
236
+ # is base64 uri
237
+ imgb64 = document["image"].split("base64,")[1]
238
+ try:
239
+ msg = base64.b64decode(imgb64)
240
+ buf = io.BytesIO(msg)
241
+ im = Image.open(buf)
242
+ document["image_visual"] = wandb.Image(im)
243
+ except base64.binascii.Error:
244
+ wandb.termwarn(f"Base64 string {document['image']} is invalid.")
245
+ document["image_visual"] = None
246
+ else:
247
+ # is data path
248
+ document["image_visual"] = wandb.Image(document["image"])
249
+
250
+ # Create row and append to table
251
+ values_list = list(document.values())
252
+ main_table.add_data(*values_list)
253
+ return main_table
254
+
255
+
256
+ def upload_dataset(dataset_name):
257
+ """Upload dataset from local database to Weights & Biases.
258
+
259
+ Args:
260
+ dataset_name: The name of the dataset in the Prodigy database.
261
+ """
262
+ # Check if wandb.init has been called
263
+ if wandb.run is None:
264
+ raise ValueError("You must call wandb.init() before upload_dataset()")
265
+
266
+ with wb_telemetry.context(run=wandb.run) as tel:
267
+ tel.feature.prodigy = True
268
+
269
+ prodigy_db = util.get_module(
270
+ "prodigy.components.db",
271
+ required="`prodigy` library is required but not installed. Please see https://prodi.gy/docs/install",
272
+ )
273
+ # Retrieve and upload prodigy dataset
274
+ database = prodigy_db.connect()
275
+ data = database.get_dataset(dataset_name)
276
+
277
+ array_dict_types = []
278
+ schema = get_schema(data, {}, array_dict_types)
279
+
280
+ for i, _d in enumerate(data):
281
+ standardize(data[i], schema, array_dict_types)
282
+ table = create_table(data)
283
+ wandb.log({dataset_name: table})
284
+ wandb.termlog(f"Prodigy dataset `{dataset_name}` uploaded.")
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sacred/__init__.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import numpy
4
+ from sacred.dependencies import get_digest
5
+ from sacred.observers import RunObserver
6
+
7
+ import wandb
8
+
9
+
10
+ class WandbObserver(RunObserver):
11
+ """Log sacred experiment data to W&B.
12
+
13
+ Args:
14
+ Accepts all the arguments accepted by wandb.init().
15
+
16
+ name — A display name for this run, which shows up in the UI and is editable, doesn't have to be unique
17
+ notes — A multiline string description associated with the run
18
+ config — a dictionary-like object to set as initial config
19
+ project — the name of the project to which this run will belong
20
+ tags — a list of strings to associate with this run as tags
21
+ dir — the path to a directory where artifacts will be written (default: ./wandb)
22
+ entity — the team posting this run (default: your username or your default team)
23
+ job_type — the type of job you are logging, e.g. eval, worker, ps (default: training)
24
+ save_code — save the main python or notebook file to wandb to enable diffing (default: editable from your settings page)
25
+ group — a string by which to group other runs; see Grouping
26
+ reinit — Shorthand for the reinit setting that defines what to do when `wandb.init()` is called while a run is active. See the setting's documentation.
27
+ id — A unique ID for this run primarily used for Resuming. It must be globally unique, and if you delete a run you can't reuse the ID. Use the name field for a descriptive, useful name for the run. The ID cannot contain special characters.
28
+ resume — if set to True, the run auto resumes; can also be a unique string for manual resuming; see Resuming (default: False)
29
+ anonymous — can be "allow", "never", or "must". This enables or explicitly disables anonymous logging. (default: never)
30
+ force — whether to force a user to be logged into wandb when running a script (default: False)
31
+ magic — (bool, dict, or str, optional): magic configuration as bool, dict, json string, yaml filename. If set to True will attempt to auto-instrument your script. (default: None)
32
+ sync_tensorboard — A boolean indicating whether or not copy all TensorBoard logs wandb; see Tensorboard (default: False)
33
+ monitor_gym — A boolean indicating whether or not to log videos generated by OpenAI Gym; see Ray Tune (default: False)
34
+ allow_val_change — whether to allow wandb.config values to change, by default we throw an exception if config values are overwritten. (default: False)
35
+
36
+ Examples:
37
+ Create sacred experiment::
38
+ from wandb.sacred import WandbObserver
39
+ ex.observers.append(WandbObserver(project='sacred_test',
40
+ name='test1'))
41
+ @ex.config
42
+ def cfg():
43
+ C = 1.0
44
+ gamma = 0.7
45
+ @ex.automain
46
+ def run(C, gamma, _run):
47
+ iris = datasets.load_iris()
48
+ per = permutation(iris.target.size)
49
+ iris.data = iris.data[per]
50
+ iris.target = iris.target[per]
51
+ clf = svm.SVC(C, 'rbf', gamma=gamma)
52
+ clf.fit(iris.data[:90],
53
+ iris.target[:90])
54
+ return clf.score(iris.data[90:],
55
+ iris.target[90:])
56
+ """
57
+
58
+ def __init__(self, **kwargs):
59
+ self.run = wandb.init(**kwargs)
60
+ self.resources = {}
61
+
62
+ def started_event(
63
+ self, ex_info, command, host_info, start_time, config, meta_info, _id
64
+ ):
65
+ # TODO: add the source code file
66
+ # TODO: add dependencies and metadata.
67
+ self.__update_config(config)
68
+
69
+ def completed_event(self, stop_time, result):
70
+ if result:
71
+ if not isinstance(result, tuple):
72
+ result = (
73
+ result,
74
+ ) # transform single result to tuple so that both single & multiple results use same code
75
+
76
+ for i, r in enumerate(result):
77
+ if isinstance(r, (float, int)):
78
+ wandb.log({f"result_{i}": float(r)})
79
+ elif isinstance(r, dict):
80
+ wandb.log(r)
81
+ elif isinstance(r, object):
82
+ artifact = wandb.Artifact(f"result_{i}.pkl", type="result")
83
+ artifact.add_file(r)
84
+ self.run.log_artifact(artifact)
85
+ elif isinstance(r, numpy.ndarray):
86
+ wandb.log({f"result_{i}": wandb.Image(r)})
87
+ else:
88
+ warnings.warn(
89
+ f"logging results does not support type '{type(r)}' results. Ignoring this result",
90
+ stacklevel=2,
91
+ )
92
+
93
+ def artifact_event(self, name, filename, metadata=None, content_type=None):
94
+ if content_type is None:
95
+ content_type = "file"
96
+ artifact = wandb.Artifact(name, type=content_type)
97
+ artifact.add_file(filename)
98
+ self.run.log_artifact(artifact)
99
+
100
+ def resource_event(self, filename):
101
+ """TODO: Maintain resources list."""
102
+ if filename not in self.resources:
103
+ md5 = get_digest(filename)
104
+ self.resources[filename] = md5
105
+
106
+ def log_metrics(self, metrics_by_name, info):
107
+ for metric_name, metric_ptr in metrics_by_name.items():
108
+ for _step, value in zip(metric_ptr["steps"], metric_ptr["values"]):
109
+ if isinstance(value, numpy.ndarray):
110
+ wandb.log({metric_name: wandb.Image(value)})
111
+ else:
112
+ wandb.log({metric_name: value})
113
+
114
+ def __update_config(self, config):
115
+ for k, v in config.items():
116
+ self.run.config[k] = v
117
+ self.run.config["resources"] = []
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """wandb integration sagemaker module."""
2
+
3
+ from .auth import sagemaker_auth
4
+ from .config import is_using_sagemaker, parse_sm_config
5
+ from .resources import parse_sm_secrets, set_global_settings, set_run_id
6
+
7
+ __all__ = [
8
+ "sagemaker_auth",
9
+ "is_using_sagemaker",
10
+ "parse_sm_config",
11
+ "parse_sm_secrets",
12
+ "set_global_settings",
13
+ "set_run_id",
14
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/auth.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ from wandb import env
7
+ from wandb.sdk import wandb_setup
8
+ from wandb.sdk.lib import wbauth
9
+
10
+
11
+ def sagemaker_auth(
12
+ overrides: dict[str, Any] | None = None,
13
+ path: str = ".",
14
+ api_key: str | None = None,
15
+ ) -> None:
16
+ """Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
17
+
18
+ Args:
19
+ overrides: Additional environment variables to write to secrets.env
20
+ path: The path to write the secrets file.
21
+ """
22
+ overrides = overrides or dict()
23
+
24
+ api_key = (
25
+ overrides.get(env.API_KEY, None)
26
+ or api_key
27
+ or wandb_setup.singleton().settings.api_key
28
+ or wbauth.read_netrc_auth(host=wandb_setup.singleton().settings.base_url)
29
+ )
30
+
31
+ if api_key is None:
32
+ raise ValueError(
33
+ "Can't find W&B API key, set the WANDB_API_KEY env variable"
34
+ + " or run `wandb login`"
35
+ )
36
+
37
+ overrides[env.API_KEY] = api_key
38
+ with open(os.path.join(path, "secrets.env"), "w") as file:
39
+ for k, v in overrides.items():
40
+ file.write(f"{k}={v}\n")
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/config.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import warnings
7
+ from typing import Any
8
+
9
+ from . import files as sm_files
10
+
11
+
12
+ def is_using_sagemaker() -> bool:
13
+ """Returns whether we're in a SageMaker environment."""
14
+ return (
15
+ os.path.exists(sm_files.SM_PARAM_CONFIG) #
16
+ or "SM_TRAINING_ENV" in os.environ
17
+ )
18
+
19
+
20
+ def parse_sm_config() -> dict[str, Any]:
21
+ """Parses SageMaker configuration.
22
+
23
+ Returns:
24
+ A dictionary of SageMaker config keys/values
25
+ or an empty dict if not found.
26
+ SM_TRAINING_ENV is a json string of the
27
+ training environment variables set by SageMaker
28
+ and is only available when running in SageMaker,
29
+ but not in local mode.
30
+ SM_TRAINING_ENV is set by the SageMaker container and
31
+ contains arguments such as hyperparameters
32
+ and arguments passed to the training job.
33
+ """
34
+ conf = {}
35
+
36
+ if os.path.exists(sm_files.SM_PARAM_CONFIG):
37
+ conf["sagemaker_training_job_name"] = os.getenv("TRAINING_JOB_NAME")
38
+
39
+ # Hyperparameter searches quote configs...
40
+ with open(sm_files.SM_PARAM_CONFIG) as fid:
41
+ for key, val in json.load(fid).items():
42
+ cast = val.strip('"')
43
+ if re.match(r"^-?[\d]+$", cast):
44
+ cast = int(cast)
45
+ elif re.match(r"^-?[.\d]+$", cast):
46
+ cast = float(cast)
47
+ conf[key] = cast
48
+
49
+ if env := os.environ.get("SM_TRAINING_ENV"):
50
+ try:
51
+ conf.update(json.loads(env))
52
+ except json.JSONDecodeError:
53
+ warnings.warn(
54
+ "Failed to parse SM_TRAINING_ENV not valid JSON string",
55
+ stacklevel=2,
56
+ )
57
+
58
+ return conf
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/files.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ SM_PARAM_CONFIG = "/opt/ml/input/config/hyperparameters.json"
2
+ SM_SECRETS = "secrets.env"
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sagemaker/resources.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import secrets
5
+ import socket
6
+ import string
7
+
8
+ import wandb
9
+
10
+ from . import config
11
+ from . import files as sm_files
12
+
13
+
14
+ def set_run_id(run_settings: wandb.Settings) -> bool:
15
+ """Set a run ID and group when using SageMaker.
16
+
17
+ Returns whether the ID and group were updated.
18
+ """
19
+ # Added in https://github.com/wandb/wandb/pull/3290.
20
+ #
21
+ # Prevents SageMaker from overriding the run ID configured
22
+ # in environment variables. Note, however, that it will still
23
+ # override a run ID passed explicitly to `wandb.init()`.
24
+ if os.getenv("WANDB_RUN_ID"):
25
+ return False
26
+
27
+ run_group = os.getenv("TRAINING_JOB_NAME")
28
+ if not run_group:
29
+ return False
30
+
31
+ alphanumeric = string.ascii_lowercase + string.digits
32
+ random = "".join(secrets.choice(alphanumeric) for _ in range(6))
33
+
34
+ host = os.getenv("CURRENT_HOST", socket.gethostname())
35
+
36
+ run_settings.run_id = f"{run_group}-{random}-{host}"
37
+ run_settings.run_group = run_group
38
+ return True
39
+
40
+
41
+ def set_global_settings(settings: wandb.Settings) -> None:
42
+ """Set global W&B settings based on the SageMaker environment."""
43
+ if env := parse_sm_secrets():
44
+ settings.update_from_env_vars(env)
45
+
46
+ # The SageMaker config may contain an API key, in which case it
47
+ # takes precedence over the value in the secrets. It's unclear
48
+ # whether this is by design, or by accident; we keep it for
49
+ # backward compatibility for now.
50
+ sm_config = config.parse_sm_config()
51
+ if api_key := sm_config.get("wandb_api_key"):
52
+ settings.api_key = api_key
53
+
54
+
55
+ def parse_sm_secrets() -> dict[str, str]:
56
+ """We read our api_key from secrets.env in SageMaker."""
57
+ env_dict = dict()
58
+ # Set secret variables
59
+ if os.path.exists(sm_files.SM_SECRETS):
60
+ for line in open(sm_files.SM_SECRETS):
61
+ key, val = line.strip().split("=", 1)
62
+ env_dict[key] = val
63
+ return env_dict
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sb3/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .sb3 import WandbCallback
2
+
3
+ __all__ = ["WandbCallback"]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sb3/sb3.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """W&B callback for sb3.
2
+
3
+ Really simple callback to get logging for each tree
4
+
5
+ Example usage:
6
+
7
+ ```python
8
+ import gym
9
+ from stable_baselines3 import PPO
10
+ from stable_baselines3.common.monitor import Monitor
11
+ from stable_baselines3.common.vec_env import DummyVecEnv, VecVideoRecorder
12
+ import wandb
13
+ from wandb.integration.sb3 import WandbCallback
14
+
15
+
16
+ config = {
17
+ "policy_type": "MlpPolicy",
18
+ "total_timesteps": 25000,
19
+ "env_name": "CartPole-v1",
20
+ }
21
+ run = wandb.init(
22
+ project="sb3",
23
+ config=config,
24
+ sync_tensorboard=True, # auto-upload sb3's tensorboard metrics
25
+ monitor_gym=True, # auto-upload the videos of agents playing the game
26
+ save_code=True, # optional
27
+ )
28
+
29
+
30
+ def make_env():
31
+ env = gym.make(config["env_name"])
32
+ env = Monitor(env) # record stats such as returns
33
+ return env
34
+
35
+
36
+ env = DummyVecEnv([make_env])
37
+ env = VecVideoRecorder(
38
+ env, "videos", record_video_trigger=lambda x: x % 2000 == 0, video_length=200
39
+ )
40
+ model = PPO(config["policy_type"], env, verbose=1, tensorboard_log=f"runs")
41
+ model.learn(
42
+ total_timesteps=config["total_timesteps"],
43
+ callback=WandbCallback(
44
+ model_save_path=f"models/{run.id}",
45
+ gradient_save_freq=100,
46
+ log="all",
47
+ ),
48
+ )
49
+ ```
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import logging
55
+ import os
56
+ from typing import Literal
57
+
58
+ from stable_baselines3.common.callbacks import BaseCallback # type: ignore
59
+
60
+ import wandb
61
+ from wandb.sdk.lib import telemetry as wb_telemetry
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ class WandbCallback(BaseCallback):
67
+ """Callback for logging experiments to Weights and Biases.
68
+
69
+ Log SB3 experiments to Weights and Biases
70
+ - Added model tracking and uploading
71
+ - Added complete hyperparameters recording
72
+ - Added gradient logging
73
+ - Note that `wandb.init(...)` must be called before the WandbCallback can be used.
74
+
75
+ Args:
76
+ verbose: The verbosity of sb3 output
77
+ model_save_path: Path to the folder where the model will be saved, The default value is `None` so the model is not logged
78
+ model_save_freq: Frequency to save the model
79
+ gradient_save_freq: Frequency to log gradient. The default value is 0 so the gradients are not logged
80
+ log: What to log. One of "gradients", "parameters", or "all".
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ verbose: int = 0,
86
+ model_save_path: str | None = None,
87
+ model_save_freq: int = 0,
88
+ gradient_save_freq: int = 0,
89
+ log: Literal["gradients", "parameters", "all"] | None = "all",
90
+ ) -> None:
91
+ super().__init__(verbose)
92
+ if wandb.run is None:
93
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
94
+ with wb_telemetry.context() as tel:
95
+ tel.feature.sb3 = True
96
+ self.model_save_freq = model_save_freq
97
+ self.model_save_path = model_save_path
98
+ self.gradient_save_freq = gradient_save_freq
99
+ if log not in ["gradients", "parameters", "all", None]:
100
+ wandb.termwarn(
101
+ "`log` must be one of `None`, 'gradients', 'parameters', or 'all', "
102
+ "falling back to 'all'"
103
+ )
104
+ log = "all"
105
+ self.log = log
106
+ # Create folder if needed
107
+ if self.model_save_path is not None:
108
+ os.makedirs(self.model_save_path, exist_ok=True)
109
+ self.path = os.path.join(self.model_save_path, "model.zip")
110
+ else:
111
+ assert self.model_save_freq == 0, (
112
+ "to use the `model_save_freq` you have to set the `model_save_path` parameter"
113
+ )
114
+
115
+ def _init_callback(self) -> None:
116
+ d = {}
117
+ if "algo" not in d:
118
+ d["algo"] = type(self.model).__name__
119
+ for key in self.model.__dict__:
120
+ if key in wandb.config:
121
+ continue
122
+ if type(self.model.__dict__[key]) in [float, int, str]:
123
+ d[key] = self.model.__dict__[key]
124
+ else:
125
+ d[key] = str(self.model.__dict__[key])
126
+ if self.gradient_save_freq > 0:
127
+ wandb.watch(
128
+ self.model.policy,
129
+ log_freq=self.gradient_save_freq,
130
+ log=self.log,
131
+ )
132
+ wandb.config.setdefaults(d)
133
+
134
+ def _on_step(self) -> bool:
135
+ if (
136
+ self.model_save_freq > 0
137
+ and self.model_save_path is not None
138
+ and self.n_calls % self.model_save_freq == 0
139
+ ):
140
+ self.save_model()
141
+ return True
142
+
143
+ def _on_training_end(self) -> None:
144
+ if self.model_save_path is not None:
145
+ self.save_model()
146
+
147
+ def save_model(self) -> None:
148
+ self.model.save(self.path)
149
+ wandb.save(self.path, base_path=self.model_save_path)
150
+ if self.verbose > 1:
151
+ logger.info(f"Saving model checkpoint to {self.path}")
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Create informative charts for scikit-learn models and log them to W&B."""
2
+
3
+ from .plot import (
4
+ plot_calibration_curve,
5
+ plot_class_proportions,
6
+ plot_classifier,
7
+ plot_clusterer,
8
+ plot_confusion_matrix,
9
+ plot_elbow_curve,
10
+ plot_feature_importances,
11
+ plot_learning_curve,
12
+ plot_outlier_candidates,
13
+ plot_precision_recall,
14
+ plot_regressor,
15
+ plot_residuals,
16
+ plot_roc,
17
+ plot_silhouette,
18
+ plot_summary_metrics,
19
+ )
20
+
21
+ __all__ = [
22
+ "plot_classifier",
23
+ "plot_clusterer",
24
+ "plot_regressor",
25
+ "plot_summary_metrics",
26
+ "plot_learning_curve",
27
+ "plot_feature_importances",
28
+ "plot_class_proportions",
29
+ "plot_calibration_curve",
30
+ "plot_roc",
31
+ "plot_precision_recall",
32
+ "plot_confusion_matrix",
33
+ "plot_elbow_curve",
34
+ "plot_silhouette",
35
+ "plot_residuals",
36
+ "plot_outlier_candidates",
37
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calculates and formats metrics and charts for introspecting sklearn models.
2
+
3
+ The functions in these modules are designed to be called by functions from the
4
+ plot submodule that have been exported into the namespace of the wandb.sklearn
5
+ submodule, rather than being called directly.
6
+ """
7
+
8
+ from .calibration_curves import calibration_curves
9
+ from .class_proportions import class_proportions
10
+ from .confusion_matrix import confusion_matrix
11
+ from .decision_boundaries import decision_boundaries
12
+ from .elbow_curve import elbow_curve
13
+ from .feature_importances import feature_importances
14
+ from .learning_curve import learning_curve
15
+ from .outlier_candidates import outlier_candidates
16
+ from .residuals import residuals
17
+ from .silhouette import silhouette
18
+ from .summary_metrics import summary_metrics
19
+
20
+ __all__ = [
21
+ "calibration_curves",
22
+ "class_proportions",
23
+ "confusion_matrix",
24
+ "decision_boundaries",
25
+ "elbow_curve",
26
+ "feature_importances",
27
+ "learning_curve",
28
+ "outlier_candidates",
29
+ "residuals",
30
+ "silhouette",
31
+ "summary_metrics",
32
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import simplefilter
2
+
3
+ import numpy as np
4
+ import sklearn
5
+ from sklearn import model_selection, naive_bayes
6
+ from sklearn.calibration import CalibratedClassifierCV
7
+ from sklearn.linear_model import LogisticRegression
8
+
9
+ import wandb
10
+ from wandb.integration.sklearn import utils
11
+
12
+ # ignore all future warnings
13
+ simplefilter(action="ignore", category=FutureWarning)
14
+
15
+
16
+ def calibration_curves(clf, X, y, clf_name): # noqa: N803
17
+ # ComplementNB (introduced in 0.20.0) requires non-negative features
18
+ if int(sklearn.__version__.split(".")[1]) >= 20 and isinstance(
19
+ clf, naive_bayes.ComplementNB
20
+ ):
21
+ X = X - X.min() # noqa:N806
22
+
23
+ # Calibrated with isotonic calibration
24
+ isotonic = CalibratedClassifierCV(clf, cv=2, method="isotonic")
25
+
26
+ # Calibrated with sigmoid calibration
27
+ sigmoid = CalibratedClassifierCV(clf, cv=2, method="sigmoid")
28
+
29
+ # Logistic regression with no calibration as baseline
30
+ lr = LogisticRegression(C=1.0)
31
+
32
+ model_column = [] # color
33
+ frac_positives_column = [] # y axis
34
+ mean_pred_value_column = [] # x axis
35
+ hist_column = [] # barchart y
36
+ edge_column = [] # barchart x
37
+
38
+ # Add curve for perfectly calibrated model
39
+ # format: model, fraction_of_positives, mean_predicted_value
40
+ model_column.append("Perfectly calibrated")
41
+ frac_positives_column.append(0)
42
+ mean_pred_value_column.append(0)
43
+ hist_column.append(0)
44
+ edge_column.append(0)
45
+ model_column.append("Perfectly calibrated")
46
+ hist_column.append(0)
47
+ edge_column.append(0)
48
+ frac_positives_column.append(1)
49
+ mean_pred_value_column.append(1)
50
+
51
+ x_train, x_test, y_train, y_test = model_selection.train_test_split(
52
+ X, y, test_size=0.9, random_state=42
53
+ )
54
+
55
+ # Add curve for LogisticRegression baseline and other models
56
+
57
+ models = [lr, isotonic, sigmoid]
58
+ names = ["Logistic", f"{clf_name} Isotonic", f"{clf_name} Sigmoid"]
59
+
60
+ for model, name in zip(models, names):
61
+ model.fit(x_train, y_train)
62
+ if hasattr(model, "predict_proba"):
63
+ prob_pos = model.predict_proba(x_test)[:, 1]
64
+ else: # use decision function
65
+ prob_pos = model.decision_function(x_test)
66
+ prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
67
+
68
+ hist, edges = np.histogram(prob_pos, bins=10, density=False)
69
+ frac_positives, mean_pred_value = sklearn.calibration.calibration_curve(
70
+ y_test, prob_pos, n_bins=10
71
+ )
72
+
73
+ # format: model, fraction_of_positives, mean_predicted_value
74
+ num_entries = len(frac_positives)
75
+ for i in range(num_entries):
76
+ hist_column.append(hist[i])
77
+ edge_column.append(edges[i])
78
+ model_column.append(name)
79
+ frac_positives_column.append(utils.round_3(frac_positives[i]))
80
+ mean_pred_value_column.append(utils.round_3(mean_pred_value[i]))
81
+ if utils.check_against_limit(
82
+ i,
83
+ "calibration_curve",
84
+ utils.chart_limit - 2,
85
+ ):
86
+ break
87
+
88
+ table = make_table(
89
+ model_column,
90
+ frac_positives_column,
91
+ mean_pred_value_column,
92
+ hist_column,
93
+ edge_column,
94
+ )
95
+ chart = wandb.visualize("wandb/calibration/v1", table)
96
+
97
+ return chart
98
+
99
+
100
+ def make_table(
101
+ model_column,
102
+ frac_positives_column,
103
+ mean_pred_value_column,
104
+ hist_column,
105
+ edge_column,
106
+ ):
107
+ columns = [
108
+ "model",
109
+ "fraction_of_positives",
110
+ "mean_predicted_value",
111
+ "hist_dict",
112
+ "edge_dict",
113
+ ]
114
+
115
+ data = list(
116
+ zip(
117
+ model_column,
118
+ frac_positives_column,
119
+ mean_pred_value_column,
120
+ hist_column,
121
+ edge_column,
122
+ )
123
+ )
124
+
125
+ return wandb.Table(columns=columns, data=data)
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import simplefilter
2
+
3
+ import numpy as np
4
+ from sklearn.utils.multiclass import unique_labels
5
+
6
+ import wandb
7
+ from wandb.integration.sklearn import utils
8
+
9
+ # ignore all future warnings
10
+ simplefilter(action="ignore", category=FutureWarning)
11
+
12
+
13
+ def class_proportions(y_train, y_test, labels):
14
+ # Get the unique values from the dataset
15
+ targets = (y_train,) if y_test is None else (y_train, y_test)
16
+ class_ids = np.array(unique_labels(*targets))
17
+
18
+ # Compute the class counts
19
+ counts_train = np.array([(y_train == c).sum() for c in class_ids])
20
+ counts_test = np.array([(y_test == c).sum() for c in class_ids])
21
+
22
+ class_column, dataset_column, count_column = make_columns(
23
+ class_ids, counts_train, counts_test
24
+ )
25
+
26
+ if labels is not None and isinstance(class_column[0], (int, np.integer)):
27
+ class_column = get_named_labels(labels, class_column)
28
+
29
+ table = make_table(class_column, dataset_column, count_column)
30
+ chart = wandb.visualize("wandb/class_proportions/v1", table)
31
+
32
+ return chart
33
+
34
+
35
+ def make_table(class_column, dataset_column, count_column):
36
+ columns = ["class", "dataset", "count"]
37
+ data = list(zip(class_column, dataset_column, count_column))
38
+
39
+ return wandb.Table(data=data, columns=columns)
40
+
41
+
42
+ def make_columns(class_ids, counts_train, counts_test):
43
+ class_column, dataset_column, count_column = [], [], []
44
+
45
+ for i in range(len(class_ids)):
46
+ # add class counts from training set
47
+ class_column.append(class_ids[i])
48
+ dataset_column.append("train")
49
+ count_column.append(counts_train[i])
50
+ # add class counts from test set
51
+ class_column.append(class_ids[i])
52
+ dataset_column.append("test")
53
+ count_column.append(counts_test[i])
54
+
55
+ if utils.check_against_limit(
56
+ i,
57
+ "class_proportions",
58
+ utils.chart_limit,
59
+ ):
60
+ break
61
+
62
+ return class_column, dataset_column, count_column
63
+
64
+
65
+ def get_named_labels(labels, numeric_labels):
66
+ return np.array([labels[num_label] for num_label in numeric_labels])
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from warnings import simplefilter
3
+
4
+ import numpy as np
5
+ from sklearn import metrics
6
+ from sklearn.utils.multiclass import unique_labels
7
+
8
+ import wandb
9
+
10
+ from .. import utils
11
+
12
+ # ignore all future warnings
13
+ simplefilter(action="ignore", category=FutureWarning)
14
+
15
+
16
+ def validate_labels(*args, **kwargs): # FIXME
17
+ raise AssertionError()
18
+
19
+
20
+ def confusion_matrix(
21
+ y_true=None,
22
+ y_pred=None,
23
+ labels=None,
24
+ true_labels=None,
25
+ pred_labels=None,
26
+ normalize=False,
27
+ ):
28
+ """Compute the confusion matrix to evaluate the performance of a classification.
29
+
30
+ Called by plot_confusion_matrix to visualize roc curves. Please use the function
31
+ plot_confusion_matrix() if you wish to visualize your confusion matrix.
32
+ """
33
+ cm = metrics.confusion_matrix(y_true, y_pred)
34
+
35
+ if labels is None:
36
+ classes = unique_labels(y_true, y_pred)
37
+ else:
38
+ classes = np.asarray(labels)
39
+
40
+ if normalize:
41
+ cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis]
42
+ cm = np.around(cm, decimals=2)
43
+ cm[np.isnan(cm)] = 0.0
44
+
45
+ if true_labels is None:
46
+ true_classes = classes
47
+ else:
48
+ validate_labels(classes, true_labels, "true_labels")
49
+
50
+ true_label_indexes = np.in1d(classes, true_labels)
51
+
52
+ true_classes = classes[true_label_indexes]
53
+ cm = cm[true_label_indexes]
54
+
55
+ if pred_labels is None:
56
+ pred_classes = classes
57
+ else:
58
+ validate_labels(classes, pred_labels, "pred_labels")
59
+
60
+ pred_label_indexes = np.in1d(classes, pred_labels)
61
+
62
+ pred_classes = classes[pred_label_indexes]
63
+ cm = cm[:, pred_label_indexes]
64
+
65
+ table = make_table(cm, pred_classes, true_classes, labels)
66
+ chart = wandb.visualize("wandb/confusion_matrix/v1", table)
67
+
68
+ return chart
69
+
70
+
71
+ def make_table(cm, pred_classes, true_classes, labels):
72
+ data, count = [], 0
73
+ for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
74
+ if labels is not None and (
75
+ isinstance(pred_classes[i], int) or isinstance(pred_classes[0], np.integer)
76
+ ):
77
+ pred = labels[pred_classes[i]]
78
+ true = labels[true_classes[j]]
79
+ else:
80
+ pred = pred_classes[i]
81
+ true = true_classes[j]
82
+ data.append([pred, true, cm[i, j]])
83
+ count += 1
84
+ if utils.check_against_limit(
85
+ count,
86
+ "confusion_matrix",
87
+ utils.chart_limit,
88
+ ):
89
+ break
90
+
91
+ table = wandb.Table(columns=["Predicted", "Actual", "Count"], data=data)
92
+
93
+ return table
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import simplefilter
2
+
3
+ import wandb
4
+
5
+ # ignore all future warnings
6
+ simplefilter(action="ignore", category=FutureWarning)
7
+
8
+
9
+ def decision_boundaries(
10
+ decision_boundary_x,
11
+ decision_boundary_y,
12
+ decision_boundary_color,
13
+ train_x,
14
+ train_y,
15
+ train_color,
16
+ test_x,
17
+ test_y,
18
+ test_color,
19
+ ):
20
+ x_dict, y_dict, color_dict = [], [], []
21
+ for i in range(min(len(decision_boundary_x), 100)):
22
+ x_dict.append(decision_boundary_x[i])
23
+ y_dict.append(decision_boundary_y[i])
24
+ color_dict.append(decision_boundary_color)
25
+ for i in range(300):
26
+ x_dict.append(test_x[i])
27
+ y_dict.append(test_y[i])
28
+ color_dict.append(test_color[i])
29
+ for i in range(min(len(train_x), 600)):
30
+ x_dict.append(train_x[i])
31
+ y_dict.append(train_y[i])
32
+ color_dict.append(train_color[i])
33
+
34
+ return wandb.visualize(
35
+ "wandb/decision_boundaries/v1",
36
+ wandb.Table(
37
+ columns=["x", "y", "color"],
38
+ data=[[x_dict[i], y_dict[i], color_dict[i]] for i in range(len(x_dict))],
39
+ ),
40
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from warnings import simplefilter
3
+
4
+ import numpy as np
5
+ from joblib import Parallel, delayed
6
+ from sklearn.base import clone
7
+
8
+ import wandb
9
+
10
+ # ignore all future warnings
11
+ simplefilter(action="ignore", category=FutureWarning)
12
+
13
+
14
+ def elbow_curve(clusterer, X, cluster_ranges, n_jobs, show_cluster_time): # noqa: N803
15
+ if cluster_ranges is None:
16
+ cluster_ranges = range(1, 10, 2)
17
+ else:
18
+ cluster_ranges = sorted(cluster_ranges)
19
+
20
+ clfs, times = _compute_results_parallel(n_jobs, clusterer, X, cluster_ranges)
21
+
22
+ clfs = np.absolute(clfs)
23
+
24
+ table = make_table(cluster_ranges, clfs, times)
25
+ chart = wandb.visualize("wandb/elbow/v1", table)
26
+
27
+ return chart
28
+
29
+
30
+ def make_table(cluster_ranges, clfs, times):
31
+ columns = ["cluster_ranges", "errors", "clustering_time"]
32
+
33
+ data = list(zip(cluster_ranges, clfs, times))
34
+
35
+ table = wandb.Table(columns=columns, data=data)
36
+
37
+ return table
38
+
39
+
40
+ def _compute_results_parallel(n_jobs, clusterer, x, cluster_ranges):
41
+ parallel_runner = Parallel(n_jobs=n_jobs)
42
+ _cluster_scorer = delayed(_clone_and_score_clusterer)
43
+ results = parallel_runner(_cluster_scorer(clusterer, x, i) for i in cluster_ranges)
44
+
45
+ clfs, times = zip(*results)
46
+
47
+ return clfs, times
48
+
49
+
50
+ def _clone_and_score_clusterer(clusterer, x, n_clusters):
51
+ start = time.time()
52
+ clusterer = clone(clusterer)
53
+ clusterer.n_clusters = n_clusters
54
+
55
+ return clusterer.fit(x).score(x), time.time() - start