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.
Files changed (28) hide show
  1. ddo_native_check.py +44 -0
  2. ddo_vmm_bootstrap.py +142 -0
  3. diffusers_dynamic_offloader/__init__.py +116 -0
  4. diffusers_dynamic_offloader/allocation_diagnostics.py +96 -0
  5. diffusers_dynamic_offloader/auxiliary_sources.py +126 -0
  6. diffusers_dynamic_offloader/backend.py +166 -0
  7. diffusers_dynamic_offloader/device_cache.py +60 -0
  8. diffusers_dynamic_offloader/dynamic_offload.py +3919 -0
  9. diffusers_dynamic_offloader/float8_compile.py +77 -0
  10. diffusers_dynamic_offloader/float8_loading.py +130 -0
  11. diffusers_dynamic_offloader/host_cache.py +101 -0
  12. diffusers_dynamic_offloader/host_memory.py +70 -0
  13. diffusers_dynamic_offloader/linear_convolution.py +105 -0
  14. diffusers_dynamic_offloader/metrics.py +217 -0
  15. diffusers_dynamic_offloader/metrics_journal.py +66 -0
  16. diffusers_dynamic_offloader/operator_diagnostics.py +167 -0
  17. diffusers_dynamic_offloader/profiles.py +495 -0
  18. diffusers_dynamic_offloader/quantized_sources.py +58 -0
  19. diffusers_dynamic_offloader/timing.py +129 -0
  20. diffusers_dynamic_offloader/vmm_model_arena.py +277 -0
  21. diffusers_dynamic_offloader/vmm_weight_store.py +840 -0
  22. diffusers_dynamic_offloader/weight_source_metadata.py +81 -0
  23. diffusers_dynamic_offloader/windows_file_reader.py +106 -0
  24. diffusers_dynamic_offloader-0.1.0rc2.dist-info/METADATA +90 -0
  25. diffusers_dynamic_offloader-0.1.0rc2.dist-info/RECORD +28 -0
  26. diffusers_dynamic_offloader-0.1.0rc2.dist-info/WHEEL +5 -0
  27. diffusers_dynamic_offloader-0.1.0rc2.dist-info/licenses/LICENSE +201 -0
  28. diffusers_dynamic_offloader-0.1.0rc2.dist-info/top_level.txt +3 -0
@@ -0,0 +1,129 @@
1
+ """Opt-in compute-stream timing; step waits are a separate diagnostic control."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+
7
+
8
+ class DynamicOffloadExecutionTimer:
9
+ """Record CUDA boundary markers; resolve only after completion is proven.
10
+
11
+ Intervals include compute-stream dependencies and host launch gaps, not
12
+ kernel-only work. They do not establish H2D/compute overlap. Disabled mode
13
+ creates no events and does not inspect CUDA. Each instance measures one run.
14
+ Explicit diagnostic_step_wait changes submission cadence and disqualifies
15
+ the report as a performance benchmark. It is never enabled by a preset.
16
+ """
17
+
18
+ def __init__(self, *, enabled=False, device="cuda", native_factory=None,
19
+ diagnostic_step_wait=False):
20
+ if diagnostic_step_wait and not enabled:
21
+ raise ValueError("diagnostic step wait requires enabled GPU timing")
22
+ self.enabled = enabled
23
+ self.diagnostic_step_wait = bool(diagnostic_step_wait)
24
+ self._step_wait_calls = 0
25
+ self._step_wait_seconds = 0.0
26
+ self.device = device
27
+ self._events = []
28
+ self._stream = None
29
+ self._end = None
30
+ self._active = False
31
+ self._failed = False
32
+ self._used = False
33
+ self._native_factory = native_factory
34
+ self._native = None
35
+ self._detach_native = None
36
+
37
+ def __enter__(self):
38
+ if self._used:
39
+ raise RuntimeError("Execution timer instances cannot be reused")
40
+ self._used = True
41
+ if self.enabled:
42
+ import torch
43
+ with torch.cuda.device(self.device):
44
+ self._stream = torch.cuda.current_stream(self.device)
45
+ self._event_type = torch.cuda.Event
46
+ if self._native_factory is not None:
47
+ self._native, self._detach_native = self._native_factory(int(self._stream.cuda_stream))
48
+ self._native.mark_boundary(0, int(self._stream.cuda_stream))
49
+ try:
50
+ event = self._event_type(enable_timing=True)
51
+ event.record(self._stream)
52
+ self._events.append(event)
53
+ except Exception:
54
+ self._failed = True
55
+ if self._native is not None:
56
+ try:
57
+ self._native.seal()
58
+ finally:
59
+ self._detach_native()
60
+ raise
61
+ self._active = True
62
+ return self
63
+
64
+ def mark_step(self):
65
+ if not self.enabled:
66
+ return
67
+ if not self._active:
68
+ raise RuntimeError("Step marker requires an active execution timer")
69
+ if self._native is not None:
70
+ self._native.mark_boundary(len(self._events), int(self._stream.cuda_stream))
71
+ event = self._event_type(enable_timing=True)
72
+ event.record(self._stream)
73
+ self._events.append(event)
74
+
75
+ if self.diagnostic_step_wait:
76
+ # Explicit causal control only, never an offload/residency policy.
77
+ # Wait for this compute boundary, not the device or upload stream.
78
+ from time import perf_counter
79
+ start = perf_counter()
80
+ try:
81
+ self._step_wait_calls += 1
82
+ event.synchronize()
83
+ finally:
84
+ self._step_wait_seconds += perf_counter() - start
85
+
86
+ def __exit__(self, exc_type, exc_value, traceback):
87
+ self._failed = exc_type is not None
88
+ self._active = False
89
+ if self._native is not None:
90
+ try:
91
+ self._native.mark_boundary(2**64 - 1, int(self._stream.cuda_stream))
92
+ self._native.seal()
93
+ finally:
94
+ self._detach_native()
95
+ if self.enabled:
96
+ self._end = self._event_type(enable_timing=True)
97
+ self._end.record(self._stream)
98
+
99
+ def snapshot(self, *, wait=False):
100
+ """Default never waits. Optional wait drains just the final marker."""
101
+ report = {"schema_version": 1, "clock": "cuda_event", "unit": "seconds",
102
+ "scope": "compute_stream_with_dependencies", "failed": self._failed}
103
+ if self.diagnostic_step_wait:
104
+ report["diagnostic_step_wait"] = {
105
+ "enabled": True, "scope": "compute_boundary_event_host_wait",
106
+ "calls": self._step_wait_calls, "host_seconds": self._step_wait_seconds,
107
+ "benchmark_eligible": False,
108
+ }
109
+ if not self.enabled:
110
+ return {**report, "status": "disabled"}
111
+ if self._end is None:
112
+ return {**report, "status": "not_finished"}
113
+ if wait:
114
+ self._end.synchronize()
115
+ if not self._end.query():
116
+ return {**report, "status": "pending", "step_count": len(self._events) - 1}
117
+ steps = [a.elapsed_time(b) / 1000 for a, b in zip(self._events, self._events[1:])]
118
+ return {**report, "status": "complete", "stream": int(self._stream.cuda_stream),
119
+ "phase_seconds": self._events[0].elapsed_time(self._end) / 1000,
120
+ "step_seconds": steps,
121
+ "tail_seconds": self._events[-1].elapsed_time(self._end) / 1000,
122
+ "steady_state_seconds_per_step": sum(steps[1:]) / len(steps[1:]) if len(steps) > 1 else None}
123
+
124
+ def attach(self, report):
125
+ """Combine with the public DDO report; hosts need no field knowledge."""
126
+ runtime = {**report.runtime, "execution_timing": self.snapshot()}
127
+ if self._native is not None:
128
+ runtime["native_timeline"] = self._native.snapshot()
129
+ return replace(report, runtime=runtime)
@@ -0,0 +1,277 @@
1
+ """DDO VMM model arena backed by the native C++ allocator.
2
+
3
+ The DDO layer owns model-agnostic policy: grouping, hooks, prefetch, metrics,
4
+ and profile integration. The native allocator owns CUDA virtual addresses,
5
+ physical residency, map/unmap operations, budget guards, and transfer counters.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ import threading
13
+ from contextlib import AbstractContextManager
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from .vmm_weight_store import PinnedStagingPool, RegisteredHostWeightRegistry, SafetensorSliceRegistry, _round_up
19
+
20
+ if TYPE_CHECKING:
21
+ import torch
22
+
23
+
24
+ _ARENA_PAGE_BYTES = 32 * 1024**2
25
+
26
+
27
+ @dataclass
28
+ class VmmModelArenaStats:
29
+ reserved_bytes: int = 0
30
+ resident_bytes: int = 0
31
+ materializations: int = 0
32
+ evictions: int = 0
33
+ copied_bytes: int = 0
34
+ map_seconds: float = 0.0
35
+ direct_dma_seconds: float = 0.0
36
+ staging_seconds: float = 0.0
37
+ file_slice_staging_seconds: float = 0.0
38
+ file_slice_bytes: int = 0
39
+ temporary_fallbacks: int = 0
40
+ temporary_bytes: int = 0
41
+ persistent_virtual_views: int = 0
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class _ArenaWeightView:
46
+ name: str
47
+ offset: int
48
+ shape: tuple[int, ...]
49
+ dtype: Any
50
+ bytes: int
51
+
52
+
53
+ class _ArenaGroup:
54
+ def __init__(self, key: str, allocation_bytes: int, payload_bytes: int, views: dict[str, _ArenaWeightView]):
55
+ self.key = key
56
+ self.allocation_bytes = allocation_bytes
57
+ self.payload_bytes = payload_bytes
58
+ self.views = views
59
+ self.tensor_views: dict[str, Any] = {}
60
+ self.temporary_views: dict[str, Any] | None = None
61
+ self.active_leases = 0
62
+
63
+
64
+ class VmmModelArenaLease(AbstractContextManager):
65
+ def __init__(self, arena: VmmModelArena, group_key: str) -> None:
66
+ self._arena = arena
67
+ self._group_key = group_key
68
+ self._closed = False
69
+
70
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
71
+ if not self._closed:
72
+ self._arena.release(self._group_key)
73
+ self._closed = True
74
+
75
+
76
+ def _allocator_source_root() -> Path:
77
+ base = Path(__file__).resolve().parents[2]
78
+ candidate = base / "ddo-vmm-allocator" / "src"
79
+ if candidate.exists():
80
+ return candidate
81
+ return Path(__file__).resolve().parents[3] / "ddo-vmm-allocator" / "src"
82
+
83
+ def _load_native_allocator(library_path: str | None):
84
+ try:
85
+ from ddo_vmm_allocator.native import load_native_vmm
86
+ from ddo_vmm_allocator.weight_arena import VmmWeightArena
87
+ except ImportError:
88
+ source_root = _allocator_source_root()
89
+ if source_root.exists() and str(source_root) not in sys.path:
90
+ sys.path.insert(0, str(source_root))
91
+ try:
92
+ from ddo_vmm_allocator.native import load_native_vmm
93
+ from ddo_vmm_allocator.weight_arena import VmmWeightArena
94
+ except ImportError as error:
95
+ raise RuntimeError(
96
+ "vmm_runtime requires ddo-vmm-allocator. Install it or run from the DDO source tree."
97
+ ) from error
98
+
99
+ # Match bootstrap/native binding precedence. Otherwise a diagnostic DLL
100
+ # and the model arena can silently use distinct native global state.
101
+ resolved_library = library_path if library_path is not None else os.environ.get("DDO_VMM_LIBRARY_PATH")
102
+ if resolved_library is None:
103
+ root = _allocator_source_root().parent
104
+ platform_library = root / "build" / "Release" / "ddo_vmm.dll"
105
+ if platform_library.exists():
106
+ resolved_library = str(platform_library)
107
+ return load_native_vmm(resolved_library), VmmWeightArena
108
+
109
+
110
+ class VmmModelArena:
111
+ """Stable model-weight views backed by the native C++ VMM allocator."""
112
+
113
+ def __init__(
114
+ self,
115
+ device_id: int,
116
+ max_resident_bytes: int,
117
+ *,
118
+ page_bytes: int = _ARENA_PAGE_BYTES,
119
+ library_path: str | None = None,
120
+ file_slices: SafetensorSliceRegistry | None = None,
121
+ staging_pool: PinnedStagingPool | None = None,
122
+ registered_host: RegisteredHostWeightRegistry | None = None,
123
+ ) -> None:
124
+ import torch
125
+
126
+ if not torch.cuda.is_available():
127
+ raise RuntimeError("PyTorch CUDA is unavailable.")
128
+ if max_resident_bytes <= 0:
129
+ raise ValueError("VMM arena resident budget must be positive")
130
+ library, arena_type = _load_native_allocator(library_path)
131
+ self.native_library_path = str(library.path)
132
+ self.device_id = device_id
133
+ self.max_resident_bytes = max_resident_bytes
134
+ self.page_bytes = page_bytes
135
+ self._native = arena_type(
136
+ library,
137
+ resident_budget_bytes=max_resident_bytes,
138
+ device_ordinal=device_id,
139
+ backing="device",
140
+ pin_source=False,
141
+ )
142
+ if file_slices is not None:
143
+ if staging_pool is None:
144
+ raise ValueError("VMM file transport requires a staging pool")
145
+ self._native.configure_file_transport(file_slices, staging_pool)
146
+ if registered_host is not None:
147
+ self._native.configure_registered_host_transport(registered_host)
148
+ self._groups: dict[str, _ArenaGroup] = {}
149
+ self._weight_groups: dict[str, str] = {}
150
+ self._reserved_bytes = 0
151
+ self._persistent_virtual_views = 0
152
+ self._lock = threading.RLock()
153
+ self._closed = False
154
+
155
+ @property
156
+ def stats(self) -> VmmModelArenaStats:
157
+ with self._lock:
158
+ stats = self._native.runtime_stats()
159
+ return VmmModelArenaStats(
160
+ reserved_bytes=self._reserved_bytes,
161
+ resident_bytes=int(stats.get("resident_bytes", 0)),
162
+ materializations=int(stats.get("materializations", 0)),
163
+ evictions=int(stats.get("evictions", 0)),
164
+ copied_bytes=int(stats.get("upload_bytes", 0)),
165
+ file_slice_bytes=int(stats.get("file_upload_bytes", 0)),
166
+ temporary_fallbacks=int(stats.get("temporary_groups", 0)),
167
+ temporary_bytes=int(stats.get("temporary_bytes", 0)),
168
+ persistent_virtual_views=self._persistent_virtual_views,
169
+ )
170
+
171
+ @property
172
+ def physical_page_bytes(self) -> int:
173
+ return self.page_bytes
174
+
175
+ def reserve_groups(self, groups: list[tuple[str, list[tuple[str, torch.Tensor]]]]) -> None:
176
+ with self._lock:
177
+ if self._groups:
178
+ raise RuntimeError("VMM arena groups were already reserved")
179
+ for group_key, weights in groups:
180
+ if not weights:
181
+ raise ValueError(f"VMM arena group {group_key!r} has no weights")
182
+ offset = 0
183
+ views: dict[str, _ArenaWeightView] = {}
184
+ for weight_name, weight in weights:
185
+ if weight_name in self._weight_groups:
186
+ raise ValueError(f"Duplicate VMM arena weight {weight_name!r}")
187
+ size_bytes = weight.numel() * weight.element_size()
188
+ views[weight_name] = _ArenaWeightView(
189
+ weight_name,
190
+ offset,
191
+ tuple(weight.shape),
192
+ weight.dtype,
193
+ size_bytes,
194
+ )
195
+ offset += size_bytes
196
+ allocation_bytes = _round_up(offset, self.page_bytes)
197
+ self._native.reserve(group_key, allocation_bytes)
198
+ tensor_views = self._native.bind_cpu_tensor_group(group_key, weights)
199
+ group = _ArenaGroup(group_key, allocation_bytes, offset, views)
200
+ group.tensor_views = tensor_views
201
+ self._groups[group_key] = group
202
+ self._weight_groups.update(dict.fromkeys(views, group_key))
203
+ self._reserved_bytes += allocation_bytes
204
+ self._persistent_virtual_views += len(views)
205
+ self._native.reset_runtime_stats()
206
+
207
+ def acquire(
208
+ self,
209
+ group_key: str,
210
+ sources: list[tuple[str, torch.Tensor]],
211
+ staging: PinnedStagingPool,
212
+ stream: Any,
213
+ registered_host: RegisteredHostWeightRegistry | None = None,
214
+ file_slices: SafetensorSliceRegistry | None = None,
215
+ allow_eviction: bool = True,
216
+ ) -> VmmModelArenaLease:
217
+ del sources, staging, registered_host, file_slices, allow_eviction
218
+ with self._lock:
219
+ self._require_open()
220
+ group = self._groups[group_key]
221
+ self._native.collect_completed_events(wait=False)
222
+ try:
223
+ self._native.prefetch_loaded_group(group_key, stream)
224
+ except Exception:
225
+ self._native.collect_completed_events(wait=True)
226
+ self._native.prefetch_loaded_group(group_key, stream)
227
+
228
+ group.active_leases += 1
229
+ return VmmModelArenaLease(self, group_key)
230
+
231
+ def mark_upload(self, group_key: str, stream: Any, staging: PinnedStagingPool) -> Any:
232
+ import torch
233
+
234
+ event = torch.cuda.Event()
235
+ event.record(stream)
236
+ if staging.has_active_upload:
237
+ staging.mark_upload(event)
238
+ return event
239
+
240
+ def weight(self, weight_name: str) -> torch.Tensor:
241
+ with self._lock:
242
+ self._require_open()
243
+ group = self._groups[self._weight_groups[weight_name]]
244
+ if group.temporary_views is not None and weight_name in group.temporary_views:
245
+ return group.temporary_views[weight_name]
246
+ return group.tensor_views[weight_name]
247
+
248
+ def contains_weight(self, weight_name: str) -> bool:
249
+ return weight_name in self._weight_groups
250
+
251
+ def release(self, group_key: str) -> None:
252
+ with self._lock:
253
+ self._require_open()
254
+ group = self._groups[group_key]
255
+ if group.active_leases <= 0:
256
+ raise RuntimeError(f"VMM arena group {group_key!r} was released without an active lease")
257
+ group.active_leases -= 1
258
+ if group.active_leases == 0:
259
+ self._native.release_after_current_stream(group_key)
260
+ group.temporary_views = None
261
+
262
+ def close(self) -> None:
263
+ with self._lock:
264
+ if self._closed:
265
+ return
266
+ for group in self._groups.values():
267
+ if group.active_leases:
268
+ raise RuntimeError(f"Cannot close VMM arena with active group {group.key!r}")
269
+ self._native.collect_completed_events(wait=True)
270
+ self._native.close()
271
+ self._groups.clear()
272
+ self._weight_groups.clear()
273
+ self._closed = True
274
+
275
+ def _require_open(self) -> None:
276
+ if self._closed:
277
+ raise RuntimeError("VMM arena is closed")