diffusers-dynamic-offloader 0.1.0rc2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ddo_native_check.py +44 -0
- ddo_vmm_bootstrap.py +142 -0
- diffusers_dynamic_offloader/__init__.py +116 -0
- diffusers_dynamic_offloader/allocation_diagnostics.py +96 -0
- diffusers_dynamic_offloader/auxiliary_sources.py +126 -0
- diffusers_dynamic_offloader/backend.py +166 -0
- diffusers_dynamic_offloader/device_cache.py +60 -0
- diffusers_dynamic_offloader/dynamic_offload.py +3919 -0
- diffusers_dynamic_offloader/float8_compile.py +77 -0
- diffusers_dynamic_offloader/float8_loading.py +130 -0
- diffusers_dynamic_offloader/host_cache.py +101 -0
- diffusers_dynamic_offloader/host_memory.py +70 -0
- diffusers_dynamic_offloader/linear_convolution.py +105 -0
- diffusers_dynamic_offloader/metrics.py +217 -0
- diffusers_dynamic_offloader/metrics_journal.py +66 -0
- diffusers_dynamic_offloader/operator_diagnostics.py +167 -0
- diffusers_dynamic_offloader/profiles.py +495 -0
- diffusers_dynamic_offloader/quantized_sources.py +58 -0
- diffusers_dynamic_offloader/timing.py +129 -0
- diffusers_dynamic_offloader/vmm_model_arena.py +277 -0
- diffusers_dynamic_offloader/vmm_weight_store.py +840 -0
- diffusers_dynamic_offloader/weight_source_metadata.py +81 -0
- diffusers_dynamic_offloader/windows_file_reader.py +106 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/METADATA +90 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/RECORD +28 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/WHEEL +5 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/licenses/LICENSE +201 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/top_level.txt +3 -0
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
"""Persistent, model-agnostic capacity profiles for Dynamic Offloader.
|
|
2
|
+
|
|
3
|
+
Profiles deliberately store observations, not executable model code. A host
|
|
4
|
+
runner supplies a stable context and records the outcome of a real workload;
|
|
5
|
+
DDO then makes that observation available to later runs on the same machine.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import uuid
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from dataclasses import dataclass, field, replace
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Mapping
|
|
22
|
+
|
|
23
|
+
import torch
|
|
24
|
+
|
|
25
|
+
DYNAMIC_OFFLOAD_PROFILE_SCHEMA_VERSION = 1
|
|
26
|
+
_PROFILE_PREFIX = "ddo-capacity-v1"
|
|
27
|
+
_SDNQ_DEFAULT_RESIDENT_CEILING_GB = 6.0
|
|
28
|
+
_SDNQ_PROBE_MIN_SAFE_BUDGET_GB = 2.0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def inspect_vmm_component(module, *, component: str = "model", module_pattern: str = ".*"):
|
|
32
|
+
"""Observe native selection on CPU/meta; no attachment or support claim.
|
|
33
|
+
|
|
34
|
+
The optional allocator package is imported only when this is requested.
|
|
35
|
+
No budget, profile file, module, source or CUDA state is modified.
|
|
36
|
+
"""
|
|
37
|
+
from .metrics import DynamicOffloadMetrics
|
|
38
|
+
|
|
39
|
+
if not isinstance(component, str) or not component.strip():
|
|
40
|
+
raise ValueError("component must be a nonempty string")
|
|
41
|
+
from ddo_vmm_allocator import inspect_model_linear_layout
|
|
42
|
+
|
|
43
|
+
return DynamicOffloadMetrics(
|
|
44
|
+
route="vmm_capacity_inspection",
|
|
45
|
+
configuration={"component": component, "module_pattern": module_pattern},
|
|
46
|
+
setup={"capacity_inspection": inspect_model_linear_layout(module, module_pattern)},
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _CudaPeakSampler:
|
|
51
|
+
"""Sample driver-visible CUDA usage while the profiled region executes."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, device: torch.device, interval_seconds: float = 0.05):
|
|
54
|
+
self.device = device
|
|
55
|
+
self.interval_seconds = interval_seconds
|
|
56
|
+
self.peak_bytes = 0
|
|
57
|
+
self._stop = threading.Event()
|
|
58
|
+
self._thread: threading.Thread | None = None
|
|
59
|
+
|
|
60
|
+
def _sample(self) -> None:
|
|
61
|
+
try:
|
|
62
|
+
free, total = torch.cuda.mem_get_info(self.device)
|
|
63
|
+
except Exception:
|
|
64
|
+
return
|
|
65
|
+
self.peak_bytes = max(self.peak_bytes, int(total - free))
|
|
66
|
+
|
|
67
|
+
def start(self) -> None:
|
|
68
|
+
self._sample()
|
|
69
|
+
|
|
70
|
+
def run() -> None:
|
|
71
|
+
while not self._stop.wait(self.interval_seconds):
|
|
72
|
+
self._sample()
|
|
73
|
+
|
|
74
|
+
self._thread = threading.Thread(target=run, name="ddo-cuda-profile", daemon=True)
|
|
75
|
+
self._thread.start()
|
|
76
|
+
|
|
77
|
+
def stop(self) -> int:
|
|
78
|
+
self._stop.set()
|
|
79
|
+
if self._thread is not None:
|
|
80
|
+
self._thread.join(timeout=self.interval_seconds * 2 + 0.1)
|
|
81
|
+
self._sample()
|
|
82
|
+
return self.peak_bytes
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _NamedProfile:
|
|
86
|
+
"""Library-owned identity, application and measurement for a named workload."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, module, config, *, component="model"):
|
|
89
|
+
self.config = config
|
|
90
|
+
self.context = {
|
|
91
|
+
"name": config.profile_name,
|
|
92
|
+
"model_class": type(module).__qualname__,
|
|
93
|
+
"identity_version": 2,
|
|
94
|
+
"execution_mode": config.execution_mode,
|
|
95
|
+
}
|
|
96
|
+
self.report = {"name": config.profile_name, "status": "disabled"}
|
|
97
|
+
# Explicit VMM component profiles must not share observations merely
|
|
98
|
+
# because two components have the same Python class/profile name.
|
|
99
|
+
# Preserve generic VMM and all existing linear/SDNQ profile identities.
|
|
100
|
+
if config.execution_mode == "vmm_fast_runtime" and component != "model":
|
|
101
|
+
if not isinstance(component, str) or not component.strip():
|
|
102
|
+
raise ValueError("VMM profile component must be a non-empty string.")
|
|
103
|
+
self.context.update(identity_version=3, component=component)
|
|
104
|
+
self.report["component"] = component
|
|
105
|
+
self._active = False
|
|
106
|
+
self._sdnq_probe_budget_gb: float | None = None
|
|
107
|
+
self._vmm_hook = None
|
|
108
|
+
|
|
109
|
+
def attach_hook(self, hook) -> None:
|
|
110
|
+
"""Associate the applied runtime so a VMM profile can take a snapshot."""
|
|
111
|
+
self._vmm_hook = hook
|
|
112
|
+
|
|
113
|
+
def prepare(self):
|
|
114
|
+
config = self.config
|
|
115
|
+
if config.build_profile and not config.profile_name.strip():
|
|
116
|
+
raise ValueError("build_profile requires a non-empty profile_name.")
|
|
117
|
+
if not config.profile_name:
|
|
118
|
+
return config
|
|
119
|
+
if config.build_profile:
|
|
120
|
+
if torch.device(config.execution_device).type != "cuda":
|
|
121
|
+
raise ValueError("Profile calibration requires a CUDA execution device.")
|
|
122
|
+
if config.execution_mode not in {"linear_runtime", "sdnq_runtime", "vmm_fast_runtime"}:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
"Profile calibration requires execution_mode='linear_runtime', 'sdnq_runtime', or 'vmm_fast_runtime'."
|
|
125
|
+
)
|
|
126
|
+
if config.execution_mode == "vmm_fast_runtime":
|
|
127
|
+
self.report["status"] = "observing_vmm_capacity"
|
|
128
|
+
self.report["profile_measurement_kind"] = "vmm_capacity"
|
|
129
|
+
return config
|
|
130
|
+
if not math.isfinite(config.profile_vram_headroom_gb) or config.profile_vram_headroom_gb < 0:
|
|
131
|
+
raise ValueError("profile_vram_headroom_gb must be finite and non-negative.")
|
|
132
|
+
self.report["status"] = "calibrating"
|
|
133
|
+
# All profile builds begin with zero residents. This preserves the
|
|
134
|
+
# established BF16 flow and gives SDNQ a real activation baseline;
|
|
135
|
+
# an SDNQ resident budget cannot safely be inferred before that
|
|
136
|
+
# workload peak is known.
|
|
137
|
+
if config.execution_mode == "sdnq_runtime":
|
|
138
|
+
print(f"[dynamic-offload] profile {config.profile_name!r}: calibrating SDNQ zero-resident baseline.")
|
|
139
|
+
print(f"[dynamic-offload] profile {config.profile_name!r}: calibrating with zero resident budget.")
|
|
140
|
+
return replace(config, resident_module_budget_gb=0.0, profile_resident_module_budget_gb=0.0)
|
|
141
|
+
if config.execution_mode == "vmm_fast_runtime":
|
|
142
|
+
record = load_dynamic_offload_profile(self.context)
|
|
143
|
+
if record is None:
|
|
144
|
+
self.report["status"] = "missing"
|
|
145
|
+
else:
|
|
146
|
+
self.report["status"] = "observed"
|
|
147
|
+
self.report["vmm_capacity"] = dict((record.get("observations") or [{}])[-1].get("vmm", {}))
|
|
148
|
+
return config
|
|
149
|
+
# An explicit caller budget has always taken precedence over a saved
|
|
150
|
+
# recommendation. It is not itself a profile calibration.
|
|
151
|
+
if config.resident_module_budget_gb > 0:
|
|
152
|
+
return config
|
|
153
|
+
record = load_dynamic_offload_profile(self.context)
|
|
154
|
+
recommendation = get_dynamic_offload_profile_recommendation(record or {}) or {}
|
|
155
|
+
budget = recommendation.get("profile_resident_module_budget_gb")
|
|
156
|
+
if not isinstance(budget, (int, float)) or not math.isfinite(budget) or budget < 0:
|
|
157
|
+
self.report["status"] = "missing"
|
|
158
|
+
print(f"[dynamic-offload] profile {config.profile_name!r}: no recommendation; calibrate with build_profile=True.")
|
|
159
|
+
return config
|
|
160
|
+
if config.max_resident_module_budget_gb > 0:
|
|
161
|
+
budget = min(budget, config.max_resident_module_budget_gb)
|
|
162
|
+
probe_budget = recommendation.get("sdnq_probe_resident_budget_gb")
|
|
163
|
+
if isinstance(probe_budget, (int, float)) and math.isfinite(probe_budget) and probe_budget > 0:
|
|
164
|
+
budget = min(float(probe_budget), budget)
|
|
165
|
+
self._sdnq_probe_budget_gb = budget
|
|
166
|
+
self.report["status"] = "probing"
|
|
167
|
+
print(
|
|
168
|
+
f"[dynamic-offload] profile {config.profile_name!r}: "
|
|
169
|
+
f"validating SDNQ resident probe={budget:.2f} GiB."
|
|
170
|
+
)
|
|
171
|
+
else:
|
|
172
|
+
self.report["status"] = "applied"
|
|
173
|
+
self.report["resident_budget_gb"] = budget
|
|
174
|
+
print(f"[dynamic-offload] profile {config.profile_name!r}: requested resident budget={budget:.2f} GiB.")
|
|
175
|
+
if config.auto_budget_policy == "off":
|
|
176
|
+
return replace(config, resident_module_budget_gb=budget, _profile_budget_applied=True)
|
|
177
|
+
return replace(config, profile_resident_module_budget_gb=budget, _profile_budget_applied=True)
|
|
178
|
+
|
|
179
|
+
@contextmanager
|
|
180
|
+
def measure(self):
|
|
181
|
+
"""Measure only the caller's inference region, then persist on success."""
|
|
182
|
+
if self.config.execution_mode == "vmm_fast_runtime":
|
|
183
|
+
if not self.config.build_profile:
|
|
184
|
+
yield self.report
|
|
185
|
+
return
|
|
186
|
+
if self._vmm_hook is None:
|
|
187
|
+
raise RuntimeError("VMM capacity profiling requires an applied dynamic-offload hook.")
|
|
188
|
+
if self._active:
|
|
189
|
+
raise RuntimeError("A profile measurement is already active.")
|
|
190
|
+
self._active = True
|
|
191
|
+
try:
|
|
192
|
+
yield self.report
|
|
193
|
+
torch.cuda.synchronize(torch.device(self.config.execution_device))
|
|
194
|
+
stats = self._vmm_hook.vmm_runtime_stats() or {}
|
|
195
|
+
capacity = {
|
|
196
|
+
"backend": "vmm_fast_runtime",
|
|
197
|
+
"platform": sys.platform,
|
|
198
|
+
"virtual_bytes": int(stats.get("fast_virtual_bytes", 0)),
|
|
199
|
+
"page_bytes": int(stats.get("fast_page_bytes", 0)),
|
|
200
|
+
"resident_bytes": int(stats.get("fast_resident_bytes", 0)),
|
|
201
|
+
"file_backed_bindings": int(stats.get("fast_file_backed_bindings", 0)),
|
|
202
|
+
"file_backed_bytes": int(stats.get("fast_file_backed_bytes", 0)),
|
|
203
|
+
"cpu_source_bindings": int(stats.get("fast_cpu_source_bindings", 0)),
|
|
204
|
+
"faults": int(stats.get("fast_faults", 0)),
|
|
205
|
+
"signature_hits": int(stats.get("fast_signature_hits", 0)),
|
|
206
|
+
"uploads": int(stats.get("fast_uploads", 0)),
|
|
207
|
+
"temporary_tensors": int(stats.get("fast_temporary_tensors", 0)),
|
|
208
|
+
"temporary_bytes": int(stats.get("fast_temporary_bytes", 0)),
|
|
209
|
+
}
|
|
210
|
+
observation = {
|
|
211
|
+
"status": "success",
|
|
212
|
+
"profile_measurement_kind": "vmm_capacity",
|
|
213
|
+
"capacity": {"metric": "vmm_virtual_bytes", "value": capacity["virtual_bytes"]},
|
|
214
|
+
"vmm": capacity,
|
|
215
|
+
}
|
|
216
|
+
path = record_dynamic_offload_profile(self.context, observation)
|
|
217
|
+
self.report.update(path=str(path), **observation)
|
|
218
|
+
self.report["status"] = "saved"
|
|
219
|
+
except BaseException:
|
|
220
|
+
self.report["status"] = "failed"
|
|
221
|
+
raise
|
|
222
|
+
finally:
|
|
223
|
+
self._active = False
|
|
224
|
+
return
|
|
225
|
+
if not self.config.build_profile and self._sdnq_probe_budget_gb is None:
|
|
226
|
+
yield self.report
|
|
227
|
+
return
|
|
228
|
+
if self._active:
|
|
229
|
+
raise RuntimeError("A profile measurement is already active.")
|
|
230
|
+
self._active = True
|
|
231
|
+
device = torch.device(self.config.execution_device)
|
|
232
|
+
sampler = _CudaPeakSampler(device) if self.config.execution_mode == "sdnq_runtime" else None
|
|
233
|
+
try:
|
|
234
|
+
torch.cuda.synchronize(device)
|
|
235
|
+
free, total = torch.cuda.mem_get_info(device)
|
|
236
|
+
external_bytes = max(0, total - free - torch.cuda.memory_reserved(device))
|
|
237
|
+
torch.cuda.reset_peak_memory_stats(device)
|
|
238
|
+
if sampler is not None:
|
|
239
|
+
sampler.start()
|
|
240
|
+
yield self.report
|
|
241
|
+
torch.cuda.synchronize(device)
|
|
242
|
+
free_end, _ = torch.cuda.mem_get_info(device)
|
|
243
|
+
peak = max(
|
|
244
|
+
total - free,
|
|
245
|
+
total - free_end,
|
|
246
|
+
external_bytes + torch.cuda.max_memory_reserved(device),
|
|
247
|
+
sampler.stop() if sampler is not None else 0,
|
|
248
|
+
) / 1024**3
|
|
249
|
+
total_gb = total / 1024**3
|
|
250
|
+
target_gb = max(0.0, total_gb - self.config.profile_vram_headroom_gb)
|
|
251
|
+
if self._sdnq_probe_budget_gb is not None:
|
|
252
|
+
budget = max(0.0, self._sdnq_probe_budget_gb - max(0.0, peak - target_gb))
|
|
253
|
+
recommendation = {"profile_resident_module_budget_gb": round(budget, 4)}
|
|
254
|
+
observation_kind = "sdnq_probe"
|
|
255
|
+
elif self.config.execution_mode == "sdnq_runtime":
|
|
256
|
+
safe_budget = DynamicOffloadProfileSession.recommend_resident_budget(
|
|
257
|
+
total_gb, peak, self.config.profile_vram_headroom_gb,
|
|
258
|
+
)
|
|
259
|
+
configured_ceiling = float(self.config.max_resident_module_budget_gb)
|
|
260
|
+
ceiling = configured_ceiling if configured_ceiling > 0 else _SDNQ_DEFAULT_RESIDENT_CEILING_GB
|
|
261
|
+
probe_budget = min(ceiling, target_gb)
|
|
262
|
+
if safe_budget >= _SDNQ_PROBE_MIN_SAFE_BUDGET_GB and probe_budget > safe_budget:
|
|
263
|
+
budget = probe_budget
|
|
264
|
+
recommendation = {
|
|
265
|
+
"profile_resident_module_budget_gb": round(budget, 4),
|
|
266
|
+
"sdnq_probe_resident_budget_gb": round(budget, 4),
|
|
267
|
+
}
|
|
268
|
+
observation_kind = "sdnq_baseline_probe_pending"
|
|
269
|
+
else:
|
|
270
|
+
budget = safe_budget
|
|
271
|
+
recommendation = {"profile_resident_module_budget_gb": round(budget, 4)}
|
|
272
|
+
observation_kind = "sdnq_baseline_safe"
|
|
273
|
+
else:
|
|
274
|
+
budget = DynamicOffloadProfileSession.recommend_resident_budget(
|
|
275
|
+
total_gb, peak, self.config.profile_vram_headroom_gb,
|
|
276
|
+
)
|
|
277
|
+
recommendation = {"profile_resident_module_budget_gb": budget}
|
|
278
|
+
observation_kind = "baseline"
|
|
279
|
+
observation = {"status": "success", "peak_vram_gb": peak,
|
|
280
|
+
"total_vram_gb": total_gb,
|
|
281
|
+
"headroom_gb": self.config.profile_vram_headroom_gb,
|
|
282
|
+
"profile_measurement_kind": observation_kind,
|
|
283
|
+
"measurement": "cuda_driver_peak_sampled_plus_allocator"}
|
|
284
|
+
path = record_dynamic_offload_profile(
|
|
285
|
+
self.context, observation,
|
|
286
|
+
recommendation=recommendation,
|
|
287
|
+
)
|
|
288
|
+
self.report.update(path=str(path), resident_budget_gb=budget, **observation)
|
|
289
|
+
self.report["status"] = "saved"
|
|
290
|
+
if observation_kind == "sdnq_baseline_probe_pending":
|
|
291
|
+
print(
|
|
292
|
+
f"[dynamic-offload] profile {self.config.profile_name!r}: "
|
|
293
|
+
f"baseline peak={peak:.2f} GiB; next SDNQ run will validate "
|
|
294
|
+
f"resident probe={budget:.2f} GiB; saved to {path}"
|
|
295
|
+
)
|
|
296
|
+
return
|
|
297
|
+
print(f"[dynamic-offload] profile {self.config.profile_name!r}: "
|
|
298
|
+
f"peak={peak:.2f} GiB, margin={self.config.profile_vram_headroom_gb:.2f} GiB, "
|
|
299
|
+
f"resident budget={budget:.2f} GiB; saved to {path}")
|
|
300
|
+
except BaseException:
|
|
301
|
+
self.report["status"] = "failed"
|
|
302
|
+
raise
|
|
303
|
+
finally:
|
|
304
|
+
if sampler is not None:
|
|
305
|
+
sampler.stop()
|
|
306
|
+
self._active = False
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _json_value(value: Any) -> Any:
|
|
310
|
+
"""Return a deterministic JSON-compatible representation of ``value``."""
|
|
311
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
312
|
+
return value
|
|
313
|
+
if isinstance(value, Mapping):
|
|
314
|
+
return {str(key): _json_value(item) for key, item in sorted(value.items(), key=lambda item: str(item[0]))}
|
|
315
|
+
if isinstance(value, (list, tuple)):
|
|
316
|
+
return [_json_value(item) for item in value]
|
|
317
|
+
raise TypeError(f"DDO profile context contains a non-JSON value: {type(value).__name__}")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def normalize_dynamic_offload_profile_context(context: Mapping[str, Any]) -> dict[str, Any]:
|
|
321
|
+
"""Validate and canonicalize the host-provided profile identity context."""
|
|
322
|
+
if not isinstance(context, Mapping) or not context:
|
|
323
|
+
raise ValueError("DDO profile context must be a non-empty mapping.")
|
|
324
|
+
normalized = _json_value(context)
|
|
325
|
+
if not isinstance(normalized, dict): # Defensive for type checkers and future changes.
|
|
326
|
+
raise TypeError("DDO profile context must normalize to an object.")
|
|
327
|
+
return normalized
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def dynamic_offload_profile_key(context: Mapping[str, Any]) -> str:
|
|
331
|
+
"""Return the stable, privacy-preserving filename key for a context."""
|
|
332
|
+
normalized = normalize_dynamic_offload_profile_context(context)
|
|
333
|
+
encoded = json.dumps(normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")
|
|
334
|
+
return f"{_PROFILE_PREFIX}-{hashlib.sha256(encoded).hexdigest()[:24]}"
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def get_dynamic_offload_profile_dir(profile_dir: str | Path | None = None) -> Path:
|
|
338
|
+
"""Return the profile directory, honoring ``DDO_PROFILE_DIR`` when set."""
|
|
339
|
+
raw_directory = profile_dir if profile_dir is not None else os.getenv("DDO_PROFILE_DIR")
|
|
340
|
+
return Path(raw_directory).expanduser() if raw_directory else Path.home() / ".ddo" / "profiles"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def dynamic_offload_profile_path(context: Mapping[str, Any], profile_dir: str | Path | None = None) -> Path:
|
|
344
|
+
"""Return the JSON path assigned to ``context`` without creating anything."""
|
|
345
|
+
return get_dynamic_offload_profile_dir(profile_dir) / f"{dynamic_offload_profile_key(context)}.json"
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def load_dynamic_offload_profile(
|
|
349
|
+
context: Mapping[str, Any], profile_dir: str | Path | None = None
|
|
350
|
+
) -> dict[str, Any] | None:
|
|
351
|
+
"""Load a matching profile, returning ``None`` for missing or invalid data."""
|
|
352
|
+
expected_context = normalize_dynamic_offload_profile_context(context)
|
|
353
|
+
path = dynamic_offload_profile_path(expected_context, profile_dir)
|
|
354
|
+
try:
|
|
355
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
356
|
+
except (OSError, json.JSONDecodeError):
|
|
357
|
+
return None
|
|
358
|
+
if not isinstance(record, dict):
|
|
359
|
+
return None
|
|
360
|
+
if record.get("schema_version") != DYNAMIC_OFFLOAD_PROFILE_SCHEMA_VERSION:
|
|
361
|
+
return None
|
|
362
|
+
if record.get("profile_key") != dynamic_offload_profile_key(expected_context):
|
|
363
|
+
return None
|
|
364
|
+
if record.get("context") != expected_context:
|
|
365
|
+
return None
|
|
366
|
+
return record
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _merge_capacity_limits(existing: Mapping[str, Any] | None, observation: Mapping[str, Any]) -> dict[str, Any]:
|
|
370
|
+
limits = dict(existing or {})
|
|
371
|
+
capacity = observation.get("capacity")
|
|
372
|
+
if not isinstance(capacity, Mapping):
|
|
373
|
+
return limits
|
|
374
|
+
metric = capacity.get("metric")
|
|
375
|
+
value = capacity.get("value")
|
|
376
|
+
status = observation.get("status")
|
|
377
|
+
if not isinstance(metric, str) or not metric or not isinstance(value, (int, float)):
|
|
378
|
+
return limits
|
|
379
|
+
previous = dict(limits.get(metric) or {})
|
|
380
|
+
if status == "success":
|
|
381
|
+
previous["max_success"] = max(float(value), float(previous.get("max_success", value)))
|
|
382
|
+
elif status == "failure":
|
|
383
|
+
previous["min_failure"] = min(float(value), float(previous.get("min_failure", value)))
|
|
384
|
+
else:
|
|
385
|
+
return limits
|
|
386
|
+
limits[metric] = previous
|
|
387
|
+
return limits
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def record_dynamic_offload_profile(
|
|
391
|
+
context: Mapping[str, Any],
|
|
392
|
+
observation: Mapping[str, Any],
|
|
393
|
+
profile_dir: str | Path | None = None,
|
|
394
|
+
recommendation: Mapping[str, Any] | None = None,
|
|
395
|
+
) -> Path:
|
|
396
|
+
"""Persist an observation and merge generic capacity limits for its context.
|
|
397
|
+
|
|
398
|
+
``observation`` may include ``{"status": "success", "capacity":
|
|
399
|
+
{"metric": "tokens", "value": 123}}``. DDO keeps the largest success
|
|
400
|
+
and the smallest failure per metric, without knowing model-specific terms.
|
|
401
|
+
"""
|
|
402
|
+
normalized_context = normalize_dynamic_offload_profile_context(context)
|
|
403
|
+
normalized_observation = _json_value(observation)
|
|
404
|
+
normalized_recommendation = None if recommendation is None else _json_value(recommendation)
|
|
405
|
+
if not isinstance(normalized_observation, dict):
|
|
406
|
+
raise TypeError("DDO profile observation must normalize to an object.")
|
|
407
|
+
if normalized_recommendation is not None and not isinstance(normalized_recommendation, dict):
|
|
408
|
+
raise TypeError("DDO profile recommendation must normalize to an object.")
|
|
409
|
+
path = dynamic_offload_profile_path(normalized_context, profile_dir)
|
|
410
|
+
prior = load_dynamic_offload_profile(normalized_context, profile_dir) or {}
|
|
411
|
+
observations = list(prior.get("observations") or [])
|
|
412
|
+
observations.append(normalized_observation)
|
|
413
|
+
record = {
|
|
414
|
+
"schema_version": DYNAMIC_OFFLOAD_PROFILE_SCHEMA_VERSION,
|
|
415
|
+
"profile_key": dynamic_offload_profile_key(normalized_context),
|
|
416
|
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
|
417
|
+
"context": normalized_context,
|
|
418
|
+
"capacity_limits": _merge_capacity_limits(prior.get("capacity_limits"), normalized_observation),
|
|
419
|
+
"observations": observations[-20:],
|
|
420
|
+
}
|
|
421
|
+
if normalized_recommendation is not None:
|
|
422
|
+
record["recommendation"] = normalized_recommendation
|
|
423
|
+
elif isinstance(prior.get("recommendation"), Mapping):
|
|
424
|
+
record["recommendation"] = dict(prior["recommendation"])
|
|
425
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
426
|
+
temporary_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
|
|
427
|
+
temporary_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
428
|
+
os.replace(temporary_path, path)
|
|
429
|
+
return path
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def get_dynamic_offload_profile_capacity(profile: Mapping[str, Any], metric: str) -> dict[str, float] | None:
|
|
433
|
+
"""Return validated limits for a generic capacity metric, if present."""
|
|
434
|
+
limits = profile.get("capacity_limits")
|
|
435
|
+
if not isinstance(limits, Mapping) or not isinstance(limits.get(metric), Mapping):
|
|
436
|
+
return None
|
|
437
|
+
result = {key: float(value) for key, value in limits[metric].items() if key in {"max_success", "min_failure"}}
|
|
438
|
+
return result or None
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def get_dynamic_offload_profile_recommendation(profile: Mapping[str, Any]) -> dict[str, Any] | None:
|
|
442
|
+
"""Return a JSON-safe host recommendation stored with a matching profile."""
|
|
443
|
+
recommendation = profile.get("recommendation")
|
|
444
|
+
return dict(recommendation) if isinstance(recommendation, Mapping) else None
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@dataclass
|
|
448
|
+
class DynamicOffloadProfileSession:
|
|
449
|
+
"""One generic lifecycle for exact presets plus family capacity history."""
|
|
450
|
+
|
|
451
|
+
execution_context: Mapping[str, Any]
|
|
452
|
+
capacity_context: Mapping[str, Any]
|
|
453
|
+
profile_dir: str | Path | None = None
|
|
454
|
+
execution_profile: dict[str, Any] | None = field(init=False)
|
|
455
|
+
capacity_profile: dict[str, Any] | None = field(init=False)
|
|
456
|
+
|
|
457
|
+
def __post_init__(self):
|
|
458
|
+
self.execution_profile = load_dynamic_offload_profile(self.execution_context, self.profile_dir)
|
|
459
|
+
self.capacity_profile = load_dynamic_offload_profile(self.capacity_context, self.profile_dir)
|
|
460
|
+
|
|
461
|
+
def apply_settings(self, settings: Any, *, allow_recommendation: bool = True) -> tuple[Any, dict[str, Any] | None]:
|
|
462
|
+
"""Apply DDO's known resident-budget recommendation, if one exists."""
|
|
463
|
+
recommendation = get_dynamic_offload_profile_recommendation(self.execution_profile or {})
|
|
464
|
+
if not allow_recommendation or not recommendation:
|
|
465
|
+
return settings, recommendation
|
|
466
|
+
if settings.config.resident_module_budget_gb > 0:
|
|
467
|
+
return settings, None
|
|
468
|
+
budget = recommendation.get("profile_resident_module_budget_gb")
|
|
469
|
+
if budget is None:
|
|
470
|
+
# Read profiles written by DDO versions that exposed the old
|
|
471
|
+
# environment variable, without retaining that public setting.
|
|
472
|
+
budget = recommendation.get("auto_full_pin_resident_budget_gb")
|
|
473
|
+
if budget is None:
|
|
474
|
+
return settings, recommendation
|
|
475
|
+
return replace(
|
|
476
|
+
settings,
|
|
477
|
+
config=replace(settings.config, profile_resident_module_budget_gb=max(0.0, float(budget))),
|
|
478
|
+
), recommendation
|
|
479
|
+
|
|
480
|
+
@staticmethod
|
|
481
|
+
def recommend_resident_budget(total_vram_gb: float, peak_vram_gb: float, headroom_gb: float) -> float:
|
|
482
|
+
"""Convert a zero-resident calibration peak into a conservative DDO budget."""
|
|
483
|
+
return round(max(0.0, float(total_vram_gb) - float(peak_vram_gb) - float(headroom_gb)), 4)
|
|
484
|
+
|
|
485
|
+
def record_success(
|
|
486
|
+
self, observation: Mapping[str, Any], recommendation: Mapping[str, Any] | None = None
|
|
487
|
+
) -> tuple[Path, Path]:
|
|
488
|
+
"""Record an exact observation/recommendation and family capacity observation."""
|
|
489
|
+
execution_path = record_dynamic_offload_profile(
|
|
490
|
+
self.execution_context, observation, self.profile_dir, recommendation=recommendation
|
|
491
|
+
)
|
|
492
|
+
capacity_path = record_dynamic_offload_profile(self.capacity_context, observation, self.profile_dir)
|
|
493
|
+
self.execution_profile = load_dynamic_offload_profile(self.execution_context, self.profile_dir)
|
|
494
|
+
self.capacity_profile = load_dynamic_offload_profile(self.capacity_context, self.profile_dir)
|
|
495
|
+
return execution_path, capacity_path
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Experimental explicit source association for composite FP8 weights.
|
|
2
|
+
|
|
3
|
+
Not imported by runtime defaults. The loader must supply physical payload
|
|
4
|
+
descriptors; no checkpoint key guessing, file reads or CUDA calls occur here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .vmm_weight_store import SafetensorFileSlice, SafetensorSliceRegistry
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Float8SourceContract:
|
|
14
|
+
weight_spec: object
|
|
15
|
+
sources: tuple[tuple[str, SafetensorFileSlice], ...]
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def physical_bytes(self):
|
|
19
|
+
return self.weight_spec.physical_bytes
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def describe_float8_sources_cpu(weight, payload_sources):
|
|
23
|
+
"""Validate all physical sources before returning a tensor-free contract.
|
|
24
|
+
|
|
25
|
+
Caller must establish value equivalence and loader provenance; matching
|
|
26
|
+
metadata alone cannot prove file bytes equal a converted weight. CPU
|
|
27
|
+
checkpoint contracts only; does not open/register sources or attach hooks.
|
|
28
|
+
"""
|
|
29
|
+
from ddo_vmm_allocator.quantized_payload import describe_float8_weight_only_cpu
|
|
30
|
+
|
|
31
|
+
spec = describe_float8_weight_only_cpu(weight)
|
|
32
|
+
if set(payload_sources) != {item.name for item in spec.payloads}:
|
|
33
|
+
raise ValueError("Both FP8 data and scale source descriptors are required")
|
|
34
|
+
registry = SafetensorSliceRegistry()
|
|
35
|
+
intervals = {}
|
|
36
|
+
sources = []
|
|
37
|
+
for payload in spec.payloads:
|
|
38
|
+
source = payload_sources[payload.name]
|
|
39
|
+
if not isinstance(source, SafetensorFileSlice):
|
|
40
|
+
raise ValueError("Immutable safetensors payload descriptor required")
|
|
41
|
+
if (type(source.offset_bytes) is not int or source.offset_bytes < 8
|
|
42
|
+
or type(source.size_bytes) is not int or source.size_bytes <= 0
|
|
43
|
+
or source.shape is None or source.dtype is None):
|
|
44
|
+
raise ValueError("Complete physical source metadata required")
|
|
45
|
+
if not source.path.is_absolute():
|
|
46
|
+
raise ValueError("Resolved absolute source path required")
|
|
47
|
+
if not registry.bind(getattr(weight, payload.name), source):
|
|
48
|
+
raise ValueError("Source shape, dtype or byte length differs from physical payload")
|
|
49
|
+
# Reject overlapping payload source ranges within a shard. This also
|
|
50
|
+
# rejects supplying one descriptor twice; aliases need separate support.
|
|
51
|
+
path = str(source.path.resolve())
|
|
52
|
+
start, end = source.offset_bytes, source.offset_bytes + source.size_bytes
|
|
53
|
+
previous = intervals.setdefault(path, [])
|
|
54
|
+
if any(start < old_end and old_start < end for old_start, old_end in previous):
|
|
55
|
+
raise ValueError("Overlapping source payload ranges are unsupported")
|
|
56
|
+
previous.append((start, end))
|
|
57
|
+
sources.append((payload.name, source))
|
|
58
|
+
return Float8SourceContract(spec, tuple(sources))
|