ZTWHHH commited on
Commit
dd2ad3e
·
verified ·
1 Parent(s): 8d44d89

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. vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc +0 -0
  2. vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc +0 -0
  3. vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/wandb/apis/importers/__init__.py +1 -0
  7. vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/__init__.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/mlflow.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/validation.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/internal.py +385 -0
  15. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/protocols.py +103 -0
  16. vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/util.py +78 -0
  17. vllm/lib/python3.10/site-packages/wandb/apis/importers/mlflow.py +254 -0
  18. vllm/lib/python3.10/site-packages/wandb/apis/importers/validation.py +108 -0
  19. vllm/lib/python3.10/site-packages/wandb/apis/importers/wandb.py +1603 -0
  20. vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/__init__.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/history.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/runs.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/users.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/utils.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/wandb/apis/reports/v2/__init__.py +8 -0
  26. vllm/lib/python3.10/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/wandb/integration/__init__.py +0 -0
  28. vllm/lib/python3.10/site-packages/wandb/integration/cohere/__init__.py +3 -0
  29. vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/resolver.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/wandb/integration/cohere/cohere.py +21 -0
  33. vllm/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py +347 -0
  34. vllm/lib/python3.10/site-packages/wandb/integration/fastai/__init__.py +243 -0
  35. vllm/lib/python3.10/site-packages/wandb/integration/fastai/__pycache__/__init__.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/wandb/integration/gym/__init__.py +99 -0
  37. vllm/lib/python3.10/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/wandb/integration/huggingface/__init__.py +3 -0
  39. vllm/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/huggingface.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/wandb/integration/huggingface/resolver.py +213 -0
  41. vllm/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py +334 -0
  42. vllm/lib/python3.10/site-packages/wandb/integration/openai/__init__.py +3 -0
  43. vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/__init__.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/fine_tuning.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/openai.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py +480 -0
  48. vllm/lib/python3.10/site-packages/wandb/integration/openai/openai.py +22 -0
  49. vllm/lib/python3.10/site-packages/wandb/integration/openai/resolver.py +240 -0
  50. vllm/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py +3 -0
vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc ADDED
Binary file (9.55 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc ADDED
Binary file (1.83 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .internals.util import Namespace
vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (218 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/mlflow.cpython-310.pyc ADDED
Binary file (9.17 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/validation.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-310.pyc ADDED
Binary file (44.4 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-310.pyc ADDED
Binary file (5.02 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-310.pyc ADDED
Binary file (2.89 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/internal.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import math
4
+ import os
5
+ import queue
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Iterable, Optional
9
+
10
+ import numpy as np
11
+ from google.protobuf.json_format import ParseDict
12
+ from tenacity import retry, stop_after_attempt, wait_random_exponential
13
+
14
+ from wandb import Artifact
15
+ from wandb.proto import wandb_internal_pb2 as pb
16
+ from wandb.proto import wandb_settings_pb2
17
+ from wandb.proto import wandb_telemetry_pb2 as telem_pb
18
+ from wandb.sdk.interface.interface import file_policy_to_enum
19
+ from wandb.sdk.interface.interface_queue import InterfaceQueue
20
+ from wandb.sdk.internal import context
21
+ from wandb.sdk.internal.sender import SendManager
22
+ from wandb.sdk.internal.settings_static import SettingsStatic
23
+ from wandb.util import coalesce, recursive_cast_dictlike_to_dict
24
+
25
+ from .protocols import ImporterRun
26
+
27
+ ROOT_DIR = "./wandb-importer"
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+ logger.setLevel(logging.INFO)
32
+
33
+ if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"):
34
+ from rich.logging import RichHandler
35
+
36
+ logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True))
37
+ else:
38
+ console_handler = logging.StreamHandler()
39
+ console_handler.setLevel(logging.INFO)
40
+
41
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
42
+ console_handler.setFormatter(formatter)
43
+
44
+ logger.addHandler(console_handler)
45
+
46
+
47
+ exp_retry = retry(
48
+ wait=wait_random_exponential(multiplier=1, max=10), stop=stop_after_attempt(3)
49
+ )
50
+
51
+
52
+ class AlternateSendManager(SendManager):
53
+ def __init__(self, *args, **kwargs):
54
+ super().__init__(*args, **kwargs)
55
+ self._send_artifact = exp_retry(self._send_artifact)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class SendManagerConfig:
60
+ """Configure which parts of SendManager tooling to use."""
61
+
62
+ use_artifacts: bool = False
63
+ log_artifacts: bool = False
64
+ metadata: bool = False
65
+ files: bool = False
66
+ media: bool = False
67
+ code: bool = False
68
+ history: bool = False
69
+ summary: bool = False
70
+ terminal_output: bool = False
71
+
72
+
73
+ @dataclass
74
+ class RecordMaker:
75
+ run: ImporterRun
76
+ interface: InterfaceQueue = InterfaceQueue()
77
+
78
+ @property
79
+ def run_dir(self) -> str:
80
+ p = Path(f"{ROOT_DIR}/{self.run.run_id()}/wandb")
81
+ p.mkdir(parents=True, exist_ok=True)
82
+ return f"{ROOT_DIR}/{self.run.run_id()}"
83
+
84
+ def make_artifacts_only_records(
85
+ self,
86
+ artifacts: Optional[Iterable[Artifact]] = None,
87
+ used_artifacts: Optional[Iterable[Artifact]] = None,
88
+ ) -> Iterable[pb.Record]:
89
+ """Only make records required to upload artifacts.
90
+
91
+ Escape hatch for adding extra artifacts to a run.
92
+ """
93
+ yield self._make_run_record()
94
+
95
+ if used_artifacts:
96
+ for art in used_artifacts:
97
+ yield self._make_artifact_record(art, use_artifact=True)
98
+
99
+ if artifacts:
100
+ for art in artifacts:
101
+ yield self._make_artifact_record(art)
102
+
103
+ def make_records(
104
+ self,
105
+ config: SendManagerConfig,
106
+ ) -> Iterable[pb.Record]:
107
+ """Make all the records that constitute a run."""
108
+ yield self._make_run_record()
109
+ yield self._make_telem_record()
110
+
111
+ include_artifacts = config.log_artifacts or config.use_artifacts
112
+ yield self._make_files_record(
113
+ include_artifacts, config.files, config.media, config.code
114
+ )
115
+
116
+ if config.use_artifacts:
117
+ if (used_artifacts := self.run.used_artifacts()) is not None:
118
+ for artifact in used_artifacts:
119
+ yield self._make_artifact_record(artifact, use_artifact=True)
120
+
121
+ if config.log_artifacts:
122
+ if (artifacts := self.run.artifacts()) is not None:
123
+ for artifact in artifacts:
124
+ yield self._make_artifact_record(artifact)
125
+
126
+ if config.history:
127
+ yield from self._make_history_records()
128
+
129
+ if config.summary:
130
+ yield self._make_summary_record()
131
+
132
+ if config.terminal_output:
133
+ if (lines := self.run.logs()) is not None:
134
+ for line in lines:
135
+ yield self._make_output_record(line)
136
+
137
+ def _make_run_record(self) -> pb.Record:
138
+ run = pb.RunRecord()
139
+ run.run_id = self.run.run_id()
140
+ run.entity = self.run.entity()
141
+ run.project = self.run.project()
142
+ run.display_name = coalesce(self.run.display_name())
143
+ run.notes = coalesce(self.run.notes(), "")
144
+ run.tags.extend(coalesce(self.run.tags(), []))
145
+ run.start_time.FromMilliseconds(self.run.start_time())
146
+
147
+ host = self.run.host()
148
+ if host is not None:
149
+ run.host = host
150
+
151
+ runtime = self.run.runtime()
152
+ if runtime is not None:
153
+ run.runtime = runtime
154
+
155
+ run_group = self.run.run_group()
156
+ if run_group is not None:
157
+ run.run_group = run_group
158
+
159
+ config = self.run.config()
160
+ if "_wandb" not in config:
161
+ config["_wandb"] = {}
162
+
163
+ # how do I get this automatically?
164
+ config["_wandb"]["code_path"] = self.run.code_path()
165
+ config["_wandb"]["python_version"] = self.run.python_version()
166
+ config["_wandb"]["cli_version"] = self.run.cli_version()
167
+
168
+ self.interface._make_config(
169
+ data=config,
170
+ obj=run.config,
171
+ ) # is there a better way?
172
+ return self.interface._make_record(run=run)
173
+
174
+ def _make_output_record(self, line) -> pb.Record:
175
+ output_raw = pb.OutputRawRecord()
176
+ output_raw.output_type = pb.OutputRawRecord.OutputType.STDOUT
177
+ output_raw.line = line
178
+ return self.interface._make_record(output_raw=output_raw)
179
+
180
+ def _make_summary_record(self) -> pb.Record:
181
+ d: dict = {
182
+ **self.run.summary(),
183
+ "_runtime": self.run.runtime(), # quirk of runtime -- it has to be here!
184
+ # '_timestamp': self.run.start_time()/1000,
185
+ }
186
+ d = recursive_cast_dictlike_to_dict(d)
187
+ summary = self.interface._make_summary_from_dict(d)
188
+ return self.interface._make_record(summary=summary)
189
+
190
+ def _make_history_records(self) -> Iterable[pb.Record]:
191
+ for metrics in self.run.metrics():
192
+ history = pb.HistoryRecord()
193
+ for k, v in metrics.items():
194
+ item = history.item.add()
195
+ item.key = k
196
+ # There seems to be some conversion issue to breaks when we try to re-upload.
197
+ # np.NaN gets converted to float("nan"), which is not expected by our system.
198
+ # If this cast to string (!) is not done, the row will be dropped.
199
+ if (isinstance(v, float) and math.isnan(v)) or v == "NaN":
200
+ v = np.NaN
201
+
202
+ if isinstance(v, bytes):
203
+ # it's a json string encoded as bytes
204
+ v = v.decode("utf-8")
205
+ else:
206
+ v = json.dumps(v)
207
+
208
+ item.value_json = v
209
+ rec = self.interface._make_record(history=history)
210
+ yield rec
211
+
212
+ def _make_files_record(
213
+ self, artifacts: bool, files: bool, media: bool, code: bool
214
+ ) -> pb.Record:
215
+ run_files = self.run.files()
216
+ metadata_fname = f"{self.run_dir}/files/wandb-metadata.json"
217
+ if not files or run_files is None:
218
+ # We'll always need a metadata file even if there are no other files to upload
219
+ metadata_fname = self._make_metadata_file()
220
+ run_files = [(metadata_fname, "end")]
221
+ files_record = pb.FilesRecord()
222
+ for path, policy in run_files:
223
+ if not artifacts and path.startswith("artifact/"):
224
+ continue
225
+ if not media and path.startswith("media/"):
226
+ continue
227
+ if not code and path.startswith("code/"):
228
+ continue
229
+
230
+ # DirWatcher requires the path to start with media/ instead of the full path
231
+ if "media" in path:
232
+ p = Path(path)
233
+ path = str(p.relative_to(f"{self.run_dir}/files"))
234
+ f = files_record.files.add()
235
+ f.path = path
236
+ f.policy = file_policy_to_enum(policy)
237
+
238
+ return self.interface._make_record(files=files_record)
239
+
240
+ def _make_artifact_record(
241
+ self, artifact: Artifact, use_artifact=False
242
+ ) -> pb.Record:
243
+ proto = self.interface._make_artifact(artifact)
244
+ proto.run_id = str(self.run.run_id())
245
+ proto.project = str(self.run.project())
246
+ proto.entity = str(self.run.entity())
247
+ proto.user_created = use_artifact
248
+ proto.use_after_commit = use_artifact
249
+ proto.finalize = True
250
+
251
+ aliases = artifact._aliases
252
+ aliases += ["latest", "imported"]
253
+
254
+ for alias in aliases:
255
+ proto.aliases.append(alias)
256
+ return self.interface._make_record(artifact=proto)
257
+
258
+ def _make_telem_record(self) -> pb.Record:
259
+ telem = telem_pb.TelemetryRecord()
260
+
261
+ feature = telem_pb.Feature()
262
+ feature.importer_mlflow = True
263
+ telem.feature.CopyFrom(feature)
264
+
265
+ cli_version = self.run.cli_version()
266
+ if cli_version:
267
+ telem.cli_version = cli_version
268
+
269
+ python_version = self.run.python_version()
270
+ if python_version:
271
+ telem.python_version = python_version
272
+
273
+ return self.interface._make_record(telemetry=telem)
274
+
275
+ def _make_metadata_file(self) -> str:
276
+ missing_text = "This data was not captured"
277
+ files_dir = f"{self.run_dir}/files"
278
+ os.makedirs(files_dir, exist_ok=True)
279
+
280
+ d = {}
281
+ d["os"] = coalesce(self.run.os_version(), missing_text)
282
+ d["python"] = coalesce(self.run.python_version(), missing_text)
283
+ d["program"] = coalesce(self.run.program(), missing_text)
284
+ d["cuda"] = coalesce(self.run.cuda_version(), missing_text)
285
+ d["host"] = coalesce(self.run.host(), missing_text)
286
+ d["username"] = coalesce(self.run.username(), missing_text)
287
+ d["executable"] = coalesce(self.run.executable(), missing_text)
288
+
289
+ gpus_used = self.run.gpus_used()
290
+ if gpus_used is not None:
291
+ d["gpu_devices"] = json.dumps(gpus_used)
292
+ d["gpu_count"] = json.dumps(len(gpus_used))
293
+
294
+ cpus_used = self.run.cpus_used()
295
+ if cpus_used is not None:
296
+ d["cpu_count"] = json.dumps(self.run.cpus_used())
297
+
298
+ mem_used = self.run.memory_used()
299
+ if mem_used is not None:
300
+ d["memory"] = json.dumps({"total": self.run.memory_used()})
301
+
302
+ fname = f"{files_dir}/wandb-metadata.json"
303
+ with open(fname, "w") as f:
304
+ f.write(json.dumps(d))
305
+ return fname
306
+
307
+
308
+ def _make_settings(
309
+ root_dir: str, settings_override: Optional[Dict[str, Any]] = None
310
+ ) -> SettingsStatic:
311
+ _settings_override = coalesce(settings_override, {})
312
+
313
+ default_settings: Dict[str, Any] = {
314
+ "x_files_dir": os.path.join(root_dir, "files"),
315
+ "root_dir": root_dir,
316
+ "sync_file": os.path.join(root_dir, "txlog.wandb"),
317
+ "resume": "false",
318
+ "program": None,
319
+ "ignore_globs": [],
320
+ "disable_job_creation": True,
321
+ "x_start_time": 0,
322
+ "_offline": None,
323
+ "x_sync": True,
324
+ "x_live_policy_rate_limit": 15, # matches dir_watcher
325
+ "x_live_policy_wait_time": 600, # matches dir_watcher
326
+ "x_file_stream_timeout_seconds": 60,
327
+ }
328
+
329
+ combined_settings = {**default_settings, **_settings_override}
330
+ settings_message = wandb_settings_pb2.Settings()
331
+ ParseDict(combined_settings, settings_message)
332
+
333
+ return SettingsStatic(settings_message)
334
+
335
+
336
+ def send_run(
337
+ run: ImporterRun,
338
+ *,
339
+ extra_arts: Optional[Iterable[Artifact]] = None,
340
+ extra_used_arts: Optional[Iterable[Artifact]] = None,
341
+ config: Optional[SendManagerConfig] = None,
342
+ overrides: Optional[Dict[str, Any]] = None,
343
+ settings_override: Optional[Dict[str, Any]] = None,
344
+ ) -> None:
345
+ if config is None:
346
+ config = SendManagerConfig()
347
+
348
+ # does this need to be here for pmap?
349
+ if overrides:
350
+ for k, v in overrides.items():
351
+ # `lambda: v` won't work!
352
+ # https://stackoverflow.com/questions/10802002/why-deepcopy-doesnt-create-new-references-to-lambda-function
353
+ setattr(run, k, lambda v=v: v)
354
+
355
+ rm = RecordMaker(run)
356
+ root_dir = rm.run_dir
357
+
358
+ settings = _make_settings(root_dir, settings_override)
359
+ sm_record_q = queue.Queue()
360
+ # wm_record_q = queue.Queue()
361
+ result_q = queue.Queue()
362
+ interface = InterfaceQueue(record_q=sm_record_q)
363
+ context_keeper = context.ContextKeeper()
364
+ sm = AlternateSendManager(
365
+ settings, sm_record_q, result_q, interface, context_keeper
366
+ )
367
+ # wm = WriteManager(
368
+ # settings, wm_record_q, result_q, sm_record_q, interface, context_keeper
369
+ # )
370
+
371
+ if extra_arts or extra_used_arts:
372
+ records = rm.make_artifacts_only_records(extra_arts, extra_used_arts)
373
+ else:
374
+ records = rm.make_records(config)
375
+
376
+ for r in records:
377
+ logger.debug(f"Sending {r=}")
378
+ # In a future update, it might be good to write to a transaction log and have
379
+ # incremental uploads only send the missing records.
380
+ # wm.write(r)
381
+
382
+ sm.send(r)
383
+
384
+ sm.finish()
385
+ # wm.finish()
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/protocols.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import (
3
+ Any,
4
+ Dict,
5
+ Iterable,
6
+ List,
7
+ Literal,
8
+ Optional,
9
+ Protocol,
10
+ Tuple,
11
+ runtime_checkable,
12
+ )
13
+
14
+ from wandb.sdk.artifacts.artifact import Artifact
15
+
16
+ logger = logging.getLogger("import_logger")
17
+
18
+ PathStr = str
19
+ Policy = Literal["now", "end", "live"]
20
+
21
+
22
+ @runtime_checkable
23
+ class ImporterRun(Protocol):
24
+ def run_id(self) -> str: ... # pragma: no cover
25
+
26
+ def entity(self) -> str: ... # pragma: no cover
27
+
28
+ def project(self) -> str: ... # pragma: no cover
29
+
30
+ def config(self) -> Dict[str, Any]: ... # pragma: no cover
31
+
32
+ def summary(self) -> Dict[str, float]: ... # pragma: no cover
33
+
34
+ def metrics(self) -> Iterable[Dict[str, float]]:
35
+ """Metrics for the run.
36
+
37
+ We expect metrics in this shape:
38
+
39
+ [
40
+ {'metric1': 1, 'metric2': 1, '_step': 0},
41
+ {'metric1': 2, 'metric2': 4, '_step': 1},
42
+ {'metric1': 3, 'metric2': 9, '_step': 2},
43
+ ...
44
+ ]
45
+
46
+ You can also submit metrics in this shape:
47
+ [
48
+ {'metric1': 1, '_step': 0},
49
+ {'metric2': 1, '_step': 0},
50
+ {'metric1': 2, '_step': 1},
51
+ {'metric2': 4, '_step': 1},
52
+ ...
53
+ ]
54
+ """
55
+ ... # pragma: no cover
56
+
57
+ def run_group(self) -> Optional[str]: ... # pragma: no cover
58
+
59
+ def job_type(self) -> Optional[str]: ... # pragma: no cover
60
+
61
+ def display_name(self) -> str: ... # pragma: no cover
62
+
63
+ def notes(self) -> Optional[str]: ... # pragma: no cover
64
+
65
+ def tags(self) -> Optional[List[str]]: ... # pragma: no cover
66
+
67
+ def artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
68
+
69
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
70
+
71
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
72
+
73
+ def python_version(self) -> Optional[str]: ... # pragma: no cover
74
+
75
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
76
+
77
+ def program(self) -> Optional[str]: ... # pragma: no cover
78
+
79
+ def host(self) -> Optional[str]: ... # pragma: no cover
80
+
81
+ def username(self) -> Optional[str]: ... # pragma: no cover
82
+
83
+ def executable(self) -> Optional[str]: ... # pragma: no cover
84
+
85
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
86
+
87
+ def cpus_used(self) -> Optional[int]: ... # pragma: no cover
88
+
89
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
90
+
91
+ def runtime(self) -> Optional[int]: ... # pragma: no cover
92
+
93
+ def start_time(self) -> Optional[int]: ... # pragma: no cover
94
+
95
+ def code_path(self) -> Optional[str]: ... # pragma: no cover
96
+
97
+ def cli_version(self) -> Optional[str]: ... # pragma: no cover
98
+
99
+ def files(
100
+ self,
101
+ ) -> Optional[Iterable[Tuple[PathStr, Policy]]]: ... # pragma: no cover
102
+
103
+ def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover
vllm/lib/python3.10/site-packages/wandb/apis/importers/internals/util.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ import traceback
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ from dataclasses import dataclass
6
+ from typing import Iterable, Optional
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Namespace:
11
+ """Configure an alternate entity/project at the dst server your data will end up in."""
12
+
13
+ entity: str
14
+ project: str
15
+
16
+ @classmethod
17
+ def from_path(cls, path: str):
18
+ entity, project = path.split("/")
19
+ return cls(entity, project)
20
+
21
+ @property
22
+ def path(self):
23
+ return f"{self.entity}/{self.project}"
24
+
25
+ @property
26
+ def send_manager_overrides(self):
27
+ overrides = {}
28
+ if self.entity:
29
+ overrides["entity"] = self.entity
30
+ if self.project:
31
+ overrides["project"] = self.project
32
+ return overrides
33
+
34
+
35
+ logger = logging.getLogger("import_logger")
36
+
37
+
38
+ def parallelize(
39
+ func,
40
+ iterable: Iterable,
41
+ *args,
42
+ max_workers: Optional[int] = None,
43
+ raise_on_error: bool = False,
44
+ **kwargs,
45
+ ):
46
+ def safe_func(*args, **kwargs):
47
+ try:
48
+ return func(*args, **kwargs)
49
+ except Exception as e:
50
+ _, _, exc_traceback = sys.exc_info()
51
+ traceback_details = traceback.extract_tb(exc_traceback)
52
+ filename = traceback_details[-1].filename
53
+ lineno = traceback_details[-1].lineno
54
+ logger.debug(
55
+ f"Exception: {func=} {args=} {kwargs=} {e=} {filename=} {lineno=}. {traceback_details=}"
56
+ )
57
+ if raise_on_error:
58
+ raise e
59
+
60
+ results = []
61
+ with ThreadPoolExecutor(max_workers) as exc:
62
+ futures = {exc.submit(safe_func, x, *args, **kwargs): x for x in iterable}
63
+ for future in as_completed(futures):
64
+ results.append(future.result())
65
+ return results
66
+
67
+
68
+ def for_each(
69
+ func, iterable: Iterable, parallel: bool = True, max_workers: Optional[int] = None
70
+ ):
71
+ if parallel:
72
+ return parallelize(
73
+ func,
74
+ iterable,
75
+ max_workers=max_workers,
76
+ )
77
+
78
+ return [func(x) for x in iterable]
vllm/lib/python3.10/site-packages/wandb/apis/importers/mlflow.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import logging
3
+ import re
4
+ from collections import defaultdict
5
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
6
+
7
+ import mlflow
8
+ from packaging.version import Version # type: ignore
9
+
10
+ import wandb
11
+ from wandb import Artifact
12
+
13
+ from .internals import internal
14
+ from .internals.util import Namespace, for_each
15
+
16
+ mlflow_version = Version(mlflow.__version__)
17
+
18
+ logger = logging.getLogger("import_logger")
19
+
20
+
21
+ class MlflowRun:
22
+ def __init__(self, run, mlflow_client):
23
+ self.run = run
24
+ self.mlflow_client: mlflow.MlflowClient = mlflow_client
25
+
26
+ def run_id(self) -> str:
27
+ return self.run.info.run_id
28
+
29
+ def entity(self) -> str:
30
+ return self.run.info.user_id
31
+
32
+ def project(self) -> str:
33
+ return "imported-from-mlflow"
34
+
35
+ def config(self) -> Dict[str, Any]:
36
+ conf = self.run.data.params
37
+
38
+ # Add tags here since mlflow supports very long tag names but we only support up to 64 chars
39
+ tags = {
40
+ k: v for k, v in self.run.data.tags.items() if not k.startswith("mlflow.")
41
+ }
42
+ return {**conf, "imported_mlflow_tags": tags}
43
+
44
+ def summary(self) -> Dict[str, float]:
45
+ return self.run.data.metrics
46
+
47
+ def metrics(self) -> Iterable[Dict[str, float]]:
48
+ d: Dict[int, Dict[str, float]] = defaultdict(dict)
49
+ for k in self.run.data.metrics.keys():
50
+ metric = self.mlflow_client.get_metric_history(self.run.info.run_id, k)
51
+ for item in metric:
52
+ d[item.step][item.key] = item.value
53
+
54
+ for k, v in d.items():
55
+ yield {"_step": k, **v}
56
+
57
+ def run_group(self) -> Optional[str]:
58
+ # this is nesting? Parent at `run.info.tags.get("mlflow.parentRunId")`
59
+ return f"Experiment {self.run.info.experiment_id}"
60
+
61
+ def job_type(self) -> Optional[str]:
62
+ # Is this the right approach?
63
+ return f"User {self.run.info.user_id}"
64
+
65
+ def display_name(self) -> str:
66
+ if mlflow_version < Version("1.30.0"):
67
+ return self.run.data.tags["mlflow.runName"]
68
+ return self.run.info.run_name
69
+
70
+ def notes(self) -> Optional[str]:
71
+ return self.run.data.tags.get("mlflow.note.content")
72
+
73
+ def tags(self) -> Optional[List[str]]:
74
+ ...
75
+
76
+ # W&B tags are different than mlflow tags.
77
+ # The full mlflow tags are added to config under key `imported_mlflow_tags` instead
78
+
79
+ def artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore
80
+ if mlflow_version < Version("2.0.0"):
81
+ dir_path = self.mlflow_client.download_artifacts(
82
+ run_id=self.run.info.run_id,
83
+ path="",
84
+ )
85
+ else:
86
+ dir_path = mlflow.artifacts.download_artifacts(run_id=self.run.info.run_id)
87
+
88
+ # Since mlflow doesn't have extra metadata about the artifacts,
89
+ # we just lump them all together into a single wandb.Artifact
90
+ artifact_name = self._handle_incompatible_strings(self.display_name())
91
+ art = wandb.Artifact(artifact_name, "imported-artifacts")
92
+ art.add_dir(dir_path)
93
+
94
+ return [art]
95
+
96
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore
97
+ ... # pragma: no cover
98
+
99
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
100
+
101
+ def python_version(self) -> Optional[str]: ... # pragma: no cover
102
+
103
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
104
+
105
+ def program(self) -> Optional[str]: ... # pragma: no cover
106
+
107
+ def host(self) -> Optional[str]: ... # pragma: no cover
108
+
109
+ def username(self) -> Optional[str]: ... # pragma: no cover
110
+
111
+ def executable(self) -> Optional[str]: ... # pragma: no cover
112
+
113
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
114
+
115
+ def cpus_used(self) -> Optional[int]: # can we get the model?
116
+ ... # pragma: no cover
117
+
118
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
119
+
120
+ def runtime(self) -> Optional[int]:
121
+ end_time = (
122
+ self.run.info.end_time // 1000
123
+ if self.run.info.end_time is not None
124
+ else self.start_time()
125
+ )
126
+ return end_time - self.start_time()
127
+
128
+ def start_time(self) -> Optional[int]:
129
+ return self.run.info.start_time // 1000
130
+
131
+ def code_path(self) -> Optional[str]: ... # pragma: no cover
132
+
133
+ def cli_version(self) -> Optional[str]: ... # pragma: no cover
134
+
135
+ def files(self) -> Optional[Iterable[Tuple[str, str]]]: ... # pragma: no cover
136
+
137
+ def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover
138
+
139
+ @staticmethod
140
+ def _handle_incompatible_strings(s: str) -> str:
141
+ valid_chars = r"[^a-zA-Z0-9_\-\.]"
142
+ replacement = "__"
143
+
144
+ return re.sub(valid_chars, replacement, s)
145
+
146
+
147
+ class MlflowImporter:
148
+ def __init__(
149
+ self,
150
+ dst_base_url: str,
151
+ dst_api_key: str,
152
+ mlflow_tracking_uri: str,
153
+ mlflow_registry_uri: Optional[str] = None,
154
+ *,
155
+ custom_api_kwargs: Optional[Dict[str, Any]] = None,
156
+ ) -> None:
157
+ self.dst_base_url = dst_base_url
158
+ self.dst_api_key = dst_api_key
159
+
160
+ if custom_api_kwargs is None:
161
+ custom_api_kwargs = {"timeout": 600}
162
+
163
+ self.dst_api = wandb.Api(
164
+ api_key=dst_api_key,
165
+ overrides={"base_url": dst_base_url},
166
+ **custom_api_kwargs,
167
+ )
168
+ self.mlflow_tracking_uri = mlflow_tracking_uri
169
+ mlflow.set_tracking_uri(self.mlflow_tracking_uri)
170
+
171
+ if mlflow_registry_uri:
172
+ mlflow.set_registry_uri(mlflow_registry_uri)
173
+
174
+ self.mlflow_client = mlflow.tracking.MlflowClient(mlflow_tracking_uri)
175
+
176
+ def __repr__(self):
177
+ return f"<MlflowImporter src={self.mlflow_tracking_uri}>"
178
+
179
+ def collect_runs(self, *, limit: Optional[int] = None) -> Iterable[MlflowRun]:
180
+ if mlflow_version < Version("1.28.0"):
181
+ experiments = self.mlflow_client.list_experiments()
182
+ else:
183
+ experiments = self.mlflow_client.search_experiments()
184
+
185
+ def _runs():
186
+ for exp in experiments:
187
+ for run in self.mlflow_client.search_runs(exp.experiment_id):
188
+ yield MlflowRun(run, self.mlflow_client)
189
+
190
+ runs = itertools.islice(_runs(), limit)
191
+ yield from runs
192
+
193
+ def _import_run(
194
+ self,
195
+ run: MlflowRun,
196
+ *,
197
+ artifacts: bool = True,
198
+ namespace: Optional[Namespace] = None,
199
+ config: Optional[internal.SendManagerConfig] = None,
200
+ ) -> None:
201
+ if namespace is None:
202
+ namespace = Namespace(run.entity(), run.project())
203
+
204
+ if config is None:
205
+ config = internal.SendManagerConfig(
206
+ metadata=True,
207
+ files=True,
208
+ media=True,
209
+ code=True,
210
+ history=True,
211
+ summary=True,
212
+ terminal_output=True,
213
+ )
214
+
215
+ settings_override = {
216
+ "api_key": self.dst_api_key,
217
+ "base_url": self.dst_base_url,
218
+ "resume": "true",
219
+ "resumed": True,
220
+ }
221
+
222
+ mlflow.set_tracking_uri(self.mlflow_tracking_uri)
223
+ internal.send_run(
224
+ run,
225
+ overrides=namespace.send_manager_overrides,
226
+ settings_override=settings_override,
227
+ config=config,
228
+ )
229
+
230
+ # in mlflow, the artifacts come with the runs, so import them together
231
+ if artifacts:
232
+ arts = list(run.artifacts())
233
+ logger.debug(f"Importing history artifacts, {run=}")
234
+ internal.send_run(
235
+ run,
236
+ extra_arts=arts,
237
+ overrides=namespace.send_manager_overrides,
238
+ settings_override=settings_override,
239
+ config=internal.SendManagerConfig(log_artifacts=True),
240
+ )
241
+
242
+ def import_runs(
243
+ self,
244
+ runs: Iterable[MlflowRun],
245
+ *,
246
+ artifacts: bool = True,
247
+ namespace: Optional[Namespace] = None,
248
+ parallel: bool = True,
249
+ max_workers: Optional[int] = None,
250
+ ) -> None:
251
+ def _import_run_wrapped(run):
252
+ self._import_run(run, namespace=namespace, artifacts=artifacts)
253
+
254
+ for_each(_import_run_wrapped, runs, parallel=parallel, max_workers=max_workers)
vllm/lib/python3.10/site-packages/wandb/apis/importers/validation.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import filecmp
2
+ import logging
3
+ import os
4
+
5
+ import requests
6
+
7
+ import wandb
8
+
9
+ logger = logging.getLogger(__name__)
10
+ logger.setLevel(logging.INFO)
11
+
12
+
13
+ def _compare_artifact_manifests(
14
+ src_art: wandb.Artifact, dst_art: wandb.Artifact
15
+ ) -> list:
16
+ problems = []
17
+ if isinstance(dst_art, wandb.CommError):
18
+ return ["commError"]
19
+
20
+ if src_art.digest != dst_art.digest:
21
+ problems.append(f"digest mismatch {src_art.digest=}, {dst_art.digest=}")
22
+
23
+ for name, src_entry in src_art.manifest.entries.items():
24
+ dst_entry = dst_art.manifest.entries.get(name)
25
+ if dst_entry is None:
26
+ problems.append(f"missing manifest entry {name=}, {src_entry=}")
27
+ continue
28
+
29
+ for attr in ["path", "digest", "size"]:
30
+ if getattr(src_entry, attr) != getattr(dst_entry, attr):
31
+ problems.append(
32
+ f"manifest entry mismatch {attr=}, {getattr(src_entry, attr)=}, {getattr(dst_entry, attr)=}"
33
+ )
34
+
35
+ return problems
36
+
37
+
38
+ def _compare_artifact_dirs(src_dir, dst_dir) -> list:
39
+ def compare(src_dir, dst_dir):
40
+ comparison = filecmp.dircmp(src_dir, dst_dir)
41
+ differences = {
42
+ "left_only": comparison.left_only,
43
+ "right_only": comparison.right_only,
44
+ "diff_files": comparison.diff_files,
45
+ "subdir_differences": {},
46
+ }
47
+
48
+ # Recursively find differences in subdirectories
49
+ for subdir in comparison.subdirs:
50
+ subdir_src = os.path.join(src_dir, subdir)
51
+ subdir_dst = os.path.join(dst_dir, subdir)
52
+ subdir_differences = compare(subdir_src, subdir_dst)
53
+ # If there are differences, add them to the result
54
+ if subdir_differences and any(subdir_differences.values()):
55
+ differences["subdir_differences"][subdir] = subdir_differences
56
+
57
+ if all(not diff for diff in differences.values()):
58
+ return None
59
+
60
+ return differences
61
+
62
+ return compare(src_dir, dst_dir)
63
+
64
+
65
+ def _check_entries_are_downloadable(art):
66
+ entries = _collect_entries(art)
67
+ for entry in entries:
68
+ if not _check_entry_is_downloable(entry):
69
+ return False
70
+ return True
71
+
72
+
73
+ def _collect_entries(art):
74
+ has_next_page = True
75
+ cursor = None
76
+ entries = []
77
+ while has_next_page:
78
+ attrs = art._fetch_file_urls(cursor)
79
+ has_next_page = attrs["pageInfo"]["hasNextPage"]
80
+ cursor = attrs["pageInfo"]["endCursor"]
81
+ for edge in attrs["edges"]:
82
+ name = edge["node"]["name"]
83
+ entry = art.get_entry(name)
84
+ entry._download_url = edge["node"]["directUrl"]
85
+ entries.append(entry)
86
+ return entries
87
+
88
+
89
+ def _check_entry_is_downloable(entry):
90
+ url = entry._download_url
91
+ expected_size = entry.size
92
+
93
+ try:
94
+ resp = requests.head(url, allow_redirects=True)
95
+ except Exception as e:
96
+ logger.error(f"Problem validating {entry=}, {e=}")
97
+ return False
98
+
99
+ if resp.status_code != 200:
100
+ return False
101
+
102
+ actual_size = resp.headers.get("content-length", -1)
103
+ actual_size = int(actual_size)
104
+
105
+ if expected_size == actual_size:
106
+ return True
107
+
108
+ return False
vllm/lib/python3.10/site-packages/wandb/apis/importers/wandb.py ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tooling for the W&B Importer."""
2
+
3
+ import itertools
4
+ import json
5
+ import logging
6
+ import numbers
7
+ import os
8
+ import re
9
+ import shutil
10
+ from dataclasses import dataclass, field
11
+ from datetime import datetime as dt
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
14
+ from unittest.mock import patch
15
+
16
+ import filelock
17
+ import polars as pl
18
+ import requests
19
+ import urllib3
20
+ import wandb_workspaces.reports.v1 as wr
21
+ import yaml
22
+ from wandb_gql import gql
23
+ from wandb_workspaces.reports.v1 import Report
24
+
25
+ import wandb
26
+ from wandb.apis.public import ArtifactCollection, Run
27
+ from wandb.apis.public.files import File
28
+ from wandb.util import coalesce, remove_keys_with_none_values
29
+
30
+ from . import validation
31
+ from .internals import internal
32
+ from .internals.protocols import PathStr, Policy
33
+ from .internals.util import Namespace, for_each
34
+
35
+ Artifact = wandb.Artifact
36
+ Api = wandb.Api
37
+ Project = wandb.apis.public.Project
38
+
39
+ ARTIFACT_ERRORS_FNAME = "artifact_errors.jsonl"
40
+ ARTIFACT_SUCCESSES_FNAME = "artifact_successes.jsonl"
41
+ RUN_ERRORS_FNAME = "run_errors.jsonl"
42
+ RUN_SUCCESSES_FNAME = "run_successes.jsonl"
43
+
44
+ ART_SEQUENCE_DUMMY_PLACEHOLDER = "__ART_SEQUENCE_DUMMY_PLACEHOLDER__"
45
+ RUN_DUMMY_PLACEHOLDER = "__RUN_DUMMY_PLACEHOLDER__"
46
+ ART_DUMMY_PLACEHOLDER_PATH = "__importer_temp__"
47
+ ART_DUMMY_PLACEHOLDER_TYPE = "__temp__"
48
+
49
+ SRC_ART_PATH = "./artifacts/src"
50
+ DST_ART_PATH = "./artifacts/dst"
51
+
52
+
53
+ logger = logging.getLogger(__name__)
54
+ logger.setLevel(logging.INFO)
55
+
56
+ if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"):
57
+ from rich.logging import RichHandler
58
+
59
+ logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True))
60
+ else:
61
+ console_handler = logging.StreamHandler()
62
+ console_handler.setLevel(logging.INFO)
63
+
64
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
65
+ console_handler.setFormatter(formatter)
66
+
67
+ logger.addHandler(console_handler)
68
+
69
+
70
+ @dataclass
71
+ class ArtifactSequence:
72
+ artifacts: Iterable[wandb.Artifact]
73
+ entity: str
74
+ project: str
75
+ type_: str
76
+ name: str
77
+
78
+ def __iter__(self) -> Iterator:
79
+ return iter(self.artifacts)
80
+
81
+ def __repr__(self) -> str:
82
+ return f"ArtifactSequence({self.identifier})"
83
+
84
+ @property
85
+ def identifier(self) -> str:
86
+ return "/".join([self.entity, self.project, self.type_, self.name])
87
+
88
+ @classmethod
89
+ def from_collection(cls, collection: ArtifactCollection):
90
+ arts = collection.artifacts()
91
+ arts = sorted(arts, key=lambda a: int(a.version.lstrip("v")))
92
+ return ArtifactSequence(
93
+ arts,
94
+ collection.entity,
95
+ collection.project,
96
+ collection.type,
97
+ collection.name,
98
+ )
99
+
100
+
101
+ class WandbRun:
102
+ def __init__(
103
+ self,
104
+ run: Run,
105
+ *,
106
+ src_base_url: str,
107
+ src_api_key: str,
108
+ dst_base_url: str,
109
+ dst_api_key: str,
110
+ ) -> None:
111
+ self.run = run
112
+ self.api = wandb.Api(
113
+ api_key=src_api_key,
114
+ overrides={"base_url": src_base_url},
115
+ )
116
+ self.dst_api = wandb.Api(
117
+ api_key=dst_api_key,
118
+ overrides={"base_url": dst_base_url},
119
+ )
120
+
121
+ # For caching
122
+ self._files: Optional[Iterable[Tuple[str, str]]] = None
123
+ self._artifacts: Optional[Iterable[Artifact]] = None
124
+ self._used_artifacts: Optional[Iterable[Artifact]] = None
125
+ self._parquet_history_paths: Optional[Iterable[str]] = None
126
+
127
+ def __repr__(self) -> str:
128
+ s = os.path.join(self.entity(), self.project(), self.run_id())
129
+ return f"WandbRun({s})"
130
+
131
+ def run_id(self) -> str:
132
+ return self.run.id
133
+
134
+ def entity(self) -> str:
135
+ return self.run.entity
136
+
137
+ def project(self) -> str:
138
+ return self.run.project
139
+
140
+ def config(self) -> Dict[str, Any]:
141
+ return self.run.config
142
+
143
+ def summary(self) -> Dict[str, float]:
144
+ s = self.run.summary
145
+ return s
146
+
147
+ def metrics(self) -> Iterable[Dict[str, float]]:
148
+ if self._parquet_history_paths is None:
149
+ self._parquet_history_paths = list(self._get_parquet_history_paths())
150
+
151
+ if self._parquet_history_paths:
152
+ rows = self._get_rows_from_parquet_history_paths()
153
+ else:
154
+ logger.warn(
155
+ "No parquet files detected; using scan history (this may not be reliable)"
156
+ )
157
+ rows = self.run.scan_history()
158
+
159
+ for row in rows:
160
+ row = remove_keys_with_none_values(row)
161
+ yield row
162
+
163
+ def run_group(self) -> Optional[str]:
164
+ return self.run.group
165
+
166
+ def job_type(self) -> Optional[str]:
167
+ return self.run.job_type
168
+
169
+ def display_name(self) -> str:
170
+ return self.run.display_name
171
+
172
+ def notes(self) -> Optional[str]:
173
+ # Notes includes the previous notes and serves as a catch-all for things we missed or can't add back
174
+ previous_link = f"Imported from: {self.run.url}"
175
+ previous_author = f"Author: {self.run.user.username}"
176
+
177
+ header = [previous_link, previous_author]
178
+ previous_notes = self.run.notes or ""
179
+
180
+ return "\n".join(header) + "\n---\n" + previous_notes
181
+
182
+ def tags(self) -> Optional[List[str]]:
183
+ return self.run.tags
184
+
185
+ def artifacts(self) -> Optional[Iterable[Artifact]]:
186
+ if self._artifacts is None:
187
+ _artifacts = []
188
+ for art in self.run.logged_artifacts():
189
+ a = _clone_art(art)
190
+ _artifacts.append(a)
191
+ self._artifacts = _artifacts
192
+
193
+ yield from self._artifacts
194
+
195
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]:
196
+ if self._used_artifacts is None:
197
+ _used_artifacts = []
198
+ for art in self.run.used_artifacts():
199
+ a = _clone_art(art)
200
+ _used_artifacts.append(a)
201
+ self._used_artifacts = _used_artifacts
202
+
203
+ yield from self._used_artifacts
204
+
205
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
206
+
207
+ def python_version(self) -> Optional[str]:
208
+ return self._metadata_file().get("python")
209
+
210
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
211
+
212
+ def program(self) -> Optional[str]: ... # pragma: no cover
213
+
214
+ def host(self) -> Optional[str]:
215
+ return self._metadata_file().get("host")
216
+
217
+ def username(self) -> Optional[str]: ... # pragma: no cover
218
+
219
+ def executable(self) -> Optional[str]: ... # pragma: no cover
220
+
221
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
222
+
223
+ def cpus_used(self) -> Optional[int]: # can we get the model?
224
+ ... # pragma: no cover
225
+
226
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
227
+
228
+ def runtime(self) -> Optional[int]:
229
+ wandb_runtime = self.run.summary.get("_wandb", {}).get("runtime")
230
+ base_runtime = self.run.summary.get("_runtime")
231
+
232
+ if (t := coalesce(wandb_runtime, base_runtime)) is None:
233
+ return t
234
+ return int(t)
235
+
236
+ def start_time(self) -> Optional[int]:
237
+ t = dt.fromisoformat(self.run.created_at).timestamp() * 1000
238
+ return int(t)
239
+
240
+ def code_path(self) -> Optional[str]:
241
+ path = self._metadata_file().get("codePath", "")
242
+ return f"code/{path}"
243
+
244
+ def cli_version(self) -> Optional[str]:
245
+ return self._config_file().get("_wandb", {}).get("value", {}).get("cli_version")
246
+
247
+ def files(self) -> Optional[Iterable[Tuple[PathStr, Policy]]]:
248
+ if self._files is None:
249
+ files_dir = f"{internal.ROOT_DIR}/{self.run_id()}/files"
250
+ _files = []
251
+ for f in self.run.files():
252
+ f: File
253
+ # These optimizations are intended to avoid rate limiting when importing many runs in parallel
254
+ # Don't carry over empty files
255
+ if f.size == 0:
256
+ continue
257
+ # Skip deadlist to avoid overloading S3
258
+ if "wandb_manifest.json.deadlist" in f.name:
259
+ continue
260
+
261
+ result = f.download(files_dir, exist_ok=True, api=self.api)
262
+ file_and_policy = (result.name, "end")
263
+ _files.append(file_and_policy)
264
+ self._files = _files
265
+
266
+ yield from self._files
267
+
268
+ def logs(self) -> Optional[Iterable[str]]:
269
+ log_files = self._find_all_in_files_regex(r"^.*output\.log$")
270
+ for path in log_files:
271
+ with open(path) as f:
272
+ yield from f.readlines()
273
+
274
+ def _metadata_file(self) -> Dict[str, Any]:
275
+ if (fname := self._find_in_files("wandb-metadata.json")) is None:
276
+ return {}
277
+
278
+ with open(fname) as f:
279
+ return json.loads(f.read())
280
+
281
+ def _config_file(self) -> Dict[str, Any]:
282
+ if (fname := self._find_in_files("config.yaml")) is None:
283
+ return {}
284
+
285
+ with open(fname) as f:
286
+ return yaml.safe_load(f) or {}
287
+
288
+ def _get_rows_from_parquet_history_paths(self) -> Iterable[Dict[str, Any]]:
289
+ # Unfortunately, it's not feasible to validate non-parquet history
290
+ if not (paths := self._get_parquet_history_paths()):
291
+ yield {}
292
+ return
293
+
294
+ # Collect and merge parquet history
295
+ dfs = [
296
+ pl.read_parquet(p) for path in paths for p in Path(path).glob("*.parquet")
297
+ ]
298
+ if "_step" in (df := _merge_dfs(dfs)):
299
+ df = df.with_columns(pl.col("_step").cast(pl.Int64))
300
+ yield from df.iter_rows(named=True)
301
+
302
+ def _get_parquet_history_paths(self) -> Iterable[str]:
303
+ if self._parquet_history_paths is None:
304
+ paths = []
305
+ # self.artifacts() returns a copy of the artifacts; use this to get raw
306
+ for art in self.run.logged_artifacts():
307
+ if art.type != "wandb-history":
308
+ continue
309
+ if (
310
+ path := _download_art(art, root=f"{SRC_ART_PATH}/{art.name}")
311
+ ) is None:
312
+ continue
313
+ paths.append(path)
314
+ self._parquet_history_paths = paths
315
+
316
+ yield from self._parquet_history_paths
317
+
318
+ def _find_in_files(self, name: str) -> Optional[str]:
319
+ if files := self.files():
320
+ for path, _ in files:
321
+ if name in path:
322
+ return path
323
+ return None
324
+
325
+ def _find_all_in_files_regex(self, regex: str) -> Iterable[str]:
326
+ if files := self.files():
327
+ for path, _ in files:
328
+ if re.match(regex, path):
329
+ yield path
330
+
331
+
332
+ class WandbImporter:
333
+ """Transfers runs, reports, and artifact sequences between W&B instances."""
334
+
335
+ def __init__(
336
+ self,
337
+ src_base_url: str,
338
+ src_api_key: str,
339
+ dst_base_url: str,
340
+ dst_api_key: str,
341
+ *,
342
+ custom_api_kwargs: Optional[Dict[str, Any]] = None,
343
+ ) -> None:
344
+ self.src_base_url = src_base_url
345
+ self.src_api_key = src_api_key
346
+ self.dst_base_url = dst_base_url
347
+ self.dst_api_key = dst_api_key
348
+
349
+ if custom_api_kwargs is None:
350
+ custom_api_kwargs = {"timeout": 600}
351
+
352
+ self.src_api = wandb.Api(
353
+ api_key=src_api_key,
354
+ overrides={"base_url": src_base_url},
355
+ **custom_api_kwargs,
356
+ )
357
+ self.dst_api = wandb.Api(
358
+ api_key=dst_api_key,
359
+ overrides={"base_url": dst_base_url},
360
+ **custom_api_kwargs,
361
+ )
362
+
363
+ self.run_api_kwargs = {
364
+ "src_base_url": src_base_url,
365
+ "src_api_key": src_api_key,
366
+ "dst_base_url": dst_base_url,
367
+ "dst_api_key": dst_api_key,
368
+ }
369
+
370
+ def __repr__(self):
371
+ return f"<WandbImporter src={self.src_base_url}, dst={self.dst_base_url}>" # pragma: no cover
372
+
373
+ def _import_run(
374
+ self,
375
+ run: WandbRun,
376
+ *,
377
+ namespace: Optional[Namespace] = None,
378
+ config: Optional[internal.SendManagerConfig] = None,
379
+ ) -> None:
380
+ """Import one WandbRun.
381
+
382
+ Use `namespace` to specify alternate settings like where the run should be uploaded
383
+ """
384
+ if namespace is None:
385
+ namespace = Namespace(run.entity(), run.project())
386
+
387
+ if config is None:
388
+ config = internal.SendManagerConfig(
389
+ metadata=True,
390
+ files=True,
391
+ media=True,
392
+ code=True,
393
+ history=True,
394
+ summary=True,
395
+ terminal_output=True,
396
+ )
397
+
398
+ settings_override = {
399
+ "api_key": self.dst_api_key,
400
+ "base_url": self.dst_base_url,
401
+ "resume": "true",
402
+ "resumed": True,
403
+ }
404
+
405
+ # Send run with base config
406
+ logger.debug(f"Importing run, {run=}")
407
+ internal.send_run(
408
+ run,
409
+ overrides=namespace.send_manager_overrides,
410
+ settings_override=settings_override,
411
+ config=config,
412
+ )
413
+
414
+ if config.history:
415
+ # Send run again with history artifacts in case config history=True, artifacts=False
416
+ # The history artifact must come with the actual history data
417
+
418
+ logger.debug(f"Collecting history artifacts, {run=}")
419
+ history_arts = []
420
+ for art in run.run.logged_artifacts():
421
+ if art.type != "wandb-history":
422
+ continue
423
+ logger.debug(f"Collecting history artifact {art.name=}")
424
+ new_art = _clone_art(art)
425
+ history_arts.append(new_art)
426
+
427
+ logger.debug(f"Importing history artifacts, {run=}")
428
+ internal.send_run(
429
+ run,
430
+ extra_arts=history_arts,
431
+ overrides=namespace.send_manager_overrides,
432
+ settings_override=settings_override,
433
+ config=config,
434
+ )
435
+
436
+ def _delete_collection_in_dst(
437
+ self,
438
+ seq: ArtifactSequence,
439
+ namespace: Optional[Namespace] = None,
440
+ ):
441
+ """Deletes the equivalent artifact collection in destination.
442
+
443
+ Intended to clear the destination when an uploaded artifact does not pass validation.
444
+ """
445
+ entity = coalesce(namespace.entity, seq.entity)
446
+ project = coalesce(namespace.project, seq.project)
447
+ art_type = f"{entity}/{project}/{seq.type_}"
448
+ art_name = seq.name
449
+
450
+ logger.info(
451
+ f"Deleting collection {entity=}, {project=}, {art_type=}, {art_name=}"
452
+ )
453
+ try:
454
+ dst_collection = self.dst_api.artifact_collection(art_type, art_name)
455
+ except (wandb.CommError, ValueError):
456
+ logger.warn(f"Collection doesn't exist {art_type=}, {art_name=}")
457
+ return
458
+
459
+ try:
460
+ dst_collection.delete()
461
+ except (wandb.CommError, ValueError) as e:
462
+ logger.warn(f"Collection can't be deleted, {art_type=}, {art_name=}, {e=}")
463
+ return
464
+
465
+ def _import_artifact_sequence(
466
+ self,
467
+ seq: ArtifactSequence,
468
+ *,
469
+ namespace: Optional[Namespace] = None,
470
+ ) -> None:
471
+ """Import one artifact sequence.
472
+
473
+ Use `namespace` to specify alternate settings like where the artifact sequence should be uploaded
474
+ """
475
+ if not seq.artifacts:
476
+ # The artifact sequence has no versions. This usually means all artifacts versions were deleted intentionally,
477
+ # but it can also happen if the sequence represents run history and that run was deleted.
478
+ logger.warn(f"Artifact {seq=} has no artifacts, skipping.")
479
+ return
480
+
481
+ if namespace is None:
482
+ namespace = Namespace(seq.entity, seq.project)
483
+
484
+ settings_override = {
485
+ "api_key": self.dst_api_key,
486
+ "base_url": self.dst_base_url,
487
+ "resume": "true",
488
+ "resumed": True,
489
+ }
490
+
491
+ send_manager_config = internal.SendManagerConfig(log_artifacts=True)
492
+
493
+ # Delete any existing artifact sequence, otherwise versions will be out of order
494
+ # Unfortunately, you can't delete only part of the sequence because versions are "remembered" even after deletion
495
+ self._delete_collection_in_dst(seq, namespace)
496
+
497
+ # Get a placeholder run for dummy artifacts we'll upload later
498
+ art = seq.artifacts[0]
499
+ run_or_dummy: Optional[Run] = _get_run_or_dummy_from_art(art, self.src_api)
500
+
501
+ # Each `group_of_artifacts` is either:
502
+ # 1. A single "real" artifact in a list; or
503
+ # 2. A list of dummy artifacts that are uploaded together.
504
+ # This guarantees the real artifacts have the correct version numbers while allowing for parallel upload of dummies.
505
+ groups_of_artifacts = list(_make_groups_of_artifacts(seq))
506
+ for i, group in enumerate(groups_of_artifacts, 1):
507
+ art = group[0]
508
+ if art.description == ART_SEQUENCE_DUMMY_PLACEHOLDER:
509
+ run = WandbRun(run_or_dummy, **self.run_api_kwargs)
510
+ else:
511
+ try:
512
+ wandb_run = art.logged_by()
513
+ except ValueError:
514
+ # The run used to exist but has since been deleted
515
+ # wandb_run = None
516
+ pass
517
+
518
+ # Could be logged by None (rare) or ValueError
519
+ if wandb_run is None:
520
+ logger.warn(
521
+ f"Run for {art.name=} does not exist (deleted?), using {run_or_dummy=}"
522
+ )
523
+ wandb_run = run_or_dummy
524
+
525
+ new_art = _clone_art(art)
526
+ group = [new_art]
527
+ run = WandbRun(wandb_run, **self.run_api_kwargs)
528
+
529
+ logger.info(
530
+ f"Uploading partial artifact {seq=}, {i}/{len(groups_of_artifacts)}"
531
+ )
532
+ internal.send_run(
533
+ run,
534
+ extra_arts=group,
535
+ overrides=namespace.send_manager_overrides,
536
+ settings_override=settings_override,
537
+ config=send_manager_config,
538
+ )
539
+ logger.info(f"Finished uploading {seq=}")
540
+
541
+ # query it back and remove placeholders
542
+ self._remove_placeholders(seq)
543
+
544
+ def _remove_placeholders(self, seq: ArtifactSequence) -> None:
545
+ try:
546
+ retry_arts_func = internal.exp_retry(self._dst_api.artifacts)
547
+ dst_arts = list(retry_arts_func(seq.type_, seq.name))
548
+ except wandb.CommError:
549
+ logger.warn(f"{seq=} does not exist in dst. Has it already been deleted?")
550
+ return
551
+ except TypeError as e:
552
+ logger.error(f"Problem getting dst versions (try again later) {e=}")
553
+ return
554
+
555
+ for art in dst_arts:
556
+ if art.description != ART_SEQUENCE_DUMMY_PLACEHOLDER:
557
+ continue
558
+ if art.type in ("wandb-history", "job"):
559
+ continue
560
+
561
+ try:
562
+ art.delete(delete_aliases=True)
563
+ except wandb.CommError as e:
564
+ if "cannot delete system managed artifact" in str(e):
565
+ logger.warn("Cannot delete system managed artifact")
566
+ else:
567
+ raise e
568
+
569
+ def _get_dst_art(
570
+ self, src_art: Run, entity: Optional[str] = None, project: Optional[str] = None
571
+ ) -> Artifact:
572
+ entity = coalesce(entity, src_art.entity)
573
+ project = coalesce(project, src_art.project)
574
+ name = src_art.name
575
+
576
+ return self.dst_api._artifact(f"{entity}/{project}/{name}")
577
+
578
+ def _get_run_problems(
579
+ self, src_run: Run, dst_run: Run, force_retry: bool = False
580
+ ) -> List[dict]:
581
+ problems = []
582
+
583
+ if force_retry:
584
+ problems.append("__force_retry__")
585
+
586
+ if non_matching_metadata := self._compare_run_metadata(src_run, dst_run):
587
+ problems.append("metadata:" + str(non_matching_metadata))
588
+
589
+ if non_matching_summary := self._compare_run_summary(src_run, dst_run):
590
+ problems.append("summary:" + str(non_matching_summary))
591
+
592
+ # TODO: Compare files?
593
+
594
+ return problems
595
+
596
+ def _compare_run_metadata(self, src_run: Run, dst_run: Run) -> dict:
597
+ fname = "wandb-metadata.json"
598
+ # problems = {}
599
+
600
+ src_f = src_run.file(fname)
601
+ if src_f.size == 0:
602
+ # the src was corrupted so no comparisons here will ever work
603
+ return {}
604
+
605
+ dst_f = dst_run.file(fname)
606
+ try:
607
+ contents = wandb.util.download_file_into_memory(
608
+ dst_f.url, self.dst_api.api_key
609
+ )
610
+ except urllib3.exceptions.ReadTimeoutError:
611
+ return {"Error checking": "Timeout"}
612
+ except requests.HTTPError as e:
613
+ if e.response.status_code == 404:
614
+ return {"Bad upload": f"File not found: {fname}"}
615
+ return {"http problem": f"{fname}: ({e})"}
616
+
617
+ dst_meta = wandb.wandb_sdk.lib.json_util.loads(contents)
618
+
619
+ non_matching = {}
620
+ if src_run.metadata:
621
+ for k, src_v in src_run.metadata.items():
622
+ if k not in dst_meta:
623
+ non_matching[k] = {"src": src_v, "dst": "KEY NOT FOUND"}
624
+ continue
625
+ dst_v = dst_meta[k]
626
+ if src_v != dst_v:
627
+ non_matching[k] = {"src": src_v, "dst": dst_v}
628
+
629
+ return non_matching
630
+
631
+ def _compare_run_summary(self, src_run: Run, dst_run: Run) -> dict:
632
+ non_matching = {}
633
+ for k, src_v in src_run.summary.items():
634
+ # These won't match between systems and that's ok
635
+ if isinstance(src_v, str) and src_v.startswith("wandb-client-artifact://"):
636
+ continue
637
+ if k in ("_wandb", "_runtime"):
638
+ continue
639
+
640
+ src_v = _recursive_cast_to_dict(src_v)
641
+
642
+ dst_v = dst_run.summary.get(k)
643
+ dst_v = _recursive_cast_to_dict(dst_v)
644
+
645
+ if isinstance(src_v, dict) and isinstance(dst_v, dict):
646
+ for kk, sv in src_v.items():
647
+ # These won't match between systems and that's ok
648
+ if isinstance(sv, str) and sv.startswith(
649
+ "wandb-client-artifact://"
650
+ ):
651
+ continue
652
+ dv = dst_v.get(kk)
653
+ if not _almost_equal(sv, dv):
654
+ non_matching[f"{k}-{kk}"] = {"src": sv, "dst": dv}
655
+ else:
656
+ if not _almost_equal(src_v, dst_v):
657
+ non_matching[k] = {"src": src_v, "dst": dst_v}
658
+
659
+ return non_matching
660
+
661
+ def _collect_failed_artifact_sequences(self) -> Iterable[ArtifactSequence]:
662
+ if (df := _read_ndjson(ARTIFACT_ERRORS_FNAME)) is None:
663
+ logger.debug(f"{ARTIFACT_ERRORS_FNAME=} is empty, returning nothing")
664
+ return
665
+
666
+ unique_failed_sequences = df[
667
+ ["src_entity", "src_project", "name", "type"]
668
+ ].unique()
669
+
670
+ for row in unique_failed_sequences.iter_rows(named=True):
671
+ entity = row["src_entity"]
672
+ project = row["src_project"]
673
+ name = row["name"]
674
+ _type = row["type"]
675
+
676
+ art_name = f"{entity}/{project}/{name}"
677
+ arts = self.src_api.artifacts(_type, art_name)
678
+ arts = sorted(arts, key=lambda a: int(a.version.lstrip("v")))
679
+ arts = sorted(arts, key=lambda a: a.type)
680
+
681
+ yield ArtifactSequence(arts, entity, project, _type, name)
682
+
683
+ def _cleanup_dummy_runs(
684
+ self,
685
+ *,
686
+ namespaces: Optional[Iterable[Namespace]] = None,
687
+ api: Optional[Api] = None,
688
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
689
+ ) -> None:
690
+ api = coalesce(api, self.dst_api)
691
+ namespaces = coalesce(namespaces, self._all_namespaces())
692
+
693
+ for ns in namespaces:
694
+ if remapping and ns in remapping:
695
+ ns = remapping[ns]
696
+
697
+ logger.debug(f"Cleaning up, {ns=}")
698
+ try:
699
+ runs = list(
700
+ api.runs(ns.path, filters={"displayName": RUN_DUMMY_PLACEHOLDER})
701
+ )
702
+ except ValueError as e:
703
+ if "Could not find project" in str(e):
704
+ logger.error("Could not find project, does it exist?")
705
+ continue
706
+
707
+ for run in runs:
708
+ logger.debug(f"Deleting dummy {run=}")
709
+ run.delete(delete_artifacts=False)
710
+
711
+ def _import_report(
712
+ self, report: Report, *, namespace: Optional[Namespace] = None
713
+ ) -> None:
714
+ """Import one wandb.Report.
715
+
716
+ Use `namespace` to specify alternate settings like where the report should be uploaded
717
+ """
718
+ if namespace is None:
719
+ namespace = Namespace(report.entity, report.project)
720
+
721
+ entity = coalesce(namespace.entity, report.entity)
722
+ project = coalesce(namespace.project, report.project)
723
+ name = report.name
724
+ title = report.title
725
+ description = report.description
726
+
727
+ api = self.dst_api
728
+
729
+ # We shouldn't need to upsert the project for every report
730
+ logger.debug(f"Upserting {entity=}/{project=}")
731
+ try:
732
+ api.create_project(project, entity)
733
+ except requests.exceptions.HTTPError as e:
734
+ if e.response.status_code != 409:
735
+ logger.warn(f"Issue upserting {entity=}/{project=}, {e=}")
736
+
737
+ logger.debug(f"Upserting report {entity=}, {project=}, {name=}, {title=}")
738
+ api.client.execute(
739
+ wr.report.UPSERT_VIEW,
740
+ variable_values={
741
+ "id": None, # Is there any benefit for this to be the same as default report?
742
+ "name": name,
743
+ "entityName": entity,
744
+ "projectName": project,
745
+ "description": description,
746
+ "displayName": title,
747
+ "type": "runs",
748
+ "spec": json.dumps(report.spec),
749
+ },
750
+ )
751
+
752
+ def _use_artifact_sequence(
753
+ self,
754
+ sequence: ArtifactSequence,
755
+ *,
756
+ namespace: Optional[Namespace] = None,
757
+ ):
758
+ if namespace is None:
759
+ namespace = Namespace(sequence.entity, sequence.project)
760
+
761
+ settings_override = {
762
+ "api_key": self.dst_api_key,
763
+ "base_url": self.dst_base_url,
764
+ "resume": "true",
765
+ "resumed": True,
766
+ }
767
+ logger.debug(f"Using artifact sequence with {settings_override=}, {namespace=}")
768
+
769
+ send_manager_config = internal.SendManagerConfig(use_artifacts=True)
770
+
771
+ for art in sequence:
772
+ if (used_by := art.used_by()) is None:
773
+ continue
774
+
775
+ for wandb_run in used_by:
776
+ run = WandbRun(wandb_run, **self.run_api_kwargs)
777
+
778
+ internal.send_run(
779
+ run,
780
+ overrides=namespace.send_manager_overrides,
781
+ settings_override=settings_override,
782
+ config=send_manager_config,
783
+ )
784
+
785
+ def import_runs(
786
+ self,
787
+ *,
788
+ namespaces: Optional[Iterable[Namespace]] = None,
789
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
790
+ parallel: bool = True,
791
+ incremental: bool = True,
792
+ max_workers: Optional[int] = None,
793
+ limit: Optional[int] = None,
794
+ metadata: bool = True,
795
+ files: bool = True,
796
+ media: bool = True,
797
+ code: bool = True,
798
+ history: bool = True,
799
+ summary: bool = True,
800
+ terminal_output: bool = True,
801
+ ):
802
+ logger.info("START: Import runs")
803
+
804
+ logger.info("Setting up for import")
805
+ _create_files_if_not_exists()
806
+ _clear_fname(RUN_ERRORS_FNAME)
807
+
808
+ logger.info("Collecting runs")
809
+ runs = list(self._collect_runs(namespaces=namespaces, limit=limit))
810
+
811
+ logger.info(f"Validating runs, {len(runs)=}")
812
+ self._validate_runs(
813
+ runs,
814
+ skip_previously_validated=incremental,
815
+ remapping=remapping,
816
+ )
817
+
818
+ logger.info("Collecting failed runs")
819
+ runs = list(self._collect_failed_runs())
820
+
821
+ logger.info(f"Importing runs, {len(runs)=}")
822
+
823
+ def _import_run_wrapped(run):
824
+ namespace = Namespace(run.entity(), run.project())
825
+ if remapping is not None and namespace in remapping:
826
+ namespace = remapping[namespace]
827
+
828
+ config = internal.SendManagerConfig(
829
+ metadata=metadata,
830
+ files=files,
831
+ media=media,
832
+ code=code,
833
+ history=history,
834
+ summary=summary,
835
+ terminal_output=terminal_output,
836
+ )
837
+
838
+ logger.debug(f"Importing {run=}, {namespace=}, {config=}")
839
+ self._import_run(run, namespace=namespace, config=config)
840
+ logger.debug(f"Finished importing {run=}, {namespace=}, {config=}")
841
+
842
+ for_each(_import_run_wrapped, runs, max_workers=max_workers, parallel=parallel)
843
+ logger.info("END: Importing runs")
844
+
845
+ def import_reports(
846
+ self,
847
+ *,
848
+ namespaces: Optional[Iterable[Namespace]] = None,
849
+ limit: Optional[int] = None,
850
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
851
+ ):
852
+ logger.info("START: Importing reports")
853
+
854
+ logger.info("Collecting reports")
855
+ reports = self._collect_reports(namespaces=namespaces, limit=limit)
856
+
857
+ logger.info("Importing reports")
858
+
859
+ def _import_report_wrapped(report):
860
+ namespace = Namespace(report.entity, report.project)
861
+ if remapping is not None and namespace in remapping:
862
+ namespace = remapping[namespace]
863
+
864
+ logger.debug(f"Importing {report=}, {namespace=}")
865
+ self._import_report(report, namespace=namespace)
866
+ logger.debug(f"Finished importing {report=}, {namespace=}")
867
+
868
+ for_each(_import_report_wrapped, reports)
869
+
870
+ logger.info("END: Importing reports")
871
+
872
+ def import_artifact_sequences(
873
+ self,
874
+ *,
875
+ namespaces: Optional[Iterable[Namespace]] = None,
876
+ incremental: bool = True,
877
+ max_workers: Optional[int] = None,
878
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
879
+ ):
880
+ """Import all artifact sequences from `namespaces`.
881
+
882
+ Note: There is a known bug with the AWS backend where artifacts > 2048MB will fail to upload. This seems to be related to multipart uploads, but we don't have a fix yet.
883
+ """
884
+ logger.info("START: Importing artifact sequences")
885
+ _clear_fname(ARTIFACT_ERRORS_FNAME)
886
+
887
+ logger.info("Collecting artifact sequences")
888
+ seqs = list(self._collect_artifact_sequences(namespaces=namespaces))
889
+
890
+ logger.info("Validating artifact sequences")
891
+ self._validate_artifact_sequences(
892
+ seqs,
893
+ incremental=incremental,
894
+ remapping=remapping,
895
+ )
896
+
897
+ logger.info("Collecting failed artifact sequences")
898
+ seqs = list(self._collect_failed_artifact_sequences())
899
+
900
+ logger.info(f"Importing artifact sequences, {len(seqs)=}")
901
+
902
+ def _import_artifact_sequence_wrapped(seq):
903
+ namespace = Namespace(seq.entity, seq.project)
904
+ if remapping is not None and namespace in remapping:
905
+ namespace = remapping[namespace]
906
+
907
+ logger.debug(f"Importing artifact sequence {seq=}, {namespace=}")
908
+ self._import_artifact_sequence(seq, namespace=namespace)
909
+ logger.debug(f"Finished importing artifact sequence {seq=}, {namespace=}")
910
+
911
+ for_each(_import_artifact_sequence_wrapped, seqs, max_workers=max_workers)
912
+
913
+ # it's safer to just use artifact on all seqs to make sure we don't miss anything
914
+ # For seqs that have already been used, this is a no-op.
915
+ logger.debug(f"Using artifact sequences, {len(seqs)=}")
916
+
917
+ def _use_artifact_sequence_wrapped(seq):
918
+ namespace = Namespace(seq.entity, seq.project)
919
+ if remapping is not None and namespace in remapping:
920
+ namespace = remapping[namespace]
921
+
922
+ logger.debug(f"Using artifact sequence {seq=}, {namespace=}")
923
+ self._use_artifact_sequence(seq, namespace=namespace)
924
+ logger.debug(f"Finished using artifact sequence {seq=}, {namespace=}")
925
+
926
+ for_each(_use_artifact_sequence_wrapped, seqs, max_workers=max_workers)
927
+
928
+ # Artifacts whose parent runs have been deleted should have that run deleted in the
929
+ # destination as well
930
+
931
+ logger.info("Cleaning up dummy runs")
932
+ self._cleanup_dummy_runs(
933
+ namespaces=namespaces,
934
+ remapping=remapping,
935
+ )
936
+
937
+ logger.info("END: Importing artifact sequences")
938
+
939
+ def import_all(
940
+ self,
941
+ *,
942
+ runs: bool = True,
943
+ artifacts: bool = True,
944
+ reports: bool = True,
945
+ namespaces: Optional[Iterable[Namespace]] = None,
946
+ incremental: bool = True,
947
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
948
+ ):
949
+ logger.info(f"START: Importing all, {runs=}, {artifacts=}, {reports=}")
950
+ if runs:
951
+ self.import_runs(
952
+ namespaces=namespaces,
953
+ incremental=incremental,
954
+ remapping=remapping,
955
+ )
956
+
957
+ if reports:
958
+ self.import_reports(
959
+ namespaces=namespaces,
960
+ remapping=remapping,
961
+ )
962
+
963
+ if artifacts:
964
+ self.import_artifact_sequences(
965
+ namespaces=namespaces,
966
+ incremental=incremental,
967
+ remapping=remapping,
968
+ )
969
+
970
+ logger.info("END: Importing all")
971
+
972
+ def _validate_run(
973
+ self,
974
+ src_run: Run,
975
+ *,
976
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
977
+ ) -> None:
978
+ namespace = Namespace(src_run.entity, src_run.project)
979
+ if remapping is not None and namespace in remapping:
980
+ namespace = remapping[namespace]
981
+
982
+ dst_entity = namespace.entity
983
+ dst_project = namespace.project
984
+ run_id = src_run.id
985
+
986
+ try:
987
+ dst_run = self.dst_api.run(f"{dst_entity}/{dst_project}/{run_id}")
988
+ except wandb.CommError:
989
+ problems = [f"run does not exist in dst at {dst_entity=}/{dst_project=}"]
990
+ else:
991
+ problems = self._get_run_problems(src_run, dst_run)
992
+
993
+ d = {
994
+ "src_entity": src_run.entity,
995
+ "src_project": src_run.project,
996
+ "dst_entity": dst_entity,
997
+ "dst_project": dst_project,
998
+ "run_id": run_id,
999
+ }
1000
+ if problems:
1001
+ d["problems"] = problems
1002
+ fname = RUN_ERRORS_FNAME
1003
+ else:
1004
+ fname = RUN_SUCCESSES_FNAME
1005
+
1006
+ with filelock.FileLock("runs.lock"):
1007
+ with open(fname, "a") as f:
1008
+ f.write(json.dumps(d) + "\n")
1009
+
1010
+ def _filter_previously_checked_runs(
1011
+ self,
1012
+ runs: Iterable[Run],
1013
+ *,
1014
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
1015
+ ) -> Iterable[Run]:
1016
+ if (df := _read_ndjson(RUN_SUCCESSES_FNAME)) is None:
1017
+ logger.debug(f"{RUN_SUCCESSES_FNAME=} is empty, yielding all runs")
1018
+ yield from runs
1019
+ return
1020
+
1021
+ data = []
1022
+ for r in runs:
1023
+ namespace = Namespace(r.entity, r.project)
1024
+ if remapping is not None and namespace in remapping:
1025
+ namespace = remapping[namespace]
1026
+
1027
+ data.append(
1028
+ {
1029
+ "src_entity": r.entity,
1030
+ "src_project": r.project,
1031
+ "dst_entity": namespace.entity,
1032
+ "dst_project": namespace.project,
1033
+ "run_id": r.id,
1034
+ "data": r,
1035
+ }
1036
+ )
1037
+ df2 = pl.DataFrame(data)
1038
+ logger.debug(f"Starting with {len(runs)=} in namespaces")
1039
+
1040
+ results = df2.join(
1041
+ df,
1042
+ how="anti",
1043
+ on=["src_entity", "src_project", "dst_entity", "dst_project", "run_id"],
1044
+ )
1045
+ logger.debug(f"After filtering out already successful runs, {len(results)=}")
1046
+
1047
+ if not results.is_empty():
1048
+ results = results.filter(~results["run_id"].is_null())
1049
+ results = results.unique(
1050
+ ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"]
1051
+ )
1052
+
1053
+ for r in results.iter_rows(named=True):
1054
+ yield r["data"]
1055
+
1056
+ def _validate_artifact(
1057
+ self,
1058
+ src_art: Artifact,
1059
+ dst_entity: str,
1060
+ dst_project: str,
1061
+ download_files_and_compare: bool = False,
1062
+ check_entries_are_downloadable: bool = True,
1063
+ ):
1064
+ problems = []
1065
+
1066
+ # These patterns of artifacts are special and should not be validated
1067
+ ignore_patterns = [
1068
+ r"^job-(.*?)\.py(:v\d+)?$",
1069
+ # r"^run-.*-history(?:\:v\d+)?$$",
1070
+ ]
1071
+ for pattern in ignore_patterns:
1072
+ if re.search(pattern, src_art.name):
1073
+ return (src_art, dst_entity, dst_project, problems)
1074
+
1075
+ try:
1076
+ dst_art = self._get_dst_art(src_art, dst_entity, dst_project)
1077
+ except Exception:
1078
+ problems.append("destination artifact not found")
1079
+ return (src_art, dst_entity, dst_project, problems)
1080
+
1081
+ try:
1082
+ logger.debug("Comparing artifact manifests")
1083
+ except Exception as e:
1084
+ problems.append(
1085
+ f"Problem getting problems! problem with {src_art.entity=}, {src_art.project=}, {src_art.name=} {e=}"
1086
+ )
1087
+ else:
1088
+ problems += validation._compare_artifact_manifests(src_art, dst_art)
1089
+
1090
+ if check_entries_are_downloadable:
1091
+ # validation._check_entries_are_downloadable(src_art)
1092
+ validation._check_entries_are_downloadable(dst_art)
1093
+
1094
+ if download_files_and_compare:
1095
+ logger.debug(f"Downloading {src_art=}")
1096
+ try:
1097
+ src_dir = _download_art(src_art, root=f"{SRC_ART_PATH}/{src_art.name}")
1098
+ except requests.HTTPError as e:
1099
+ problems.append(
1100
+ f"Invalid download link for src {src_art.entity=}, {src_art.project=}, {src_art.name=}, {e}"
1101
+ )
1102
+
1103
+ logger.debug(f"Downloading {dst_art=}")
1104
+ try:
1105
+ dst_dir = _download_art(dst_art, root=f"{DST_ART_PATH}/{dst_art.name}")
1106
+ except requests.HTTPError as e:
1107
+ problems.append(
1108
+ f"Invalid download link for dst {dst_art.entity=}, {dst_art.project=}, {dst_art.name=}, {e}"
1109
+ )
1110
+ else:
1111
+ logger.debug(f"Comparing artifact dirs {src_dir=}, {dst_dir=}")
1112
+ if problem := validation._compare_artifact_dirs(src_dir, dst_dir):
1113
+ problems.append(problem)
1114
+
1115
+ return (src_art, dst_entity, dst_project, problems)
1116
+
1117
+ def _validate_runs(
1118
+ self,
1119
+ runs: Iterable[WandbRun],
1120
+ *,
1121
+ skip_previously_validated: bool = True,
1122
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
1123
+ ):
1124
+ base_runs = [r.run for r in runs]
1125
+ if skip_previously_validated:
1126
+ base_runs = list(
1127
+ self._filter_previously_checked_runs(
1128
+ base_runs,
1129
+ remapping=remapping,
1130
+ )
1131
+ )
1132
+
1133
+ def _validate_run(run):
1134
+ logger.debug(f"Validating {run=}")
1135
+ self._validate_run(run, remapping=remapping)
1136
+ logger.debug(f"Finished validating {run=}")
1137
+
1138
+ for_each(_validate_run, base_runs)
1139
+
1140
+ def _collect_failed_runs(self):
1141
+ if (df := _read_ndjson(RUN_ERRORS_FNAME)) is None:
1142
+ logger.debug(f"{RUN_ERRORS_FNAME=} is empty, returning nothing")
1143
+ return
1144
+
1145
+ unique_failed_runs = df[
1146
+ ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"]
1147
+ ].unique()
1148
+
1149
+ for row in unique_failed_runs.iter_rows(named=True):
1150
+ src_entity = row["src_entity"]
1151
+ src_project = row["src_project"]
1152
+ # dst_entity = row["dst_entity"]
1153
+ # dst_project = row["dst_project"]
1154
+ run_id = row["run_id"]
1155
+
1156
+ run = self.src_api.run(f"{src_entity}/{src_project}/{run_id}")
1157
+ yield WandbRun(run, **self.run_api_kwargs)
1158
+
1159
+ def _filter_previously_checked_artifacts(self, seqs: Iterable[ArtifactSequence]):
1160
+ if (df := _read_ndjson(ARTIFACT_SUCCESSES_FNAME)) is None:
1161
+ logger.info(
1162
+ f"{ARTIFACT_SUCCESSES_FNAME=} is empty, yielding all artifact sequences"
1163
+ )
1164
+ for seq in seqs:
1165
+ yield from seq.artifacts
1166
+ return
1167
+
1168
+ for seq in seqs:
1169
+ for art in seq:
1170
+ try:
1171
+ logged_by = _get_run_or_dummy_from_art(art, self.src_api)
1172
+ except requests.HTTPError as e:
1173
+ logger.error(f"Failed to get run, skipping: {art=}, {e=}")
1174
+ continue
1175
+
1176
+ if art.type == "wandb-history" and isinstance(logged_by, _DummyRun):
1177
+ logger.debug(f"Skipping history artifact {art=}")
1178
+ # We can never upload valid history for a deleted run, so skip it
1179
+ continue
1180
+
1181
+ entity = art.entity
1182
+ project = art.project
1183
+ _type = art.type
1184
+ name, ver = _get_art_name_ver(art)
1185
+
1186
+ filtered_df = df.filter(
1187
+ (df["src_entity"] == entity)
1188
+ & (df["src_project"] == project)
1189
+ & (df["name"] == name)
1190
+ & (df["version"] == ver)
1191
+ & (df["type"] == _type)
1192
+ )
1193
+
1194
+ # not in file, so not verified yet, don't filter out
1195
+ if len(filtered_df) == 0:
1196
+ yield art
1197
+
1198
+ def _validate_artifact_sequences(
1199
+ self,
1200
+ seqs: Iterable[ArtifactSequence],
1201
+ *,
1202
+ incremental: bool = True,
1203
+ download_files_and_compare: bool = False,
1204
+ check_entries_are_downloadable: bool = True,
1205
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
1206
+ ):
1207
+ if incremental:
1208
+ logger.info("Validating in incremental mode")
1209
+
1210
+ def filtered_sequences():
1211
+ for seq in seqs:
1212
+ if not seq.artifacts:
1213
+ continue
1214
+
1215
+ art = seq.artifacts[0]
1216
+ try:
1217
+ logged_by = _get_run_or_dummy_from_art(art, self.src_api)
1218
+ except requests.HTTPError as e:
1219
+ logger.error(
1220
+ f"Validate Artifact http error: {art.entity=}, {art.project=}, {art.name=}, {e=}"
1221
+ )
1222
+ continue
1223
+
1224
+ if art.type == "wandb-history" and isinstance(logged_by, _DummyRun):
1225
+ # We can never upload valid history for a deleted run, so skip it
1226
+ continue
1227
+
1228
+ yield seq
1229
+
1230
+ artifacts = self._filter_previously_checked_artifacts(filtered_sequences())
1231
+ else:
1232
+ logger.info("Validating in non-incremental mode")
1233
+ artifacts = [art for seq in seqs for art in seq.artifacts]
1234
+
1235
+ def _validate_artifact_wrapped(args):
1236
+ art, entity, project = args
1237
+ if (
1238
+ remapping is not None
1239
+ and (namespace := Namespace(entity, project)) in remapping
1240
+ ):
1241
+ remapped_ns = remapping[namespace]
1242
+ entity = remapped_ns.entity
1243
+ project = remapped_ns.project
1244
+
1245
+ logger.debug(f"Validating {art=}, {entity=}, {project=}")
1246
+ result = self._validate_artifact(
1247
+ art,
1248
+ entity,
1249
+ project,
1250
+ download_files_and_compare=download_files_and_compare,
1251
+ check_entries_are_downloadable=check_entries_are_downloadable,
1252
+ )
1253
+ logger.debug(f"Finished validating {art=}, {entity=}, {project=}")
1254
+ return result
1255
+
1256
+ args = ((art, art.entity, art.project) for art in artifacts)
1257
+ art_problems = for_each(_validate_artifact_wrapped, args)
1258
+ for art, dst_entity, dst_project, problems in art_problems:
1259
+ name, ver = _get_art_name_ver(art)
1260
+ d = {
1261
+ "src_entity": art.entity,
1262
+ "src_project": art.project,
1263
+ "dst_entity": dst_entity,
1264
+ "dst_project": dst_project,
1265
+ "name": name,
1266
+ "version": ver,
1267
+ "type": art.type,
1268
+ }
1269
+
1270
+ if problems:
1271
+ d["problems"] = problems
1272
+ fname = ARTIFACT_ERRORS_FNAME
1273
+ else:
1274
+ fname = ARTIFACT_SUCCESSES_FNAME
1275
+
1276
+ with open(fname, "a") as f:
1277
+ f.write(json.dumps(d) + "\n")
1278
+
1279
+ def _collect_runs(
1280
+ self,
1281
+ *,
1282
+ namespaces: Optional[Iterable[Namespace]] = None,
1283
+ limit: Optional[int] = None,
1284
+ skip_ids: Optional[List[str]] = None,
1285
+ start_date: Optional[str] = None,
1286
+ api: Optional[Api] = None,
1287
+ ) -> Iterable[WandbRun]:
1288
+ api = coalesce(api, self.src_api)
1289
+ namespaces = coalesce(namespaces, self._all_namespaces())
1290
+
1291
+ filters: Dict[str, Any] = {}
1292
+ if skip_ids is not None:
1293
+ filters["name"] = {"$nin": skip_ids}
1294
+ if start_date is not None:
1295
+ filters["createdAt"] = {"$gte": start_date}
1296
+
1297
+ def _runs():
1298
+ for ns in namespaces:
1299
+ logger.debug(f"Collecting runs from {ns=}")
1300
+ for run in api.runs(ns.path, filters=filters):
1301
+ yield WandbRun(run, **self.run_api_kwargs)
1302
+
1303
+ runs = itertools.islice(_runs(), limit)
1304
+ yield from runs
1305
+
1306
+ def _all_namespaces(
1307
+ self, *, entity: Optional[str] = None, api: Optional[Api] = None
1308
+ ):
1309
+ api = coalesce(api, self.src_api)
1310
+ entity = coalesce(entity, api.default_entity)
1311
+ projects = api.projects(entity)
1312
+ for p in projects:
1313
+ yield Namespace(p.entity, p.name)
1314
+
1315
+ def _collect_reports(
1316
+ self,
1317
+ *,
1318
+ namespaces: Optional[Iterable[Namespace]] = None,
1319
+ limit: Optional[int] = None,
1320
+ api: Optional[Api] = None,
1321
+ ):
1322
+ api = coalesce(api, self.src_api)
1323
+ namespaces = coalesce(namespaces, self._all_namespaces())
1324
+
1325
+ wandb.login(key=self.src_api_key, host=self.src_base_url)
1326
+
1327
+ def reports():
1328
+ for ns in namespaces:
1329
+ for r in api.reports(ns.path):
1330
+ yield wr.Report.from_url(r.url, api=api)
1331
+
1332
+ yield from itertools.islice(reports(), limit)
1333
+
1334
+ def _collect_artifact_sequences(
1335
+ self,
1336
+ *,
1337
+ namespaces: Optional[Iterable[Namespace]] = None,
1338
+ limit: Optional[int] = None,
1339
+ api: Optional[Api] = None,
1340
+ ):
1341
+ api = coalesce(api, self.src_api)
1342
+ namespaces = coalesce(namespaces, self._all_namespaces())
1343
+
1344
+ def artifact_sequences():
1345
+ for ns in namespaces:
1346
+ logger.debug(f"Collecting artifact sequences from {ns=}")
1347
+ types = []
1348
+ try:
1349
+ types = [t for t in api.artifact_types(ns.path)]
1350
+ except Exception as e:
1351
+ logger.error(f"Failed to get artifact types {e=}")
1352
+
1353
+ for t in types:
1354
+ collections = []
1355
+
1356
+ # Skip history because it's really for run history
1357
+ if t.name == "wandb-history":
1358
+ continue
1359
+
1360
+ try:
1361
+ collections = t.collections()
1362
+ except Exception as e:
1363
+ logger.error(f"Failed to get artifact collections {e=}")
1364
+
1365
+ for c in collections:
1366
+ if c.is_sequence():
1367
+ yield ArtifactSequence.from_collection(c)
1368
+
1369
+ seqs = itertools.islice(artifact_sequences(), limit)
1370
+ unique_sequences = {seq.identifier: seq for seq in seqs}
1371
+ yield from unique_sequences.values()
1372
+
1373
+
1374
+ def _get_art_name_ver(art: Artifact) -> Tuple[str, int]:
1375
+ name, ver = art.name.split(":v")
1376
+ return name, int(ver)
1377
+
1378
+
1379
+ def _make_dummy_art(name: str, _type: str, ver: int):
1380
+ art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE)
1381
+ art._type = _type
1382
+ art._description = ART_SEQUENCE_DUMMY_PLACEHOLDER
1383
+
1384
+ p = Path(ART_DUMMY_PLACEHOLDER_PATH)
1385
+ p.mkdir(parents=True, exist_ok=True)
1386
+
1387
+ # dummy file with different name to prevent dedupe
1388
+ fname = p / str(ver)
1389
+ with open(fname, "w"):
1390
+ pass
1391
+ art.add_file(fname)
1392
+
1393
+ return art
1394
+
1395
+
1396
+ def _make_groups_of_artifacts(seq: ArtifactSequence, start: int = 0):
1397
+ prev_ver = start - 1
1398
+ for art in seq:
1399
+ name, ver = _get_art_name_ver(art)
1400
+
1401
+ # If there's a gap between versions, fill with dummy artifacts
1402
+ if ver - prev_ver > 1:
1403
+ yield [_make_dummy_art(name, art.type, v) for v in range(prev_ver + 1, ver)]
1404
+
1405
+ # Then yield the actual artifact
1406
+ # Must always be a list of one artifact to guarantee ordering
1407
+ yield [art]
1408
+ prev_ver = ver
1409
+
1410
+
1411
+ def _recursive_cast_to_dict(obj):
1412
+ if isinstance(obj, list):
1413
+ return [_recursive_cast_to_dict(item) for item in obj]
1414
+ elif isinstance(obj, dict) or hasattr(obj, "items"):
1415
+ new_dict = {}
1416
+ for key, value in obj.items():
1417
+ new_dict[key] = _recursive_cast_to_dict(value)
1418
+ return new_dict
1419
+ else:
1420
+ return obj
1421
+
1422
+
1423
+ def _almost_equal(x, y, eps=1e-6):
1424
+ if isinstance(x, dict) and isinstance(y, dict):
1425
+ if x.keys() != y.keys():
1426
+ return False
1427
+ return all(_almost_equal(x[k], y[k], eps) for k in x)
1428
+
1429
+ if isinstance(x, numbers.Number) and isinstance(y, numbers.Number):
1430
+ return abs(x - y) < eps
1431
+
1432
+ if type(x) is not type(y):
1433
+ return False
1434
+
1435
+ return x == y
1436
+
1437
+
1438
+ @dataclass
1439
+ class _DummyUser:
1440
+ username: str = ""
1441
+
1442
+
1443
+ @dataclass
1444
+ class _DummyRun:
1445
+ entity: str = ""
1446
+ project: str = ""
1447
+ run_id: str = RUN_DUMMY_PLACEHOLDER
1448
+ id: str = RUN_DUMMY_PLACEHOLDER
1449
+ display_name: str = RUN_DUMMY_PLACEHOLDER
1450
+ notes: str = ""
1451
+ url: str = ""
1452
+ group: str = ""
1453
+ created_at: str = "2000-01-01"
1454
+ user: _DummyUser = field(default_factory=_DummyUser)
1455
+ tags: list = field(default_factory=list)
1456
+ summary: dict = field(default_factory=dict)
1457
+ config: dict = field(default_factory=dict)
1458
+
1459
+ def files(self):
1460
+ return []
1461
+
1462
+
1463
+ def _read_ndjson(fname: str) -> Optional[pl.DataFrame]:
1464
+ try:
1465
+ df = pl.read_ndjson(fname)
1466
+ except FileNotFoundError:
1467
+ return None
1468
+ except RuntimeError as e:
1469
+ # No runs previously checked
1470
+ if "empty string is not a valid JSON value" in str(e):
1471
+ return None
1472
+ if "error parsing ndjson" in str(e):
1473
+ return None
1474
+ raise e
1475
+
1476
+ return df
1477
+
1478
+
1479
+ def _get_run_or_dummy_from_art(art: Artifact, api=None):
1480
+ run = None
1481
+
1482
+ try:
1483
+ run = art.logged_by()
1484
+ except ValueError as e:
1485
+ logger.warn(
1486
+ f"Can't log artifact because run doesn't exist, {art=}, {run=}, {e=}"
1487
+ )
1488
+
1489
+ if run is not None:
1490
+ return run
1491
+
1492
+ query = gql(
1493
+ """
1494
+ query ArtifactCreatedBy(
1495
+ $id: ID!
1496
+ ) {
1497
+ artifact(id: $id) {
1498
+ createdBy {
1499
+ ... on Run {
1500
+ name
1501
+ project {
1502
+ name
1503
+ entityName
1504
+ }
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+ """
1510
+ )
1511
+ response = api.client.execute(query, variable_values={"id": art.id})
1512
+ creator = response.get("artifact", {}).get("createdBy", {})
1513
+ run = _DummyRun(
1514
+ entity=art.entity,
1515
+ project=art.project,
1516
+ run_id=creator.get("name", RUN_DUMMY_PLACEHOLDER),
1517
+ id=creator.get("name", RUN_DUMMY_PLACEHOLDER),
1518
+ )
1519
+ return run
1520
+
1521
+
1522
+ def _clear_fname(fname: str) -> None:
1523
+ old_fname = f"{internal.ROOT_DIR}/{fname}"
1524
+ new_fname = f"{internal.ROOT_DIR}/prev_{fname}"
1525
+
1526
+ logger.debug(f"Moving {old_fname=} to {new_fname=}")
1527
+ try:
1528
+ shutil.copy2(old_fname, new_fname)
1529
+ except FileNotFoundError:
1530
+ # this is just to make a copy of the last iteration, so its ok if the src doesn't exist
1531
+ pass
1532
+
1533
+ with open(fname, "w"):
1534
+ pass
1535
+
1536
+
1537
+ def _download_art(art: Artifact, root: str) -> Optional[str]:
1538
+ try:
1539
+ with patch("click.echo"):
1540
+ return art.download(root=root, skip_cache=True)
1541
+ except Exception as e:
1542
+ logger.error(f"Error downloading artifact {art=}, {e=}")
1543
+
1544
+
1545
+ def _clone_art(art: Artifact, root: Optional[str] = None):
1546
+ if root is None:
1547
+ # Currently, we would only ever clone a src artifact to move it to dst.
1548
+ root = f"{SRC_ART_PATH}/{art.name}"
1549
+
1550
+ if (path := _download_art(art, root=root)) is None:
1551
+ raise ValueError(f"Problem downloading {art=}")
1552
+
1553
+ name, _ = art.name.split(":v")
1554
+
1555
+ # Hack: skip naming validation check for wandb-* types
1556
+ new_art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE)
1557
+ new_art._type = art.type
1558
+ new_art._created_at = art.created_at
1559
+
1560
+ new_art._aliases = art.aliases
1561
+ new_art._description = art.description
1562
+
1563
+ with patch("click.echo"):
1564
+ new_art.add_dir(path)
1565
+
1566
+ return new_art
1567
+
1568
+
1569
+ def _create_files_if_not_exists() -> None:
1570
+ fnames = [
1571
+ ARTIFACT_ERRORS_FNAME,
1572
+ ARTIFACT_SUCCESSES_FNAME,
1573
+ RUN_ERRORS_FNAME,
1574
+ RUN_SUCCESSES_FNAME,
1575
+ ]
1576
+
1577
+ for fname in fnames:
1578
+ logger.debug(f"Creating {fname=} if not exists")
1579
+ with open(fname, "a"):
1580
+ pass
1581
+
1582
+
1583
+ def _merge_dfs(dfs: List[pl.DataFrame]) -> pl.DataFrame:
1584
+ # Ensure there are DataFrames in the list
1585
+ if len(dfs) == 0:
1586
+ return pl.DataFrame()
1587
+
1588
+ if len(dfs) == 1:
1589
+ return dfs[0]
1590
+
1591
+ merged_df = dfs[0]
1592
+ for df in dfs[1:]:
1593
+ merged_df = merged_df.join(df, how="outer", on=["_step"])
1594
+ col_pairs = [
1595
+ (c, f"{c}_right")
1596
+ for c in merged_df.columns
1597
+ if f"{c}_right" in merged_df.columns
1598
+ ]
1599
+ for col, right in col_pairs:
1600
+ new_col = merged_df[col].fill_null(merged_df[right])
1601
+ merged_df = merged_df.with_columns(new_col).drop(right)
1602
+
1603
+ return merged_df
vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.52 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/history.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/runs.cpython-310.pyc ADDED
Binary file (29.3 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/users.cpython-310.pyc ADDED
Binary file (4.07 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/public/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/apis/reports/v2/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import wandb
2
+
3
+ try:
4
+ from wandb_workspaces.reports.v2 import * # noqa: F403
5
+ except ImportError:
6
+ wandb.termerror(
7
+ "Failed to import wandb_workspaces. To edit reports programmatically, please install it using `pip install wandb[workspaces]`."
8
+ )
vllm/lib/python3.10/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (430 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/wandb/integration/cohere/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __all__ = ("autolog",)
2
+
3
+ from .cohere import autolog
vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (227 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-310.pyc ADDED
Binary file (560 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/resolver.cpython-310.pyc ADDED
Binary file (9.53 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/cohere/cohere.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from wandb.sdk.integration_utils.auto_logging import AutologAPI
4
+
5
+ from .resolver import CohereRequestResponseResolver
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ autolog = AutologAPI(
11
+ name="Cohere",
12
+ symbols=(
13
+ "Client.generate",
14
+ "Client.chat",
15
+ "Client.classify",
16
+ "Client.summarize",
17
+ "Client.rerank",
18
+ ),
19
+ resolver=CohereRequestResponseResolver(),
20
+ telemetry_feature="cohere_autolog",
21
+ )
vllm/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from datetime import datetime
3
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
4
+
5
+ import wandb
6
+ from wandb.sdk.integration_utils.auto_logging import Response
7
+ from wandb.sdk.lib.runid import generate_id
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def subset_dict(
13
+ original_dict: Dict[str, Any], keys_subset: Sequence[str]
14
+ ) -> Dict[str, Any]:
15
+ """Create a subset of a dictionary using a subset of keys.
16
+
17
+ :param original_dict: The original dictionary.
18
+ :param keys_subset: The subset of keys to extract.
19
+ :return: A dictionary containing only the specified keys.
20
+ """
21
+ return {key: original_dict[key] for key in keys_subset if key in original_dict}
22
+
23
+
24
+ def reorder_and_convert_dict_list_to_table(
25
+ data: List[Dict[str, Any]], order: List[str]
26
+ ) -> Tuple[List[str], List[List[Any]]]:
27
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
28
+
29
+ :param data: A list of dictionaries.
30
+ :param order: A list of keys specifying the desired order for specific dictionaries. The remaining dictionaries will be ordered based on their original order.
31
+ :return: A pair of column names and corresponding values.
32
+ """
33
+ final_columns = []
34
+ keys_present = set()
35
+
36
+ # First, add all ordered keys to the final columns
37
+ for key in order:
38
+ if key not in keys_present:
39
+ final_columns.append(key)
40
+ keys_present.add(key)
41
+
42
+ # Then, add any keys present in the dictionaries but not in the order
43
+ for d in data:
44
+ for key in d:
45
+ if key not in keys_present:
46
+ final_columns.append(key)
47
+ keys_present.add(key)
48
+
49
+ # Then, construct the table of values
50
+ values = []
51
+ for d in data:
52
+ row = []
53
+ for key in final_columns:
54
+ row.append(d.get(key, None))
55
+ values.append(row)
56
+
57
+ return final_columns, values
58
+
59
+
60
+ def flatten_dict(
61
+ dictionary: Dict[str, Any], parent_key: str = "", sep: str = "-"
62
+ ) -> Dict[str, Any]:
63
+ """Flatten a nested dictionary, joining keys using a specified separator.
64
+
65
+ :param dictionary: The dictionary to flatten.
66
+ :param parent_key: The base key to prepend to each key.
67
+ :param sep: The separator to use when joining keys.
68
+ :return: A flattened dictionary.
69
+ """
70
+ flattened_dict = {}
71
+ for key, value in dictionary.items():
72
+ new_key = f"{parent_key}{sep}{key}" if parent_key else key
73
+ if isinstance(value, dict):
74
+ flattened_dict.update(flatten_dict(value, new_key, sep=sep))
75
+ else:
76
+ flattened_dict[new_key] = value
77
+ return flattened_dict
78
+
79
+
80
+ def collect_common_keys(list_of_dicts: List[Dict[str, Any]]) -> Dict[str, List[Any]]:
81
+ """Collect the common keys of a list of dictionaries. For each common key, put its values into a list in the order they appear in the original dictionaries.
82
+
83
+ :param list_of_dicts: The list of dictionaries to inspect.
84
+ :return: A dictionary with each common key and its corresponding list of values.
85
+ """
86
+ common_keys = set.intersection(*map(set, list_of_dicts))
87
+ common_dict = {key: [] for key in common_keys}
88
+ for d in list_of_dicts:
89
+ for key in common_keys:
90
+ common_dict[key].append(d[key])
91
+ return common_dict
92
+
93
+
94
+ class CohereRequestResponseResolver:
95
+ """Class to resolve the request/response from the Cohere API and convert it to a dictionary that can be logged."""
96
+
97
+ def __call__(
98
+ self,
99
+ args: Sequence[Any],
100
+ kwargs: Dict[str, Any],
101
+ response: Response,
102
+ start_time: float,
103
+ time_elapsed: float,
104
+ ) -> Optional[Dict[str, Any]]:
105
+ """Process the response from the Cohere API and convert it to a dictionary that can be logged.
106
+
107
+ :param args: The arguments of the original function.
108
+ :param kwargs: The keyword arguments of the original function.
109
+ :param response: The response from the Cohere API.
110
+ :param start_time: The start time of the request.
111
+ :param time_elapsed: The time elapsed for the request.
112
+ :return: A dictionary containing the parsed response and timing information.
113
+ """
114
+ try:
115
+ # Each of the different endpoints map to one specific response type
116
+ # We want to 'type check' the response without directly importing the packages type
117
+ # It may make more sense to pass the invoked symbol from the AutologAPI instead
118
+ response_type = str(type(response)).split("'")[1].split(".")[-1]
119
+
120
+ # Initialize parsed_response to None to handle the case where the response type is unsupported
121
+ parsed_response = None
122
+ if response_type == "Generations":
123
+ parsed_response = self._resolve_generate_response(response)
124
+ # TODO: Remove hard-coded default model name
125
+ table_column_order = [
126
+ "start_time",
127
+ "query_id",
128
+ "model",
129
+ "prompt",
130
+ "text",
131
+ "token_likelihoods",
132
+ "likelihood",
133
+ "time_elapsed_(seconds)",
134
+ "end_time",
135
+ ]
136
+ default_model = "command"
137
+ elif response_type == "Chat":
138
+ parsed_response = self._resolve_chat_response(response)
139
+ table_column_order = [
140
+ "start_time",
141
+ "query_id",
142
+ "model",
143
+ "conversation_id",
144
+ "response_id",
145
+ "query",
146
+ "text",
147
+ "prompt",
148
+ "preamble",
149
+ "chat_history",
150
+ "chatlog",
151
+ "time_elapsed_(seconds)",
152
+ "end_time",
153
+ ]
154
+ default_model = "command"
155
+ elif response_type == "Classifications":
156
+ parsed_response = self._resolve_classify_response(response)
157
+ kwargs = self._resolve_classify_kwargs(kwargs)
158
+ table_column_order = [
159
+ "start_time",
160
+ "query_id",
161
+ "model",
162
+ "id",
163
+ "input",
164
+ "prediction",
165
+ "confidence",
166
+ "time_elapsed_(seconds)",
167
+ "end_time",
168
+ ]
169
+ default_model = "embed-english-v2.0"
170
+ elif response_type == "SummarizeResponse":
171
+ parsed_response = self._resolve_summarize_response(response)
172
+ table_column_order = [
173
+ "start_time",
174
+ "query_id",
175
+ "model",
176
+ "response_id",
177
+ "text",
178
+ "additional_command",
179
+ "summary",
180
+ "time_elapsed_(seconds)",
181
+ "end_time",
182
+ "length",
183
+ "format",
184
+ ]
185
+ default_model = "summarize-xlarge"
186
+ elif response_type == "Reranking":
187
+ parsed_response = self._resolve_rerank_response(response)
188
+ table_column_order = [
189
+ "start_time",
190
+ "query_id",
191
+ "model",
192
+ "id",
193
+ "query",
194
+ "top_n",
195
+ # This is a nested dict key that got flattened
196
+ "document-text",
197
+ "relevance_score",
198
+ "index",
199
+ "time_elapsed_(seconds)",
200
+ "end_time",
201
+ ]
202
+ default_model = "rerank-english-v2.0"
203
+ else:
204
+ logger.info(f"Unsupported Cohere response object: {response}")
205
+
206
+ return self._resolve(
207
+ args,
208
+ kwargs,
209
+ parsed_response,
210
+ start_time,
211
+ time_elapsed,
212
+ response_type,
213
+ table_column_order,
214
+ default_model,
215
+ )
216
+ except Exception as e:
217
+ logger.warning(f"Failed to resolve request/response: {e}")
218
+ return None
219
+
220
+ # These helper functions process the response from different endpoints of the Cohere API.
221
+ # Since the response objects for different endpoints have different structures,
222
+ # we need different logic to process them.
223
+
224
+ def _resolve_generate_response(self, response: Response) -> List[Dict[str, Any]]:
225
+ return_list = []
226
+ for _response in response:
227
+ # Built in Cohere.*.Generations function to color token_likelihoods and return a dict of response data
228
+ _response_dict = _response._visualize_helper()
229
+ try:
230
+ _response_dict["token_likelihoods"] = wandb.Html(
231
+ _response_dict["token_likelihoods"]
232
+ )
233
+ except (KeyError, ValueError):
234
+ pass
235
+ return_list.append(_response_dict)
236
+
237
+ return return_list
238
+
239
+ def _resolve_chat_response(self, response: Response) -> List[Dict[str, Any]]:
240
+ return [
241
+ subset_dict(
242
+ response.__dict__,
243
+ [
244
+ "response_id",
245
+ "generation_id",
246
+ "query",
247
+ "text",
248
+ "conversation_id",
249
+ "prompt",
250
+ "chatlog",
251
+ "preamble",
252
+ ],
253
+ )
254
+ ]
255
+
256
+ def _resolve_classify_response(self, response: Response) -> List[Dict[str, Any]]:
257
+ # The labels key is a dict returning the scores for the classification probability for each label provided
258
+ # We flatten this nested dict for ease of consumption in the wandb UI
259
+ return [flatten_dict(_response.__dict__) for _response in response]
260
+
261
+ def _resolve_classify_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
262
+ # Example texts look strange when rendered in Wandb UI as it is a list of text and label
263
+ # We extract each value into its own column
264
+ example_texts = []
265
+ example_labels = []
266
+ for example in kwargs["examples"]:
267
+ example_texts.append(example.text)
268
+ example_labels.append(example.label)
269
+ kwargs.pop("examples")
270
+ kwargs["example_texts"] = example_texts
271
+ kwargs["example_labels"] = example_labels
272
+ return kwargs
273
+
274
+ def _resolve_summarize_response(self, response: Response) -> List[Dict[str, Any]]:
275
+ return [{"response_id": response.id, "summary": response.summary}]
276
+
277
+ def _resolve_rerank_response(self, response: Response) -> List[Dict[str, Any]]:
278
+ # The documents key contains a dict containing the content of the document which is at least "text"
279
+ # We flatten this nested dict for ease of consumption in the wandb UI
280
+ flattened_response_dicts = [
281
+ flatten_dict(_response.__dict__) for _response in response
282
+ ]
283
+ # ReRank returns each document provided a top_n value so we aggregate into one view so users can paginate a row
284
+ # As opposed to each row being one of the top_n responses
285
+ return_dict = collect_common_keys(flattened_response_dicts)
286
+ return_dict["id"] = response.id
287
+ return [return_dict]
288
+
289
+ def _resolve(
290
+ self,
291
+ args: Sequence[Any],
292
+ kwargs: Dict[str, Any],
293
+ parsed_response: List[Dict[str, Any]],
294
+ start_time: float,
295
+ time_elapsed: float,
296
+ response_type: str,
297
+ table_column_order: List[str],
298
+ default_model: str,
299
+ ) -> Dict[str, Any]:
300
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
301
+
302
+ :param args: The arguments passed to the API client.
303
+ :param kwargs: The keyword arguments passed to the API client.
304
+ :param parsed_response: The parsed response from the API.
305
+ :param start_time: The start time of the API request.
306
+ :param time_elapsed: The time elapsed during the API request.
307
+ :param response_type: The type of the API response.
308
+ :param table_column_order: The desired order of columns in the resulting table.
309
+ :param default_model: The default model to use if not specified in the response.
310
+ :return: A dictionary containing the formatted response.
311
+ """
312
+ # Args[0] is the client object where we can grab specific metadata about the underlying API status
313
+ query_id = generate_id(length=16)
314
+ parsed_args = subset_dict(
315
+ args[0].__dict__,
316
+ ["api_version", "batch_size", "max_retries", "num_workers", "timeout"],
317
+ )
318
+
319
+ start_time_dt = datetime.fromtimestamp(start_time)
320
+ end_time_dt = datetime.fromtimestamp(start_time + time_elapsed)
321
+
322
+ timings = {
323
+ "start_time": start_time_dt,
324
+ "end_time": end_time_dt,
325
+ "time_elapsed_(seconds)": time_elapsed,
326
+ }
327
+
328
+ packed_data = []
329
+ for _parsed_response in parsed_response:
330
+ _packed_dict = {
331
+ "query_id": query_id,
332
+ **kwargs,
333
+ **_parsed_response,
334
+ **timings,
335
+ **parsed_args,
336
+ }
337
+ if "model" not in _packed_dict:
338
+ _packed_dict["model"] = default_model
339
+ packed_data.append(_packed_dict)
340
+
341
+ columns, data = reorder_and_convert_dict_list_to_table(
342
+ packed_data, table_column_order
343
+ )
344
+
345
+ request_response_table = wandb.Table(data=data, columns=columns)
346
+
347
+ return {f"{response_type}": request_response_table}
vllm/lib/python3.10/site-packages/wandb/integration/fastai/__init__.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hooks that add fast.ai v1 Learners to Weights & Biases through a callback.
2
+
3
+ Requested logged data can be configured through the callback constructor.
4
+
5
+ Examples:
6
+ WandbCallback can be used when initializing the Learner::
7
+
8
+ ```
9
+ from wandb.fastai import WandbCallback
10
+ [...]
11
+ learn = Learner(data, ..., callback_fns=WandbCallback)
12
+ learn.fit(epochs)
13
+ ```
14
+
15
+ Custom parameters can be given using functools.partial::
16
+
17
+ ```
18
+ from wandb.fastai import WandbCallback
19
+ from functools import partial
20
+ [...]
21
+ learn = Learner(data, ..., callback_fns=partial(WandbCallback, ...))
22
+ learn.fit(epochs)
23
+ ```
24
+
25
+ Finally, it is possible to use WandbCallback only when starting
26
+ training. In this case it must be instantiated::
27
+
28
+ ```
29
+ learn.fit(..., callbacks=WandbCallback(learn))
30
+ ```
31
+
32
+ or, with custom parameters::
33
+
34
+ ```
35
+ learn.fit(..., callbacks=WandbCallback(learn, ...))
36
+ ```
37
+ """
38
+
39
+ import random
40
+ import sys
41
+ from pathlib import Path
42
+ from typing import Any, Literal, Optional
43
+
44
+ import fastai
45
+ from fastai.callbacks import TrackerCallback
46
+
47
+ import wandb
48
+ from wandb.sdk.lib import ipython
49
+
50
+ try:
51
+ import matplotlib
52
+
53
+ if not ipython.in_jupyter():
54
+ matplotlib.use("Agg") # non-interactive backend (avoid tkinter issues)
55
+ import matplotlib.pyplot as plt
56
+ except ImportError:
57
+ wandb.termwarn("matplotlib required if logging sample image predictions")
58
+
59
+
60
+ class WandbCallback(TrackerCallback):
61
+ """Callback for saving model topology, losses & metrics.
62
+
63
+ Optionally logs weights, gradients, sample predictions and best trained model.
64
+
65
+ Args:
66
+ learn (fastai.basic_train.Learner): the fast.ai learner to hook.
67
+ log (str): "gradients", "parameters", "all", or None. Losses & metrics are always logged.
68
+ save_model (bool): save model at the end of each epoch. It will also load best model at the end of training.
69
+ monitor (str): metric to monitor for saving best model. None uses default TrackerCallback monitor value.
70
+ mode (str): "auto", "min" or "max" to compare "monitor" values and define best model.
71
+ input_type (str): "images" or None. Used to display sample predictions.
72
+ validation_data (list): data used for sample predictions if input_type is set.
73
+ predictions (int): number of predictions to make if input_type is set and validation_data is None.
74
+ seed (int): initialize random generator for sample predictions if input_type is set and validation_data is None.
75
+ """
76
+
77
+ # Record if watch has been called previously (even in another instance)
78
+ _watch_called = False
79
+
80
+ def __init__(
81
+ self,
82
+ learn: "fastai.basic_train.Learner",
83
+ log: Optional[Literal["gradients", "parameters", "all"]] = "gradients",
84
+ save_model: bool = True,
85
+ monitor: Optional[str] = None,
86
+ mode: Literal["auto", "min", "max"] = "auto",
87
+ input_type: Optional[Literal["images"]] = None,
88
+ validation_data: Optional[list] = None,
89
+ predictions: int = 36,
90
+ seed: int = 12345,
91
+ ) -> None:
92
+ # Check if wandb.init has been called
93
+ if wandb.run is None:
94
+ raise ValueError("You must call wandb.init() before WandbCallback()")
95
+
96
+ # Adapted from fast.ai "SaveModelCallback"
97
+ if monitor is None:
98
+ # use default TrackerCallback monitor value
99
+ super().__init__(learn, mode=mode)
100
+ else:
101
+ super().__init__(learn, monitor=monitor, mode=mode)
102
+ self.save_model = save_model
103
+ self.model_path = Path(wandb.run.dir) / "bestmodel.pth"
104
+
105
+ self.log = log
106
+ self.input_type = input_type
107
+ self.best = None
108
+
109
+ # Select items for sample predictions to see evolution along training
110
+ self.validation_data = validation_data
111
+ if input_type and not self.validation_data:
112
+ wandb_random = random.Random(seed) # For repeatability
113
+ predictions = min(predictions, len(learn.data.valid_ds))
114
+ indices = wandb_random.sample(range(len(learn.data.valid_ds)), predictions)
115
+ self.validation_data = [learn.data.valid_ds[i] for i in indices]
116
+
117
+ def on_train_begin(self, **kwargs: Any) -> None:
118
+ """Call watch method to log model topology, gradients & weights."""
119
+ # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
120
+ super().on_train_begin()
121
+
122
+ # Ensure we don't call "watch" multiple times
123
+ if not WandbCallback._watch_called:
124
+ WandbCallback._watch_called = True
125
+
126
+ # Logs model topology and optionally gradients and weights
127
+ wandb.watch(self.learn.model, log=self.log)
128
+
129
+ def on_epoch_end(
130
+ self, epoch: int, smooth_loss: float, last_metrics: list, **kwargs: Any
131
+ ) -> None:
132
+ """Log training loss, validation loss and custom metrics & log prediction samples & save model."""
133
+ if self.save_model:
134
+ # Adapted from fast.ai "SaveModelCallback"
135
+ current = self.get_monitor_value()
136
+ if current is not None and self.operator(current, self.best):
137
+ wandb.termlog(
138
+ f"Better model found at epoch {epoch} with {self.monitor} value: {current}."
139
+ )
140
+ self.best = current
141
+
142
+ # Save within wandb folder
143
+ with self.model_path.open("wb") as model_file:
144
+ self.learn.save(model_file)
145
+
146
+ # Log sample predictions if learn.predict is available
147
+ if self.validation_data:
148
+ try:
149
+ self._wandb_log_predictions()
150
+ except FastaiError as e:
151
+ wandb.termwarn(e.message)
152
+ self.validation_data = None # prevent from trying again on next loop
153
+ except Exception as e:
154
+ wandb.termwarn(f"Unable to log prediction samples.\n{e}")
155
+ self.validation_data = None # prevent from trying again on next loop
156
+
157
+ # Log losses & metrics
158
+ # Adapted from fast.ai "CSVLogger"
159
+ logs = {
160
+ name: stat
161
+ for name, stat in list(
162
+ zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics)
163
+ )
164
+ }
165
+ wandb.log(logs)
166
+
167
+ def on_train_end(self, **kwargs: Any) -> None:
168
+ """Load the best model."""
169
+ if self.save_model:
170
+ # Adapted from fast.ai "SaveModelCallback"
171
+ if self.model_path.is_file():
172
+ with self.model_path.open("rb") as model_file:
173
+ self.learn.load(model_file, purge=False)
174
+ wandb.termlog(f"Loaded best saved model from {self.model_path}")
175
+
176
+ def _wandb_log_predictions(self) -> None:
177
+ """Log prediction samples."""
178
+ pred_log = []
179
+
180
+ if self.validation_data is None:
181
+ return
182
+
183
+ for x, y in self.validation_data:
184
+ try:
185
+ pred = self.learn.predict(x)
186
+ except Exception:
187
+ raise FastaiError(
188
+ 'Unable to run "predict" method from Learner to log prediction samples.'
189
+ )
190
+
191
+ # scalar -> likely to be a category
192
+ # tensor of dim 1 -> likely to be multicategory
193
+ if not pred[1].shape or pred[1].dim() == 1:
194
+ pred_log.append(
195
+ wandb.Image(
196
+ x.data,
197
+ caption=f"Ground Truth: {y}\nPrediction: {pred[0]}",
198
+ )
199
+ )
200
+
201
+ # most vision datasets have a "show" function we can use
202
+ elif hasattr(x, "show"):
203
+ # log input data
204
+ pred_log.append(wandb.Image(x.data, caption="Input data", grouping=3))
205
+
206
+ # log label and prediction
207
+ for im, capt in ((pred[0], "Prediction"), (y, "Ground Truth")):
208
+ # Resize plot to image resolution
209
+ # from https://stackoverflow.com/a/13714915
210
+ my_dpi = 100
211
+ fig = plt.figure(frameon=False, dpi=my_dpi)
212
+ h, w = x.size
213
+ fig.set_size_inches(w / my_dpi, h / my_dpi)
214
+ ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
215
+ ax.set_axis_off()
216
+ fig.add_axes(ax)
217
+
218
+ # Superpose label or prediction to input image
219
+ x.show(ax=ax, y=im)
220
+ pred_log.append(wandb.Image(fig, caption=capt))
221
+ plt.close(fig)
222
+
223
+ # likely to be an image
224
+ elif hasattr(y, "shape") and (
225
+ (len(y.shape) == 2) or (len(y.shape) == 3 and y.shape[0] in [1, 3, 4])
226
+ ):
227
+ pred_log.extend(
228
+ [
229
+ wandb.Image(x.data, caption="Input data", grouping=3),
230
+ wandb.Image(pred[0].data, caption="Prediction"),
231
+ wandb.Image(y.data, caption="Ground Truth"),
232
+ ]
233
+ )
234
+
235
+ # we just log input data
236
+ else:
237
+ pred_log.append(wandb.Image(x.data, caption="Input data"))
238
+
239
+ wandb.log({"Prediction Samples": pred_log}, commit=False)
240
+
241
+
242
+ class FastaiError(wandb.Error):
243
+ pass
vllm/lib/python3.10/site-packages/wandb/integration/fastai/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (7.46 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/gym/__init__.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import sys
3
+ from typing import Literal, Optional
4
+
5
+ import wandb
6
+ import wandb.util
7
+
8
+ _gym_version_lt_0_26: Optional[bool] = None
9
+ _gymnasium_version_lt_1_0_0: Optional[bool] = None
10
+
11
+ _required_error_msg = (
12
+ "Couldn't import the gymnasium python package, "
13
+ "install with `pip install gymnasium`"
14
+ )
15
+ GymLib = Literal["gym", "gymnasium"]
16
+
17
+
18
+ def monitor():
19
+ """Monitor a gym environment.
20
+
21
+ Supports both gym and gymnasium.
22
+ """
23
+ gym_lib: Optional[GymLib] = None
24
+
25
+ # gym is not maintained anymore, gymnasium is the drop-in replacement - prefer it
26
+ if wandb.util.get_module("gymnasium") is not None:
27
+ gym_lib = "gymnasium"
28
+ elif wandb.util.get_module("gym") is not None:
29
+ gym_lib = "gym"
30
+
31
+ if gym_lib is None:
32
+ raise wandb.Error(_required_error_msg)
33
+
34
+ global _gym_version_lt_0_26
35
+ global _gymnasium_version_lt_1_0_0
36
+
37
+ if _gym_version_lt_0_26 is None or _gymnasium_version_lt_1_0_0 is None:
38
+ if gym_lib == "gym":
39
+ import gym
40
+ else:
41
+ import gymnasium as gym # type: ignore
42
+
43
+ from wandb.util import parse_version
44
+
45
+ gym_lib_version = parse_version(gym.__version__)
46
+ _gym_version_lt_0_26 = gym_lib_version < parse_version("0.26.0")
47
+ _gymnasium_version_lt_1_0_0 = gym_lib_version < parse_version("1.0.0a1")
48
+
49
+ path = "path" # Default path
50
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
51
+ vcr_recorder_attribute = "RecordVideo"
52
+ wrappers = wandb.util.get_module(
53
+ f"{gym_lib}.wrappers",
54
+ required=_required_error_msg,
55
+ )
56
+ recorder = getattr(wrappers, vcr_recorder_attribute)
57
+ else:
58
+ vcr = wandb.util.get_module(
59
+ f"{gym_lib}.wrappers.monitoring.video_recorder",
60
+ required=_required_error_msg,
61
+ )
62
+ # Breaking change in gym 0.26.0
63
+ if _gym_version_lt_0_26:
64
+ vcr_recorder_attribute = "ImageEncoder"
65
+ recorder = getattr(vcr, vcr_recorder_attribute)
66
+ path = "output_path" # Override path for older gym versions
67
+ else:
68
+ vcr_recorder_attribute = "VideoRecorder"
69
+ recorder = getattr(vcr, vcr_recorder_attribute)
70
+
71
+ recorder.orig_close = recorder.close
72
+
73
+ def close(self):
74
+ recorder.orig_close(self)
75
+ if not self.enabled:
76
+ return
77
+ if wandb.run:
78
+ m = re.match(r".+(video\.\d+).+", getattr(self, path))
79
+ key = m.group(1) if m else "videos"
80
+ wandb.log({key: wandb.Video(getattr(self, path))})
81
+
82
+ def del_(self):
83
+ self.orig_close()
84
+
85
+ if not _gym_version_lt_0_26:
86
+ recorder.__del__ = del_
87
+ recorder.close = close
88
+
89
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
90
+ wrapper_name = vcr_recorder_attribute
91
+ else:
92
+ wrapper_name = f"monitoring.video_recorder.{vcr_recorder_attribute}"
93
+
94
+ wandb.patched["gym"].append(
95
+ [
96
+ f"{gym_lib}.wrappers.{wrapper_name}",
97
+ "close",
98
+ ]
99
+ )
vllm/lib/python3.10/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.08 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/huggingface/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __all__ = ("autolog",)
2
+
3
+ from .huggingface import autolog
vllm/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/huggingface.cpython-310.pyc ADDED
Binary file (564 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/huggingface/resolver.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from datetime import datetime
4
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
5
+
6
+ import pytz
7
+
8
+ import wandb
9
+ from wandb.sdk.integration_utils.auto_logging import Response
10
+ from wandb.sdk.lib.runid import generate_id
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ SUPPORTED_PIPELINE_TASKS = [
15
+ "text-classification",
16
+ "sentiment-analysis",
17
+ "question-answering",
18
+ "summarization",
19
+ "translation",
20
+ "text2text-generation",
21
+ "text-generation",
22
+ # "conversational",
23
+ ]
24
+
25
+ PIPELINES_WITH_TOP_K = [
26
+ "text-classification",
27
+ "sentiment-analysis",
28
+ "question-answering",
29
+ ]
30
+
31
+
32
+ class HuggingFacePipelineRequestResponseResolver:
33
+ """Resolver for HuggingFace's pipeline request and responses, providing necessary data transformations and formatting.
34
+
35
+ This is based off (from wandb.sdk.integration_utils.auto_logging import RequestResponseResolver)
36
+ """
37
+
38
+ autolog_id = None
39
+
40
+ def __call__(
41
+ self,
42
+ args: Sequence[Any],
43
+ kwargs: Dict[str, Any],
44
+ response: Response,
45
+ start_time: float,
46
+ time_elapsed: float,
47
+ ) -> Optional[Dict[str, Any]]:
48
+ """Main call method for this class.
49
+
50
+ :param args: list of arguments
51
+ :param kwargs: dictionary of keyword arguments
52
+ :param response: the response from the request
53
+ :param start_time: time when request started
54
+ :param time_elapsed: time elapsed for the request
55
+ :returns: packed data as a dictionary for logging to wandb, None if an exception occurred
56
+ """
57
+ try:
58
+ pipe, input_data = args[:2]
59
+ task = pipe.task
60
+
61
+ # Translation tasks are in the form of `translation_x_to_y`
62
+ if task in SUPPORTED_PIPELINE_TASKS or task.startswith("translation"):
63
+ model = self._get_model(pipe)
64
+ if model is None:
65
+ return None
66
+ model_alias = model.name_or_path
67
+ timestamp = datetime.now(pytz.utc)
68
+
69
+ input_data, response = self._transform_task_specific_data(
70
+ task, input_data, response
71
+ )
72
+ formatted_data = self._format_data(task, input_data, response, kwargs)
73
+ packed_data = self._create_table(
74
+ formatted_data, model_alias, timestamp, time_elapsed
75
+ )
76
+ table_name = os.environ.get("WANDB_AUTOLOG_TABLE_NAME", f"{task}")
77
+ # TODO: Let users decide the name in a way that does not use an environment variable
78
+
79
+ return {
80
+ table_name: wandb.Table(
81
+ columns=packed_data[0], data=packed_data[1:]
82
+ )
83
+ }
84
+
85
+ logger.warning(
86
+ f"The task: `{task}` is not yet supported.\nPlease contact `wandb` to notify us if you would like support for this task"
87
+ )
88
+ except Exception as e:
89
+ logger.warning(e)
90
+ return None
91
+
92
+ # TODO: This should have a dependency on PreTrainedModel. i.e. isinstance(PreTrainedModel)
93
+ # from transformers.modeling_utils import PreTrainedModel
94
+ # We do not want this dependency explicitly in our codebase so we make a very general
95
+ # assumption about the structure of the pipeline which may have unintended consequences
96
+ def _get_model(self, pipe) -> Optional[Any]:
97
+ """Extracts model from the pipeline.
98
+
99
+ :param pipe: the HuggingFace pipeline
100
+ :returns: Model if available, None otherwise
101
+ """
102
+ model = pipe.model
103
+ try:
104
+ return model.model
105
+ except AttributeError:
106
+ logger.info(
107
+ "Model does not have a `.model` attribute. Assuming `pipe.model` is the correct model."
108
+ )
109
+ return model
110
+
111
+ @staticmethod
112
+ def _transform_task_specific_data(
113
+ task: str, input_data: Union[List[Any], Any], response: Union[List[Any], Any]
114
+ ) -> Tuple[Union[List[Any], Any], Union[List[Any], Any]]:
115
+ """Transform input and response data based on specific tasks.
116
+
117
+ :param task: the task name
118
+ :param input_data: the input data
119
+ :param response: the response data
120
+ :returns: tuple of transformed input_data and response
121
+ """
122
+ if task == "question-answering":
123
+ input_data = input_data if isinstance(input_data, list) else [input_data]
124
+ input_data = [data.__dict__ for data in input_data]
125
+ elif task == "conversational":
126
+ # We only grab the latest input/output pair from the conversation
127
+ # Logging the whole conversation renders strangely.
128
+ input_data = input_data if isinstance(input_data, list) else [input_data]
129
+ input_data = [data.__dict__["past_user_inputs"][-1] for data in input_data]
130
+
131
+ response = response if isinstance(response, list) else [response]
132
+ response = [data.__dict__["generated_responses"][-1] for data in response]
133
+ return input_data, response
134
+
135
+ def _format_data(
136
+ self,
137
+ task: str,
138
+ input_data: Union[List[Any], Any],
139
+ response: Union[List[Any], Any],
140
+ kwargs: Dict[str, Any],
141
+ ) -> List[Dict[str, Any]]:
142
+ """Formats input data, response, and kwargs into a list of dictionaries.
143
+
144
+ :param task: the task name
145
+ :param input_data: the input data
146
+ :param response: the response data
147
+ :param kwargs: dictionary of keyword arguments
148
+ :returns: list of dictionaries containing formatted data
149
+ """
150
+ input_data = input_data if isinstance(input_data, list) else [input_data]
151
+ response = response if isinstance(response, list) else [response]
152
+
153
+ formatted_data = []
154
+ for i_text, r_text in zip(input_data, response):
155
+ # Unpack single element responses for better rendering in wandb UI when it is a task without top_k
156
+ # top_k = 1 would unpack the response into a single element while top_k > 1 would be a list
157
+ # this would cause the UI to not properly concatenate the tables of the same task by omitting the elements past the first
158
+ if (
159
+ (isinstance(r_text, list))
160
+ and (len(r_text) == 1)
161
+ and task not in PIPELINES_WITH_TOP_K
162
+ ):
163
+ r_text = r_text[0]
164
+ formatted_data.append(
165
+ {"input": i_text, "response": r_text, "kwargs": kwargs}
166
+ )
167
+ return formatted_data
168
+
169
+ def _create_table(
170
+ self,
171
+ formatted_data: List[Dict[str, Any]],
172
+ model_alias: str,
173
+ timestamp: float,
174
+ time_elapsed: float,
175
+ ) -> List[List[Any]]:
176
+ """Creates a table from formatted data, model alias, timestamp, and elapsed time.
177
+
178
+ :param formatted_data: list of dictionaries containing formatted data
179
+ :param model_alias: alias of the model
180
+ :param timestamp: timestamp of the data
181
+ :param time_elapsed: time elapsed from the beginning
182
+ :returns: list of lists, representing a table of data. [0]th element = columns. [1]st element = data
183
+ """
184
+ header = [
185
+ "ID",
186
+ "Model Alias",
187
+ "Timestamp",
188
+ "Elapsed Time",
189
+ "Input",
190
+ "Response",
191
+ "Kwargs",
192
+ ]
193
+ table = [header]
194
+ autolog_id = generate_id(length=16)
195
+
196
+ for data in formatted_data:
197
+ row = [
198
+ autolog_id,
199
+ model_alias,
200
+ timestamp,
201
+ time_elapsed,
202
+ data["input"],
203
+ data["response"],
204
+ data["kwargs"],
205
+ ]
206
+ table.append(row)
207
+
208
+ self.autolog_id = autolog_id
209
+
210
+ return table
211
+
212
+ def get_latest_id(self):
213
+ return self.autolog_id
vllm/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import itertools
3
+ import textwrap
4
+ from typing import Callable, List, Mapping, Optional
5
+
6
+ import wandb
7
+
8
+ try:
9
+ from kfp import __version__ as kfp_version
10
+ from kfp.components import structures
11
+ from kfp.components._components import _create_task_factory_from_component_spec
12
+ from kfp.components._python_op import _func_to_component_spec
13
+
14
+ from wandb.util import parse_version
15
+
16
+ MIN_KFP_VERSION = "1.6.1"
17
+
18
+ if parse_version(kfp_version) < parse_version(MIN_KFP_VERSION):
19
+ wandb.termwarn(
20
+ f"Your version of kfp {kfp_version} may not work. This integration requires kfp>={MIN_KFP_VERSION}"
21
+ )
22
+
23
+ except ImportError:
24
+ wandb.termerror("kfp not found! Please `pip install kfp`")
25
+
26
+ from .wandb_logging import wandb_log
27
+
28
+ decorator_code = inspect.getsource(wandb_log)
29
+ wandb_logging_extras = f"""
30
+ import typing
31
+ from typing import NamedTuple
32
+
33
+ import collections
34
+ from collections import namedtuple
35
+
36
+ import kfp
37
+ from kfp import components
38
+ from kfp.components import InputPath, OutputPath
39
+
40
+ import wandb
41
+
42
+ {decorator_code}
43
+ """
44
+
45
+
46
+ def full_path_exists(full_func):
47
+ def get_parent_child_pairs(full_func):
48
+ components = full_func.split(".")
49
+ parents, children = [], []
50
+ for i, _ in enumerate(components[:-1], 1):
51
+ parent = ".".join(components[:i])
52
+ child = components[i]
53
+ parents.append(parent)
54
+ children.append(child)
55
+ return zip(parents, children)
56
+
57
+ for parent, child in get_parent_child_pairs(full_func):
58
+ module = wandb.util.get_module(parent)
59
+ if not module or not hasattr(module, child) or getattr(module, child) is None:
60
+ return False
61
+ return True
62
+
63
+
64
+ def patch(module_name, func):
65
+ module = wandb.util.get_module(module_name)
66
+ success = False
67
+
68
+ full_func = f"{module_name}.{func.__name__}"
69
+ if not full_path_exists(full_func):
70
+ wandb.termerror(
71
+ f"Failed to patch {module_name}.{func.__name__}! Please check if this package/module is installed!"
72
+ )
73
+ else:
74
+ wandb.patched.setdefault(module.__name__, [])
75
+ # if already patched, do not patch again
76
+ if [module, func.__name__] not in wandb.patched[module.__name__]:
77
+ setattr(module, f"orig_{func.__name__}", getattr(module, func.__name__))
78
+ setattr(module, func.__name__, func)
79
+ wandb.patched[module.__name__].append([module, func.__name__])
80
+ success = True
81
+
82
+ return success
83
+
84
+
85
+ def unpatch(module_name):
86
+ if module_name in wandb.patched:
87
+ for module, func in wandb.patched[module_name]:
88
+ setattr(module, func, getattr(module, f"orig_{func}"))
89
+ wandb.patched[module_name] = []
90
+
91
+
92
+ def unpatch_kfp():
93
+ unpatch("kfp.components")
94
+ unpatch("kfp.components._python_op")
95
+ unpatch("wandb.integration.kfp")
96
+
97
+
98
+ def patch_kfp():
99
+ to_patch = [
100
+ (
101
+ "kfp.components",
102
+ create_component_from_func,
103
+ ),
104
+ (
105
+ "kfp.components._python_op",
106
+ create_component_from_func,
107
+ ),
108
+ (
109
+ "kfp.components._python_op",
110
+ _get_function_source_definition,
111
+ ),
112
+ ("kfp.components._python_op", strip_type_hints),
113
+ ]
114
+
115
+ successes = []
116
+ for module_name, func in to_patch:
117
+ success = patch(module_name, func)
118
+ successes.append(success)
119
+ if not all(successes):
120
+ wandb.termerror(
121
+ "Failed to patch one or more kfp functions. Patching @wandb_log decorator to no-op."
122
+ )
123
+ patch("wandb.integration.kfp", wandb_log)
124
+
125
+
126
+ def wandb_log(
127
+ func=None,
128
+ # /, # py38 only
129
+ log_component_file=True,
130
+ ):
131
+ """Wrap a standard python function and log to W&B.
132
+
133
+ NOTE: Because patching failed, this decorator is a no-op.
134
+ """
135
+ from functools import wraps
136
+
137
+ def decorator(func):
138
+ @wraps(func)
139
+ def wrapper(*args, **kwargs):
140
+ return func(*args, **kwargs)
141
+
142
+ return wrapper
143
+
144
+ if func is None:
145
+ return decorator
146
+ else:
147
+ return decorator(func)
148
+
149
+
150
+ def _get_function_source_definition(func: Callable) -> str:
151
+ """Get the source code of a function.
152
+
153
+ This function is modified from KFP. The original source is below:
154
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L300-L319.
155
+ """
156
+ func_code = inspect.getsource(func)
157
+
158
+ # Function might be defined in some indented scope (e.g. in another
159
+ # function). We need to handle this and properly dedent the function source
160
+ # code
161
+ func_code = textwrap.dedent(func_code)
162
+ func_code_lines = func_code.split("\n")
163
+
164
+ # For wandb, allow decorators (so we can use the @wandb_log decorator)
165
+ func_code_lines = itertools.dropwhile(
166
+ lambda x: not (x.startswith(("def", "@wandb_log"))),
167
+ func_code_lines,
168
+ )
169
+
170
+ if not func_code_lines:
171
+ raise ValueError(
172
+ f'Failed to dedent and clean up the source of function "{func.__name__}". '
173
+ "It is probably not properly indented."
174
+ )
175
+
176
+ return "\n".join(func_code_lines)
177
+
178
+
179
+ def create_component_from_func(
180
+ func: Callable,
181
+ output_component_file: Optional[str] = None,
182
+ base_image: Optional[str] = None,
183
+ packages_to_install: Optional[List[str]] = None,
184
+ annotations: Optional[Mapping[str, str]] = None,
185
+ ):
186
+ '''Convert a Python function to a component and returns a task factory.
187
+
188
+ The returned task factory accepts arguments and returns a task object.
189
+
190
+ This function is modified from KFP. The original source is below:
191
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L998-L1110.
192
+
193
+ Args:
194
+ func: The python function to convert
195
+ 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.
196
+ 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`.
197
+ packages_to_install: Optional. List of [versioned] python packages to pip install before executing the user function.
198
+ annotations: Optional. Allows adding arbitrary key-value data to the component specification.
199
+
200
+ Returns:
201
+ A factory function with a strongly-typed signature taken from the python function.
202
+ Once called with the required arguments, the factory constructs a task instance that can run the original function in a container.
203
+
204
+ Examples:
205
+ The function name and docstring are used as component name and description. Argument and return annotations are used as component input/output types::
206
+
207
+ def add(a: float, b: float) -> float:
208
+ """Return sum of two arguments"""
209
+ return a + b
210
+
211
+
212
+ # add_op is a task factory function that creates a task object when given arguments
213
+ add_op = create_component_from_func(
214
+ func=add,
215
+ base_image="python:3.7", # Optional
216
+ output_component_file="add.component.yaml", # Optional
217
+ packages_to_install=["pandas==0.24"], # Optional
218
+ )
219
+
220
+ # The component spec can be accessed through the .component_spec attribute:
221
+ add_op.component_spec.save("add.component.yaml")
222
+
223
+ # The component function can be called with arguments to create a task:
224
+ add_task = add_op(1, 3)
225
+
226
+ # The resulting task has output references, corresponding to the component outputs.
227
+ # When the function only has a single anonymous return value, the output name is "Output":
228
+ sum_output_ref = add_task.outputs["Output"]
229
+
230
+ # These task output references can be passed to other component functions, constructing a computation graph:
231
+ task2 = add_op(sum_output_ref, 5)
232
+
233
+
234
+ :code:`create_component_from_func` function can also be used as decorator::
235
+
236
+ @create_component_from_func
237
+ def add_op(a: float, b: float) -> float:
238
+ """Return sum of two arguments"""
239
+ return a + b
240
+
241
+ To declare a function with multiple return values, use the :code:`NamedTuple` return annotation syntax::
242
+
243
+ from typing import NamedTuple
244
+
245
+
246
+ def add_multiply_two_numbers(a: float, b: float) -> NamedTuple(
247
+ "Outputs", [("sum", float), ("product", float)]
248
+ ):
249
+ """Return sum and product of two arguments"""
250
+ return (a + b, a * b)
251
+
252
+
253
+ add_multiply_op = create_component_from_func(add_multiply_two_numbers)
254
+
255
+ # The component function can be called with arguments to create a task:
256
+ add_multiply_task = add_multiply_op(1, 3)
257
+
258
+ # The resulting task has output references, corresponding to the component outputs:
259
+ sum_output_ref = add_multiply_task.outputs["sum"]
260
+
261
+ # These task output references can be passed to other component functions, constructing a computation graph:
262
+ task2 = add_multiply_op(sum_output_ref, 5)
263
+
264
+ Bigger data should be read from files and written to files.
265
+ 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.
266
+ 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.
267
+
268
+ 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.
269
+ 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.
270
+
271
+ Example of a component function declaring file input and output::
272
+
273
+ def catboost_train_classifier(
274
+ training_data_path: InputPath("CSV"), # Path to input data file of type "CSV"
275
+ trained_model_path: OutputPath(
276
+ "CatBoostModel"
277
+ ), # Path to output data file of type "CatBoostModel"
278
+ number_of_trees: int = 100, # Small output of type "Integer"
279
+ ) -> NamedTuple(
280
+ "Outputs",
281
+ [
282
+ ("Accuracy", float), # Small output of type "Float"
283
+ ("Precision", float), # Small output of type "Float"
284
+ ("JobUri", "URI"), # Small output of type "URI"
285
+ ],
286
+ ):
287
+ """Train CatBoost classification model"""
288
+ ...
289
+
290
+ return (accuracy, precision, recall)
291
+ '''
292
+ core_packages = ["wandb", "kfp"]
293
+
294
+ if not packages_to_install:
295
+ packages_to_install = core_packages
296
+ else:
297
+ packages_to_install += core_packages
298
+
299
+ component_spec = _func_to_component_spec(
300
+ func=func,
301
+ extra_code=wandb_logging_extras,
302
+ base_image=base_image,
303
+ packages_to_install=packages_to_install,
304
+ )
305
+ if annotations:
306
+ component_spec.metadata = structures.MetadataSpec(
307
+ annotations=annotations,
308
+ )
309
+
310
+ if output_component_file:
311
+ component_spec.save(output_component_file)
312
+
313
+ return _create_task_factory_from_component_spec(component_spec)
314
+
315
+
316
+ def strip_type_hints(source_code: str) -> str:
317
+ """Strip type hints from source code.
318
+
319
+ This function is modified from KFP. The original source is below:
320
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L237-L248.
321
+ """
322
+ # For wandb, do not strip type hints
323
+
324
+ # try:
325
+ # return _strip_type_hints_using_lib2to3(source_code)
326
+ # except Exception as ex:
327
+ # print('Error when stripping type annotations: ' + str(ex))
328
+
329
+ # try:
330
+ # return _strip_type_hints_using_strip_hints(source_code)
331
+ # except Exception as ex:
332
+ # print('Error when stripping type annotations: ' + str(ex))
333
+
334
+ return source_code
vllm/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
vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (247 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/fine_tuning.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/openai.cpython-310.pyc ADDED
Binary file (593 Bytes). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-310.pyc ADDED
Binary file (7.85 kB). View file
 
vllm/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import datetime
3
+ import io
4
+ import json
5
+ import os
6
+ import re
7
+ import tempfile
8
+ import time
9
+ from typing import Any, Dict, List, Optional, Tuple, Union
10
+
11
+ import wandb
12
+ from wandb import util
13
+ from wandb.data_types import Table
14
+ from wandb.sdk.lib import telemetry
15
+ from wandb.sdk.wandb_run import Run
16
+ from wandb.util import parse_version
17
+
18
+ openai = util.get_module(
19
+ name="openai",
20
+ required="This integration requires `openai`. To install, please run `pip install openai`",
21
+ lazy=False,
22
+ )
23
+
24
+ if parse_version(openai.__version__) < parse_version("1.12.0"):
25
+ raise wandb.Error(
26
+ f"This integration requires openai version 1.12.0 and above. Your current version is {openai.__version__} "
27
+ "To fix, please `pip install -U openai`"
28
+ )
29
+
30
+ from openai import OpenAI # noqa: E402
31
+ from openai.types.fine_tuning import FineTuningJob # noqa: E402
32
+ from openai.types.fine_tuning.fine_tuning_job import ( # noqa: E402
33
+ Error,
34
+ Hyperparameters,
35
+ )
36
+
37
+ np = util.get_module(
38
+ name="numpy",
39
+ required="`numpy` not installed >> This integration requires numpy! To fix, please `pip install numpy`",
40
+ lazy=False,
41
+ )
42
+
43
+ pd = util.get_module(
44
+ name="pandas",
45
+ required="`pandas` not installed >> This integration requires pandas! To fix, please `pip install pandas`",
46
+ lazy=False,
47
+ )
48
+
49
+
50
+ class WandbLogger:
51
+ """Log OpenAI fine-tunes to [Weights & Biases](https://wandb.me/openai-docs)."""
52
+
53
+ _wandb_api: Optional[wandb.Api] = None
54
+ _logged_in: bool = False
55
+ openai_client: Optional[OpenAI] = None
56
+ _run: Optional[Run] = None
57
+
58
+ @classmethod
59
+ def sync(
60
+ cls,
61
+ fine_tune_job_id: Optional[str] = None,
62
+ openai_client: Optional[OpenAI] = None,
63
+ num_fine_tunes: Optional[int] = None,
64
+ project: str = "OpenAI-Fine-Tune",
65
+ entity: Optional[str] = None,
66
+ overwrite: bool = False,
67
+ wait_for_job_success: bool = True,
68
+ log_datasets: bool = True,
69
+ model_artifact_name: str = "model-metadata",
70
+ model_artifact_type: str = "model",
71
+ **kwargs_wandb_init: Dict[str, Any],
72
+ ) -> str:
73
+ """Sync fine-tunes to Weights & Biases.
74
+
75
+ :param fine_tune_job_id: The id of the fine-tune (optional)
76
+ :param openai_client: Pass the `OpenAI()` client (optional)
77
+ :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.
78
+ :param project: Name of the project where you're sending runs. By default, it is "GPT-3".
79
+ :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.
80
+ :param overwrite: Forces logging and overwrite existing wandb run of the same fine-tune.
81
+ :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.
82
+ :param model_artifact_name: Name of the model artifact that is logged
83
+ :param model_artifact_type: Type of the model artifact that is logged
84
+ """
85
+ if openai_client is None:
86
+ openai_client = OpenAI()
87
+ cls.openai_client = openai_client
88
+
89
+ if fine_tune_job_id:
90
+ wandb.termlog("Retrieving fine-tune job...")
91
+ fine_tune = openai_client.fine_tuning.jobs.retrieve(
92
+ fine_tuning_job_id=fine_tune_job_id
93
+ )
94
+ fine_tunes = [fine_tune]
95
+ else:
96
+ # get list of fine_tune to log
97
+ fine_tunes = openai_client.fine_tuning.jobs.list()
98
+ if not fine_tunes or fine_tunes.data is None:
99
+ wandb.termwarn("No fine-tune has been retrieved")
100
+ return
101
+ # Select the `num_fine_tunes` from the `fine_tunes.data` list.
102
+ # If `num_fine_tunes` is None, it selects all items in the list (from start to end).
103
+ # If for example, `num_fine_tunes` is 5, it selects the last 5 items in the list.
104
+ # Note that the last items in the list are the latest fine-tune jobs.
105
+ fine_tunes = fine_tunes.data[
106
+ -num_fine_tunes if num_fine_tunes is not None else None :
107
+ ]
108
+
109
+ # log starting from oldest fine_tune
110
+ show_individual_warnings = (
111
+ fine_tune_job_id is not None or num_fine_tunes is not None
112
+ )
113
+ fine_tune_logged = []
114
+ for fine_tune in fine_tunes:
115
+ fine_tune_id = fine_tune.id
116
+ # check run with the given `fine_tune_id` has not been logged already
117
+ run_path = f"{project}/{fine_tune_id}"
118
+ if entity is not None:
119
+ run_path = f"{entity}/{run_path}"
120
+ wandb_run = cls._get_wandb_run(run_path)
121
+ if wandb_run:
122
+ wandb_status = wandb_run.summary.get("status")
123
+ if show_individual_warnings:
124
+ if wandb_status == "succeeded" and not overwrite:
125
+ wandb.termwarn(
126
+ f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}. "
127
+ "Use `overwrite=True` if you want to overwrite previous run"
128
+ )
129
+ elif wandb_status != "succeeded" or overwrite:
130
+ if wandb_status != "succeeded":
131
+ wandb.termwarn(
132
+ f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully"
133
+ )
134
+ wandb.termlog(
135
+ f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten"
136
+ )
137
+ overwrite = True
138
+ if wandb_status == "succeeded" and not overwrite:
139
+ return
140
+
141
+ # check if the user has not created a wandb run externally
142
+ if wandb.run is None:
143
+ cls._run = wandb.init(
144
+ job_type="fine-tune",
145
+ project=project,
146
+ entity=entity,
147
+ name=fine_tune_id,
148
+ id=fine_tune_id,
149
+ **kwargs_wandb_init,
150
+ )
151
+ else:
152
+ # if a run exits - created externally
153
+ cls._run = wandb.run
154
+
155
+ if wait_for_job_success:
156
+ fine_tune = cls._wait_for_job_success(fine_tune)
157
+
158
+ cls._log_fine_tune(
159
+ fine_tune,
160
+ project,
161
+ entity,
162
+ overwrite,
163
+ show_individual_warnings,
164
+ log_datasets,
165
+ model_artifact_name,
166
+ model_artifact_type,
167
+ **kwargs_wandb_init,
168
+ )
169
+
170
+ if not show_individual_warnings and not any(fine_tune_logged):
171
+ wandb.termwarn("No new successful fine-tunes were found")
172
+
173
+ return "🎉 wandb sync completed successfully"
174
+
175
+ @classmethod
176
+ def _wait_for_job_success(cls, fine_tune: FineTuningJob) -> FineTuningJob:
177
+ wandb.termlog("Waiting for the OpenAI fine-tuning job to finish training...")
178
+ wandb.termlog(
179
+ "To avoid blocking, you can call `WandbLogger.sync` with `wait_for_job_success=False` after OpenAI training completes."
180
+ )
181
+ while True:
182
+ if fine_tune.status == "succeeded":
183
+ wandb.termlog(
184
+ "Fine-tuning finished, logging metrics, model metadata, and run metadata to Weights & Biases"
185
+ )
186
+ return fine_tune
187
+ if fine_tune.status == "failed":
188
+ wandb.termwarn(
189
+ f"Fine-tune {fine_tune.id} has failed and will not be logged"
190
+ )
191
+ return fine_tune
192
+ if fine_tune.status == "cancelled":
193
+ wandb.termwarn(
194
+ f"Fine-tune {fine_tune.id} was cancelled and will not be logged"
195
+ )
196
+ return fine_tune
197
+ time.sleep(10)
198
+ fine_tune = cls.openai_client.fine_tuning.jobs.retrieve(
199
+ fine_tuning_job_id=fine_tune.id
200
+ )
201
+
202
+ @classmethod
203
+ def _log_fine_tune(
204
+ cls,
205
+ fine_tune: FineTuningJob,
206
+ project: str,
207
+ entity: Optional[str],
208
+ overwrite: bool,
209
+ show_individual_warnings: bool,
210
+ log_datasets: bool,
211
+ model_artifact_name: str,
212
+ model_artifact_type: str,
213
+ **kwargs_wandb_init: Dict[str, Any],
214
+ ):
215
+ fine_tune_id = fine_tune.id
216
+ status = fine_tune.status
217
+
218
+ with telemetry.context(run=cls._run) as tel:
219
+ tel.feature.openai_finetuning = True
220
+
221
+ # check run completed successfully
222
+ if status != "succeeded":
223
+ if show_individual_warnings:
224
+ wandb.termwarn(
225
+ f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged'
226
+ )
227
+ return
228
+
229
+ # check results are present
230
+ try:
231
+ results_id = fine_tune.result_files[0]
232
+ try:
233
+ encoded_results = cls.openai_client.files.content(
234
+ file_id=results_id
235
+ ).read()
236
+ results = base64.b64decode(encoded_results).decode("utf-8")
237
+ except Exception:
238
+ # attempt to read as text, works for older jobs
239
+ results = cls.openai_client.files.content(file_id=results_id).text
240
+ except openai.NotFoundError:
241
+ if show_individual_warnings:
242
+ wandb.termwarn(
243
+ f"Fine-tune {fine_tune_id} has no results and will not be logged"
244
+ )
245
+ return
246
+
247
+ # update the config
248
+ cls._run.config.update(cls._get_config(fine_tune))
249
+
250
+ # log results
251
+ df_results = pd.read_csv(io.StringIO(results))
252
+ for _, row in df_results.iterrows():
253
+ metrics = {k: v for k, v in row.items() if not np.isnan(v)}
254
+ step = metrics.pop("step")
255
+ if step is not None:
256
+ step = int(step)
257
+ cls._run.log(metrics, step=step)
258
+ fine_tuned_model = fine_tune.fine_tuned_model
259
+ if fine_tuned_model is not None:
260
+ cls._run.summary["fine_tuned_model"] = fine_tuned_model
261
+
262
+ # training/validation files and fine-tune details
263
+ cls._log_artifacts(
264
+ fine_tune,
265
+ project,
266
+ entity,
267
+ log_datasets,
268
+ overwrite,
269
+ model_artifact_name,
270
+ model_artifact_type,
271
+ )
272
+
273
+ # mark run as complete
274
+ cls._run.summary["status"] = "succeeded"
275
+
276
+ cls._run.finish()
277
+ return True
278
+
279
+ @classmethod
280
+ def _ensure_logged_in(cls):
281
+ if not cls._logged_in:
282
+ if wandb.login():
283
+ cls._logged_in = True
284
+ else:
285
+ raise Exception(
286
+ "It appears you are not currently logged in to Weights & Biases. "
287
+ "Please run `wandb login` in your terminal or `wandb.login()` in a notebook."
288
+ "When prompted, you can obtain your API key by visiting wandb.ai/authorize."
289
+ )
290
+
291
+ @classmethod
292
+ def _get_wandb_run(cls, run_path: str):
293
+ cls._ensure_logged_in()
294
+ try:
295
+ if cls._wandb_api is None:
296
+ cls._wandb_api = wandb.Api()
297
+ return cls._wandb_api.run(run_path)
298
+ except Exception:
299
+ return None
300
+
301
+ @classmethod
302
+ def _get_wandb_artifact(cls, artifact_path: str):
303
+ cls._ensure_logged_in()
304
+ try:
305
+ if cls._wandb_api is None:
306
+ cls._wandb_api = wandb.Api()
307
+ return cls._wandb_api.artifact(artifact_path)
308
+ except Exception:
309
+ return None
310
+
311
+ @classmethod
312
+ def _get_config(cls, fine_tune: FineTuningJob) -> Dict[str, Any]:
313
+ config = dict(fine_tune)
314
+ config["result_files"] = config["result_files"][0]
315
+ if config.get("created_at"):
316
+ config["created_at"] = datetime.datetime.fromtimestamp(
317
+ config["created_at"]
318
+ ).strftime("%Y-%m-%d %H:%M:%S")
319
+ if config.get("finished_at"):
320
+ config["finished_at"] = datetime.datetime.fromtimestamp(
321
+ config["finished_at"]
322
+ ).strftime("%Y-%m-%d %H:%M:%S")
323
+ if config.get("hyperparameters"):
324
+ config["hyperparameters"] = cls.sanitize(config["hyperparameters"])
325
+ if config.get("error"):
326
+ config["error"] = cls.sanitize(config["error"])
327
+ return config
328
+
329
+ @classmethod
330
+ def _unpack_hyperparameters(cls, hyperparameters: Hyperparameters):
331
+ # `Hyperparameters` object is not unpacking properly using `vars` or `__dict__`,
332
+ # vars(hyperparameters) return {n_epochs: n} only.
333
+ hyperparams = {}
334
+ try:
335
+ hyperparams["n_epochs"] = hyperparameters.n_epochs
336
+ hyperparams["batch_size"] = hyperparameters.batch_size
337
+ hyperparams["learning_rate_multiplier"] = (
338
+ hyperparameters.learning_rate_multiplier
339
+ )
340
+ except Exception:
341
+ # If unpacking fails, return the object to be logged as config
342
+ return None
343
+
344
+ return hyperparams
345
+
346
+ @staticmethod
347
+ def sanitize(input: Any) -> Union[Dict, List, str]:
348
+ valid_types = [bool, int, float, str]
349
+ if isinstance(input, (Hyperparameters, Error)):
350
+ return dict(input)
351
+ if isinstance(input, dict):
352
+ return {
353
+ k: v if type(v) in valid_types else str(v) for k, v in input.items()
354
+ }
355
+ elif isinstance(input, list):
356
+ return [v if type(v) in valid_types else str(v) for v in input]
357
+ else:
358
+ return str(input)
359
+
360
+ @classmethod
361
+ def _log_artifacts(
362
+ cls,
363
+ fine_tune: FineTuningJob,
364
+ project: str,
365
+ entity: Optional[str],
366
+ log_datasets: bool,
367
+ overwrite: bool,
368
+ model_artifact_name: str,
369
+ model_artifact_type: str,
370
+ ) -> None:
371
+ if log_datasets:
372
+ wandb.termlog("Logging training/validation files...")
373
+ # training/validation files
374
+ training_file = fine_tune.training_file if fine_tune.training_file else None
375
+ validation_file = (
376
+ fine_tune.validation_file if fine_tune.validation_file else None
377
+ )
378
+ for file, prefix, artifact_type in (
379
+ (training_file, "train", "training_files"),
380
+ (validation_file, "valid", "validation_files"),
381
+ ):
382
+ if file is not None:
383
+ cls._log_artifact_inputs(
384
+ file, prefix, artifact_type, project, entity, overwrite
385
+ )
386
+
387
+ # fine-tune details
388
+ fine_tune_id = fine_tune.id
389
+ artifact = wandb.Artifact(
390
+ model_artifact_name,
391
+ type=model_artifact_type,
392
+ metadata=dict(fine_tune),
393
+ )
394
+
395
+ with artifact.new_file("model_metadata.json", mode="w", encoding="utf-8") as f:
396
+ dict_fine_tune = dict(fine_tune)
397
+ dict_fine_tune["hyperparameters"] = cls.sanitize(
398
+ dict_fine_tune["hyperparameters"]
399
+ )
400
+ dict_fine_tune["error"] = cls.sanitize(dict_fine_tune["error"])
401
+ dict_fine_tune = cls.sanitize(dict_fine_tune)
402
+ json.dump(dict_fine_tune, f, indent=2)
403
+ cls._run.log_artifact(
404
+ artifact,
405
+ aliases=["latest", fine_tune_id],
406
+ )
407
+
408
+ @classmethod
409
+ def _log_artifact_inputs(
410
+ cls,
411
+ file_id: Optional[str],
412
+ prefix: str,
413
+ artifact_type: str,
414
+ project: str,
415
+ entity: Optional[str],
416
+ overwrite: bool,
417
+ ) -> None:
418
+ # get input artifact
419
+ artifact_name = f"{prefix}-{file_id}"
420
+ # sanitize name to valid wandb artifact name
421
+ artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name)
422
+ artifact_alias = file_id
423
+ artifact_path = f"{project}/{artifact_name}:{artifact_alias}"
424
+ if entity is not None:
425
+ artifact_path = f"{entity}/{artifact_path}"
426
+ artifact = cls._get_wandb_artifact(artifact_path)
427
+
428
+ # create artifact if file not already logged previously
429
+ if artifact is None or overwrite:
430
+ # get file content
431
+ try:
432
+ file_content = cls.openai_client.files.content(file_id=file_id)
433
+ except openai.NotFoundError:
434
+ wandb.termerror(
435
+ f"File {file_id} could not be retrieved. Make sure you have OpenAI permissions to download training/validation files"
436
+ )
437
+ return
438
+
439
+ artifact = wandb.Artifact(artifact_name, type=artifact_type)
440
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
441
+ tmp_file.write(file_content.content)
442
+ tmp_file_path = tmp_file.name
443
+ artifact.add_file(tmp_file_path, file_id)
444
+ os.unlink(tmp_file_path)
445
+
446
+ # create a Table
447
+ try:
448
+ table, n_items = cls._make_table(file_content.text)
449
+ # Add table to the artifact.
450
+ artifact.add(table, file_id)
451
+ # Add the same table to the workspace.
452
+ cls._run.log({f"{prefix}_data": table})
453
+ # Update the run config and artifact metadata
454
+ cls._run.config.update({f"n_{prefix}": n_items})
455
+ artifact.metadata["items"] = n_items
456
+ except Exception as e:
457
+ wandb.termerror(
458
+ f"Issue saving {file_id} as a Table to Artifacts, exception:\n '{e}'"
459
+ )
460
+ else:
461
+ # log number of items
462
+ cls._run.config.update({f"n_{prefix}": artifact.metadata.get("items")})
463
+
464
+ cls._run.use_artifact(artifact, aliases=["latest", artifact_alias])
465
+
466
+ @classmethod
467
+ def _make_table(cls, file_content: str) -> Tuple[Table, int]:
468
+ table = wandb.Table(columns=["role: system", "role: user", "role: assistant"])
469
+
470
+ df = pd.read_json(io.StringIO(file_content), orient="records", lines=True)
471
+ for _idx, message in df.iterrows():
472
+ messages = message.messages
473
+ assert len(messages) == 3
474
+ table.add_data(
475
+ messages[0]["content"],
476
+ messages[1]["content"],
477
+ messages[2]["content"],
478
+ )
479
+
480
+ return table, len(df)
vllm/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
+ )
vllm/lib/python3.10/site-packages/wandb/integration/openai/resolver.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import io
3
+ import logging
4
+ from dataclasses import asdict, dataclass
5
+ from typing import Any, Dict, List, Optional, Sequence
6
+
7
+ import wandb
8
+ from wandb.sdk.data_types import trace_tree
9
+ from wandb.sdk.integration_utils.auto_logging import Response
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @dataclass
15
+ class UsageMetrics:
16
+ elapsed_time: float = None
17
+ prompt_tokens: int = None
18
+ completion_tokens: int = None
19
+ total_tokens: int = None
20
+
21
+
22
+ @dataclass
23
+ class Metrics:
24
+ usage: UsageMetrics = None
25
+ stats: wandb.Table = None
26
+ trace: trace_tree.WBTraceTree = None
27
+
28
+
29
+ usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())}
30
+
31
+
32
+ class OpenAIRequestResponseResolver:
33
+ def __init__(self):
34
+ self.define_metrics_called = False
35
+
36
+ def __call__(
37
+ self,
38
+ args: Sequence[Any],
39
+ kwargs: Dict[str, Any],
40
+ response: Response,
41
+ start_time: float, # pass to comply with the protocol, but use response["created"] instead
42
+ time_elapsed: float,
43
+ ) -> Optional[Dict[str, Any]]:
44
+ request = kwargs
45
+
46
+ if not self.define_metrics_called:
47
+ # define metrics on first call
48
+ for key in usage_metric_keys:
49
+ wandb.define_metric(key, step_metric="_timestamp")
50
+ self.define_metrics_called = True
51
+
52
+ try:
53
+ if response.get("object") == "edit":
54
+ return self._resolve_edit(request, response, time_elapsed)
55
+ elif response.get("object") == "text_completion":
56
+ return self._resolve_completion(request, response, time_elapsed)
57
+ elif response.get("object") == "chat.completion":
58
+ return self._resolve_chat_completion(request, response, time_elapsed)
59
+ else:
60
+ # todo: properly treat failed requests
61
+ logger.info(
62
+ f"Unsupported OpenAI response object: {response.get('object')}"
63
+ )
64
+ except Exception as e:
65
+ logger.warning(f"Failed to resolve request/response: {e}")
66
+ return None
67
+
68
+ @staticmethod
69
+ def results_to_trace_tree(
70
+ request: Dict[str, Any],
71
+ response: Response,
72
+ results: List[trace_tree.Result],
73
+ time_elapsed: float,
74
+ ) -> trace_tree.WBTraceTree:
75
+ """Converts the request, response, and results into a trace tree.
76
+
77
+ params:
78
+ request: The request dictionary
79
+ response: The response object
80
+ results: A list of results object
81
+ time_elapsed: The time elapsed in seconds
82
+ returns:
83
+ A wandb trace tree object.
84
+ """
85
+ start_time_ms = int(round(response["created"] * 1000))
86
+ end_time_ms = start_time_ms + int(round(time_elapsed * 1000))
87
+ span = trace_tree.Span(
88
+ name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}",
89
+ attributes=dict(response), # type: ignore
90
+ start_time_ms=start_time_ms,
91
+ end_time_ms=end_time_ms,
92
+ span_kind=trace_tree.SpanKind.LLM,
93
+ results=results,
94
+ )
95
+ model_obj = {"request": request, "response": response, "_kind": "openai"}
96
+ return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj)
97
+
98
+ def _resolve_edit(
99
+ self,
100
+ request: Dict[str, Any],
101
+ response: Response,
102
+ time_elapsed: float,
103
+ ) -> Dict[str, Any]:
104
+ """Resolves the request and response objects for `openai.Edit`."""
105
+ request_str = (
106
+ f"\n\n**Instruction**: {request['instruction']}\n\n"
107
+ f"**Input**: {request['input']}\n"
108
+ )
109
+ choices = [
110
+ f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"]
111
+ ]
112
+
113
+ return self._resolve_metrics(
114
+ request=request,
115
+ response=response,
116
+ request_str=request_str,
117
+ choices=choices,
118
+ time_elapsed=time_elapsed,
119
+ )
120
+
121
+ def _resolve_completion(
122
+ self,
123
+ request: Dict[str, Any],
124
+ response: Response,
125
+ time_elapsed: float,
126
+ ) -> Dict[str, Any]:
127
+ """Resolves the request and response objects for `openai.Completion`."""
128
+ request_str = f"\n\n**Prompt**: {request['prompt']}\n"
129
+ choices = [
130
+ f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"]
131
+ ]
132
+
133
+ return self._resolve_metrics(
134
+ request=request,
135
+ response=response,
136
+ request_str=request_str,
137
+ choices=choices,
138
+ time_elapsed=time_elapsed,
139
+ )
140
+
141
+ def _resolve_chat_completion(
142
+ self,
143
+ request: Dict[str, Any],
144
+ response: Response,
145
+ time_elapsed: float,
146
+ ) -> Dict[str, Any]:
147
+ """Resolves the request and response objects for `openai.Completion`."""
148
+ prompt = io.StringIO()
149
+ for message in request["messages"]:
150
+ prompt.write(f"\n\n**{message['role']}**: {message['content']}\n")
151
+ request_str = prompt.getvalue()
152
+
153
+ choices = [
154
+ f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n"
155
+ for choice in response["choices"]
156
+ ]
157
+
158
+ return self._resolve_metrics(
159
+ request=request,
160
+ response=response,
161
+ request_str=request_str,
162
+ choices=choices,
163
+ time_elapsed=time_elapsed,
164
+ )
165
+
166
+ def _resolve_metrics(
167
+ self,
168
+ request: Dict[str, Any],
169
+ response: Response,
170
+ request_str: str,
171
+ choices: List[str],
172
+ time_elapsed: float,
173
+ ) -> Dict[str, Any]:
174
+ """Resolves the request and response objects for `openai.Completion`."""
175
+ results = [
176
+ trace_tree.Result(
177
+ inputs={"request": request_str},
178
+ outputs={"response": choice},
179
+ )
180
+ for choice in choices
181
+ ]
182
+ metrics = self._get_metrics_to_log(request, response, results, time_elapsed)
183
+ return self._convert_metrics_to_dict(metrics)
184
+
185
+ @staticmethod
186
+ def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics:
187
+ """Gets the usage stats from the response object."""
188
+ if response.get("usage"):
189
+ usage_stats = UsageMetrics(**response["usage"])
190
+ else:
191
+ usage_stats = UsageMetrics()
192
+ usage_stats.elapsed_time = time_elapsed
193
+ return usage_stats
194
+
195
+ def _get_metrics_to_log(
196
+ self,
197
+ request: Dict[str, Any],
198
+ response: Response,
199
+ results: List[Any],
200
+ time_elapsed: float,
201
+ ) -> Metrics:
202
+ model = response.get("model") or request.get("model")
203
+ usage_metrics = self._get_usage_metrics(response, time_elapsed)
204
+
205
+ usage = []
206
+ for result in results:
207
+ row = {
208
+ "request": result.inputs["request"],
209
+ "response": result.outputs["response"],
210
+ "model": model,
211
+ "start_time": datetime.datetime.fromtimestamp(response["created"]),
212
+ "end_time": datetime.datetime.fromtimestamp(
213
+ response["created"] + time_elapsed
214
+ ),
215
+ "request_id": response.get("id", None),
216
+ "api_type": response.get("api_type", "openai"),
217
+ "session_id": wandb.run.id,
218
+ }
219
+ row.update(asdict(usage_metrics))
220
+ usage.append(row)
221
+ usage_table = wandb.Table(
222
+ columns=list(usage[0].keys()),
223
+ data=[(item.values()) for item in usage],
224
+ )
225
+
226
+ trace = self.results_to_trace_tree(request, response, results, time_elapsed)
227
+
228
+ metrics = Metrics(stats=usage_table, trace=trace, usage=usage_metrics)
229
+ return metrics
230
+
231
+ @staticmethod
232
+ def _convert_metrics_to_dict(metrics: Metrics) -> Dict[str, Any]:
233
+ """Converts metrics to a dict."""
234
+ metrics_dict = {
235
+ "stats": metrics.stats,
236
+ "trace": metrics.trace,
237
+ }
238
+ usage_stats = {f"usage/{k}": v for k, v in asdict(metrics.usage).items()}
239
+ metrics_dict.update(usage_stats)
240
+ return metrics_dict
vllm/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"]