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,3919 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import json
5
+ import math
6
+ import os
7
+ import re
8
+ import threading
9
+ import time
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from dataclasses import dataclass, field, replace
12
+ from pathlib import Path
13
+ from typing import Any, Mapping
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from diffusers.hooks.hooks import HookRegistry, ModelHook
19
+
20
+ from .metrics import DynamicOffloadMetrics
21
+
22
+ _DEFAULT_TARGET_MODULE_CLASSES = (nn.Linear, nn.Embedding)
23
+ _DYNAMIC_OFFLOAD_HOOK = "dynamic_offload"
24
+ _DDO_ENV_PREFIX = "DDO_"
25
+ _PIN_MEMORY_ERRORS = (RuntimeError, getattr(torch, "AcceleratorError", RuntimeError))
26
+ _DEFAULT_ALWAYS_RESIDENT_MODULE_PATTERNS = (
27
+ r"(^|\.)(proj_in|time_embed|prompt_adaln|norm_out|proj_out)(\.|$)",
28
+ )
29
+ _AUTO_BUDGET_DISABLED = "off"
30
+ _AUTO_BUDGET_BALANCED = "balanced"
31
+ _DYNAMIC_OFFLOAD_PLAN_CACHE: dict[tuple[Any, ...], "DynamicOffloadState"] = {}
32
+ _DYNAMIC_OFFLOAD_PLAN_CACHE_LOCK = threading.Lock()
33
+ _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE: dict[tuple[Any, ...], torch.Tensor] = {}
34
+ _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE_LOCK = threading.Lock()
35
+
36
+
37
+ def dynamic_offload_env_value(name: str, default: str = "", environ: Mapping[str, str] | None = None) -> str:
38
+ env = os.environ if environ is None else environ
39
+ return env.get(name, default)
40
+
41
+
42
+ def is_wsl_environment() -> bool:
43
+ if os.name == "nt":
44
+ return False
45
+ try:
46
+ release = os.uname().release.lower()
47
+ except AttributeError:
48
+ release = ""
49
+ if "microsoft" in release or "wsl" in release:
50
+ return True
51
+ try:
52
+ version = Path("/proc/version").read_text(encoding="utf-8", errors="ignore").lower()
53
+ except OSError:
54
+ return False
55
+ return "microsoft" in version or "wsl" in version
56
+
57
+
58
+ def get_available_system_ram_gb() -> float:
59
+ try:
60
+ import psutil
61
+ except ImportError:
62
+ psutil = None
63
+ if psutil is not None:
64
+ try:
65
+ return psutil.virtual_memory().available / 1024**3
66
+ except Exception:
67
+ pass
68
+
69
+ if os.name == "nt":
70
+ try:
71
+ import ctypes
72
+
73
+ class MemoryStatusEx(ctypes.Structure):
74
+ _fields_ = [
75
+ ("dwLength", ctypes.c_ulong),
76
+ ("dwMemoryLoad", ctypes.c_ulong),
77
+ ("ullTotalPhys", ctypes.c_ulonglong),
78
+ ("ullAvailPhys", ctypes.c_ulonglong),
79
+ ("ullTotalPageFile", ctypes.c_ulonglong),
80
+ ("ullAvailPageFile", ctypes.c_ulonglong),
81
+ ("ullTotalVirtual", ctypes.c_ulonglong),
82
+ ("ullAvailVirtual", ctypes.c_ulonglong),
83
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
84
+ ]
85
+
86
+ status = MemoryStatusEx()
87
+ status.dwLength = ctypes.sizeof(MemoryStatusEx)
88
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
89
+ return status.ullAvailPhys / 1024**3
90
+ except Exception:
91
+ return 0.0
92
+ else:
93
+ try:
94
+ page_size = os.sysconf("SC_PAGE_SIZE")
95
+ available_pages = os.sysconf("SC_AVPHYS_PAGES")
96
+ return page_size * available_pages / 1024**3
97
+ except (AttributeError, OSError, ValueError):
98
+ return 0.0
99
+
100
+ return 0.0
101
+
102
+
103
+ def get_cuda_total_vram_gb(device: str | torch.device = "cuda:0") -> float:
104
+ if not torch.cuda.is_available():
105
+ return 0.0
106
+ try:
107
+ return torch.cuda.get_device_properties(device).total_memory / 1024**3
108
+ except Exception:
109
+ return 0.0
110
+
111
+
112
+ def purge_windows_standby_cache() -> dict[str, Any]:
113
+ """Purge the Windows standby page list using NtSetSystemInformation.
114
+
115
+ This mirrors tools such as EmptyStandbyList while keeping the behavior optional
116
+ and explicit. The caller must run with a token that can enable
117
+ SeProfileSingleProcessPrivilege.
118
+ """
119
+ if os.name != "nt":
120
+ raise RuntimeError("Windows standby cache purge is only available on Windows.")
121
+
122
+ import ctypes
123
+ from ctypes import wintypes
124
+
125
+ system_memory_list_information = 80
126
+ memory_purge_standby_list = 4
127
+ token_adjust_privileges = 0x0020
128
+ token_query = 0x0008
129
+ se_privilege_enabled = 0x00000002
130
+ error_not_all_assigned = 1300
131
+
132
+ class LUID(ctypes.Structure):
133
+ _fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]
134
+
135
+ class TOKEN_PRIVILEGES(ctypes.Structure):
136
+ _fields_ = [
137
+ ("PrivilegeCount", wintypes.DWORD),
138
+ ("Luid", LUID),
139
+ ("Attributes", wintypes.DWORD),
140
+ ]
141
+
142
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
143
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
144
+ ntdll = ctypes.WinDLL("ntdll")
145
+
146
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
147
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
148
+ kernel32.CloseHandle.restype = wintypes.BOOL
149
+
150
+ advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
151
+ advapi32.OpenProcessToken.restype = wintypes.BOOL
152
+ advapi32.LookupPrivilegeValueW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(LUID)]
153
+ advapi32.LookupPrivilegeValueW.restype = wintypes.BOOL
154
+ advapi32.AdjustTokenPrivileges.argtypes = [
155
+ wintypes.HANDLE,
156
+ wintypes.BOOL,
157
+ ctypes.POINTER(TOKEN_PRIVILEGES),
158
+ wintypes.DWORD,
159
+ ctypes.c_void_p,
160
+ ctypes.c_void_p,
161
+ ]
162
+ advapi32.AdjustTokenPrivileges.restype = wintypes.BOOL
163
+
164
+ ntdll.NtSetSystemInformation.argtypes = [wintypes.ULONG, ctypes.c_void_p, wintypes.ULONG]
165
+ ntdll.NtSetSystemInformation.restype = wintypes.LONG
166
+
167
+ token = wintypes.HANDLE()
168
+ process = kernel32.GetCurrentProcess()
169
+ if not advapi32.OpenProcessToken(process, token_adjust_privileges | token_query, ctypes.byref(token)):
170
+ raise ctypes.WinError(ctypes.get_last_error())
171
+
172
+ try:
173
+ luid = LUID()
174
+ if not advapi32.LookupPrivilegeValueW(None, "SeProfileSingleProcessPrivilege", ctypes.byref(luid)):
175
+ raise ctypes.WinError(ctypes.get_last_error())
176
+
177
+ privileges = TOKEN_PRIVILEGES(1, luid, se_privilege_enabled)
178
+ ctypes.set_last_error(0)
179
+ if not advapi32.AdjustTokenPrivileges(token, False, ctypes.byref(privileges), 0, None, None):
180
+ raise ctypes.WinError(ctypes.get_last_error())
181
+ last_error = ctypes.get_last_error()
182
+ if last_error == error_not_all_assigned:
183
+ raise PermissionError("SeProfileSingleProcessPrivilege is not assigned to this process token.")
184
+ finally:
185
+ kernel32.CloseHandle(token)
186
+
187
+ command = ctypes.c_int(memory_purge_standby_list)
188
+ status = ntdll.NtSetSystemInformation(
189
+ system_memory_list_information,
190
+ ctypes.byref(command),
191
+ ctypes.sizeof(command),
192
+ )
193
+ if status != 0:
194
+ raise OSError(f"NtSetSystemInformation failed with NTSTATUS 0x{status & 0xFFFFFFFF:08X}")
195
+
196
+ return {
197
+ "system_information_class": system_memory_list_information,
198
+ "command": memory_purge_standby_list,
199
+ "privilege": "SeProfileSingleProcessPrivilege",
200
+ }
201
+
202
+
203
+ def purge_windows_standby_cache_event(record_event, event_name: str, *, print_message: bool = True) -> dict[str, Any]:
204
+ event_t0 = time.time()
205
+ result = purge_windows_standby_cache()
206
+ if record_event is not None:
207
+ record_event(event_name, time.time() - event_t0, **result)
208
+ if print_message:
209
+ print(f" [windows-memory] {event_name}: standby cache purge requested", flush=True)
210
+ return result
211
+
212
+
213
+ def maybe_purge_windows_standby_cache(
214
+ settings_or_phase: "DynamicOffloadSettings | str | None" = None,
215
+ phase: str | None = None,
216
+ *,
217
+ settings: "DynamicOffloadSettings | None" = None,
218
+ preset: str = "auto",
219
+ execution_device: str | torch.device = "cuda:0",
220
+ offload_device: str | torch.device = "cpu",
221
+ running_on_wsl: bool | None = None,
222
+ record_event: Any | None = None,
223
+ event_name: str | None = None,
224
+ default: str = "0",
225
+ print_message: bool = True,
226
+ ignore_errors: bool = True,
227
+ environ: Mapping[str, str] | None = None,
228
+ enabled: bool | None = None,
229
+ ) -> dict[str, Any]:
230
+ """Purge Windows standby cache when preset/env enables it for a lifecycle phase.
231
+
232
+ Call either `maybe_purge_windows_standby_cache(settings, "before_run")` or
233
+ `maybe_purge_windows_standby_cache("before_run", preset="auto")`. It is a
234
+ no-op outside Windows, so runners can call the same lifecycle hook on every
235
+ platform while DDO decides whether a purge is useful.
236
+ ``enabled=None`` inherits environment/preset policy; an explicit boolean
237
+ overrides it without modifying process-global environment variables.
238
+ """
239
+ resolved_settings = settings
240
+ resolved_phase = phase
241
+ if isinstance(settings_or_phase, str):
242
+ resolved_phase = settings_or_phase if resolved_phase is None else resolved_phase
243
+ elif settings_or_phase is not None and resolved_settings is None:
244
+ resolved_settings = settings_or_phase
245
+
246
+ if resolved_phase is None:
247
+ raise TypeError("phase is required")
248
+
249
+ if resolved_settings is None:
250
+ resolved_settings = load_dynamic_offload_settings_from_env(
251
+ execution_device=execution_device,
252
+ offload_device=offload_device,
253
+ running_on_wsl=running_on_wsl,
254
+ environ=environ,
255
+ default_preset=preset,
256
+ )
257
+
258
+ key = "DDO_PURGE_WINDOWS_STANDBY_" + resolved_phase.strip().upper()
259
+ enabled = resolved_settings.preset_bool(key, default, environ) if enabled is None else enabled
260
+ if not enabled:
261
+ return {"purged": False, "reason": "disabled", "phase": resolved_phase}
262
+ if os.name != "nt":
263
+ return {"purged": False, "reason": "non_windows", "phase": resolved_phase}
264
+
265
+ resolved_event_name = event_name or key.lower().removeprefix("ddo_")
266
+ try:
267
+ result = purge_windows_standby_cache_event(record_event, resolved_event_name, print_message=print_message)
268
+ except Exception as exc:
269
+ if not ignore_errors:
270
+ raise
271
+ result = {"purged": False, "reason": exc.__class__.__name__, "phase": resolved_phase, "error": str(exc)}
272
+ if record_event is not None:
273
+ record_event(resolved_event_name, 0.0, **result)
274
+ if print_message:
275
+ print(f" [windows-memory] {resolved_event_name}: standby cache purge skipped ({exc})", flush=True)
276
+ return result
277
+ result.update({"purged": True, "phase": resolved_phase})
278
+ return result
279
+
280
+ _DYNAMIC_OFFLOAD_PRESET_VALUES: dict[str, dict[str, str]] = {
281
+ "off": {
282
+ "DDO_EXECUTION_MODE": "plan",
283
+ "DDO_PLAN": "0",
284
+ },
285
+ "diffusers_leaf_offload_compat": {
286
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
287
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
288
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "1",
289
+ "DDO_RUNNER_TEXT_ENCODER_DYNAMIC_OFFLOAD": "0",
290
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
291
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "1",
292
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_TYPE": "leaf_level",
293
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_STREAM": "1",
294
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_RECORD_STREAM": "1",
295
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_LOW_CPU_MEM_USAGE": "1",
296
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
297
+ "DDO_EXECUTION_MODE": "plan",
298
+ "DDO_PLAN": "0",
299
+ "DDO_RUNNER_PRE_VAE_CLEANUP_REPEATS": "1",
300
+ },
301
+ "diffusers_offload_compat": {
302
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
303
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
304
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "1",
305
+ "DDO_RUNNER_TEXT_ENCODER_DYNAMIC_OFFLOAD": "0",
306
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
307
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "1",
308
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_TYPE": "block_level",
309
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_STREAM": "1",
310
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_RECORD_STREAM": "1",
311
+ "DDO_RUNNER_TRANSFORMER_OFFLOAD_LOW_CPU_MEM_USAGE": "1",
312
+ "DDO_RUNNER_TRANSFORMER_NUM_BLOCKS_PER_GROUP": "1",
313
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
314
+ "DDO_EXECUTION_MODE": "plan",
315
+ "DDO_PLAN": "0",
316
+ "DDO_RUNNER_PRE_VAE_CLEANUP_REPEATS": "1",
317
+ },
318
+ "one_shot_fast": {
319
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
320
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
321
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "1",
322
+ "DDO_RUNNER_TEXT_ENCODER_DYNAMIC_OFFLOAD": "0",
323
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
324
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "0",
325
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
326
+ "DDO_EXECUTION_MODE": "linear_runtime",
327
+ "DDO_PIN_CPU_MEMORY": "1",
328
+ "DDO_ALLOW_PIN_MEMORY_FALLBACK": "1",
329
+ "DDO_PIN_CPU_WORKERS": "4",
330
+ "DDO_AUTO_BUDGET_POLICY": "balanced",
331
+ "DDO_MAX_RESIDENT_MODULE_BUDGET_GB": "0",
332
+ "DDO_SYSTEM_RAM_HEADROOM_GB": "8",
333
+ "DDO_RESIDENT_MODULE_BUDGET_GB": "0",
334
+ "DDO_RESIDENT_MODULE_PATTERNS": "auto",
335
+ "DDO_RESIDENT_MODULE_SELECTION": "spread",
336
+ "DDO_SMALL_TENSOR_THRESHOLD_KB": "1024",
337
+ "DDO_RUNNER_PRE_VAE_CLEANUP_REPEATS": "1",
338
+ "DDO_PURGE_WINDOWS_STANDBY_BEFORE_RUN": "1",
339
+ "DDO_PURGE_WINDOWS_STANDBY_AFTER_TEXT_ENCODER": "1",
340
+ "DDO_PURGE_WINDOWS_STANDBY_BEFORE_TRANSFORMER": "1",
341
+ },
342
+ "wsl_compat": {
343
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
344
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
345
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "0",
346
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
347
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "0",
348
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
349
+ "DDO_EXECUTION_MODE": "linear_runtime",
350
+ "DDO_PIN_CPU_MEMORY": "0",
351
+ "DDO_ALLOW_PIN_MEMORY_FALLBACK": "1",
352
+ "DDO_DISABLE_PIN_ON_WSL": "1",
353
+ "DDO_PIN_CPU_WORKERS": "1",
354
+ "DDO_AUTO_BUDGET_POLICY": "off",
355
+ "DDO_RESIDENT_MODULE_BUDGET_GB": "6",
356
+ "DDO_RESIDENT_MODULE_PATTERNS": "auto",
357
+ "DDO_RESIDENT_MODULE_SELECTION": "spread",
358
+ "DDO_SMALL_TENSOR_THRESHOLD_KB": "1024",
359
+ "DDO_RUNNER_PRE_VAE_CLEANUP_REPEATS": "3",
360
+ },
361
+ "warm_process": {
362
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
363
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
364
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "1",
365
+ "DDO_RUNNER_TEXT_ENCODER_DYNAMIC_OFFLOAD": "0",
366
+ "DDO_RUNNER_GENERATION_REPEATS": "2",
367
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
368
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "0",
369
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
370
+ "DDO_EXECUTION_MODE": "linear_runtime",
371
+ "DDO_PIN_CPU_MEMORY": "1",
372
+ "DDO_ALLOW_PIN_MEMORY_FALLBACK": "1",
373
+ "DDO_PIN_CPU_WORKERS": "4",
374
+ "DDO_CACHE_PINNED_WEIGHTS": "1",
375
+ "DDO_AUTO_BUDGET_POLICY": "off",
376
+ "DDO_RESIDENT_MODULE_BUDGET_GB": "6",
377
+ "DDO_RESIDENT_MODULE_PATTERNS": "auto",
378
+ "DDO_RESIDENT_MODULE_SELECTION": "spread",
379
+ "DDO_SMALL_TENSOR_THRESHOLD_KB": "1024",
380
+ },
381
+ "low_ram_safe": {
382
+ "DDO_RUNNER_TEXT_ENCODER_GROUP_OFFLOAD": "1",
383
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_TYPE": "leaf_level",
384
+ "DDO_RUNNER_TEXT_ENCODER_OFFLOAD_STREAM": "0",
385
+ "DDO_RUNNER_TEXT_ENCODER_DYNAMIC_OFFLOAD": "0",
386
+ "DDO_RUNNER_TRANSFORMER_MEMORY_MANAGER": "off",
387
+ "DDO_RUNNER_TRANSFORMER_GROUP_OFFLOAD": "0",
388
+ "DDO_RUNNER_ATTENTION_BACKEND": "native",
389
+ "DDO_EXECUTION_MODE": "linear_runtime",
390
+ "DDO_PIN_CPU_MEMORY": "0",
391
+ "DDO_ALLOW_PIN_MEMORY_FALLBACK": "1",
392
+ "DDO_PIN_CPU_WORKERS": "1",
393
+ "DDO_AUTO_BUDGET_POLICY": "off",
394
+ "DDO_RESIDENT_MODULE_BUDGET_GB": "3",
395
+ "DDO_RESIDENT_MODULE_PATTERNS": "auto",
396
+ "DDO_RESIDENT_MODULE_SELECTION": "spread",
397
+ "DDO_SMALL_TENSOR_THRESHOLD_KB": "1024",
398
+ },
399
+ }
400
+
401
+
402
+ DDO_PRESETS = _DYNAMIC_OFFLOAD_PRESET_VALUES
403
+
404
+ # Component routing is independent of transformer residency/planner defaults.
405
+ _VAE_LEAF_POLICY = {
406
+ "ROUTE": "diffusers_group_offload", "OFFLOAD_TYPE": "leaf_level",
407
+ "OFFLOAD_STREAM": "0", "OFFLOAD_LOW_CPU_MEM_USAGE": "0",
408
+ }
409
+ _PRESET_COMPONENT_POLICIES = {
410
+ "one_shot_fast": {"vae": _VAE_LEAF_POLICY},
411
+ "low_ram_safe": {"vae": _VAE_LEAF_POLICY},
412
+ "vmm_fast": {"vae": _VAE_LEAF_POLICY},
413
+ # Preserve the historical staged-host resident VAE for unvalidated presets.
414
+ "warm_process": {"vae": {"ROUTE": "none"}},
415
+ "wsl_compat": {"vae": {"ROUTE": "none"}},
416
+ "nvme_baseline": {"vae": {"ROUTE": "none"}},
417
+ }
418
+
419
+
420
+ def get_dynamic_offload_presets() -> dict[str, dict[str, str]]:
421
+ return {preset_name: dict(values) for preset_name, values in DDO_PRESETS.items()}
422
+
423
+
424
+ def format_dynamic_offload_presets(*, default_preset: str = "auto", running_on_wsl: bool | None = None) -> str:
425
+ resolved_default = resolve_dynamic_offload_preset(default_preset, running_on_wsl=running_on_wsl)
426
+ lines = [
427
+ "DDO presets",
428
+ f" {default_preset} -> {resolved_default}",
429
+ ]
430
+ for preset_name in sorted(DDO_PRESETS):
431
+ lines.append(f"\n{preset_name}")
432
+ preset_values = DDO_PRESETS[preset_name]
433
+ if not preset_values:
434
+ lines.append(" <no preset values>")
435
+ continue
436
+ for key in sorted(preset_values):
437
+ lines.append(f" {key}={preset_values[key]}")
438
+ return "\n".join(lines)
439
+
440
+
441
+ def resolve_dynamic_offload_preset(requested_preset: str, *, running_on_wsl: bool | None = None) -> str:
442
+ requested_preset = requested_preset.strip().lower()
443
+ if requested_preset != "auto":
444
+ if requested_preset and requested_preset not in DDO_PRESETS:
445
+ valid_presets = ", ".join(["auto", *sorted(DDO_PRESETS)])
446
+ raise ValueError(
447
+ f"Invalid DDO_PRESET={requested_preset!r}. "
448
+ f"Valid values: {valid_presets}"
449
+ )
450
+ return requested_preset
451
+
452
+ return "one_shot_fast"
453
+
454
+
455
+ def dynamic_offload_preset_env_value(
456
+ name: str,
457
+ default: str = "",
458
+ *,
459
+ requested_preset: str = "",
460
+ effective_preset: str | None = None,
461
+ running_on_wsl: bool | None = None,
462
+ environ: Mapping[str, str] | None = None,
463
+ ) -> str:
464
+ env = os.environ if environ is None else environ
465
+ if name in env:
466
+ return env[name]
467
+
468
+ preset_name = effective_preset
469
+ if preset_name is None:
470
+ preset_name = resolve_dynamic_offload_preset(requested_preset, running_on_wsl=running_on_wsl)
471
+ if not preset_name:
472
+ return default
473
+
474
+ # Native backend presets do not inherit linear planner/lifecycle defaults.
475
+ # Explicit environment overrides above still apply to shared helpers.
476
+ if preset_name in {"vmm_fast", "nvme_baseline"}:
477
+ return default
478
+
479
+ preset_values = DDO_PRESETS[preset_name]
480
+ return preset_values.get(name, default)
481
+
482
+
483
+ def _parse_bool_value(value: str) -> bool:
484
+ return value.strip().lower() in {"1", "true", "yes", "on"}
485
+
486
+
487
+ def _parse_pattern_list_value(value: str) -> tuple[str, ...]:
488
+ return tuple(item.strip() for item in re.split(r"[;,]", value) if item.strip())
489
+
490
+
491
+ def _native_source_cache_transport_config(
492
+ staging_bytes: int, slot_mb: int, slots: int, host_cache_gb: float, *, native_transport: bool = False,
493
+ source_cache_gb: float = 0.0, source_registered_gb: float = 0.0
494
+ ) -> dict[str, int]:
495
+ """Resolve a total native ring capacity, independently of cache admission.
496
+
497
+ Cache opt-in also selects the native ring. Explicit native transport allows
498
+ cache-off controls to use the same ring without allocating PyTorch staging.
499
+ """
500
+ if not math.isfinite(source_cache_gb) or source_cache_gb < 0 or source_cache_gb > 32:
501
+ raise ValueError("native model source cache must be finite and between 0 and 32 GiB")
502
+ if not math.isfinite(source_registered_gb) or source_registered_gb < 0 or source_registered_gb > source_cache_gb:
503
+ raise ValueError("native source registration ceiling must be finite, non-negative and <= retained capacity")
504
+ model_windows = source_cache_gb > 0
505
+ if model_windows and (slot_mb or slots):
506
+ raise ValueError("choose model source-cache GiB or legacy cache slots, not both")
507
+ if model_windows:
508
+ slot_mb = 64
509
+ slots = math.ceil(source_cache_gb * 1024 / slot_mb)
510
+ cache_requested = bool(slot_mb or slots)
511
+ if not cache_requested and not native_transport:
512
+ return {}
513
+ if cache_requested and (slot_mb <= 0 or slots <= 0):
514
+ raise ValueError("vmm_fast native source cache requires positive slot MB and slot count together")
515
+ if cache_requested and host_cache_gb:
516
+ raise ValueError("vmm_fast native source cache cannot share the unaccounted CPU weight registry")
517
+ if staging_bytes <= 0:
518
+ raise ValueError("vmm_fast native transport requires positive staging bytes")
519
+ cache_slot_bytes = slot_mb * 1024**2
520
+ window_bytes = min(64 * 1024**2, staging_bytes)
521
+ staging_slots = (staging_bytes + window_bytes - 1) // window_bytes
522
+ process_limit_bytes = window_bytes * staging_slots + cache_slot_bytes * slots
523
+ if not cache_requested and staging_bytes > 2 * 1024**3:
524
+ raise ValueError("native ring total capacity must be <=2 GiB")
525
+ if (cache_slot_bytes > 64 * 1024**2
526
+ or cache_slot_bytes * slots > (32 * 1024**3 if model_windows else 128 * 1024**2)
527
+ or (cache_requested and process_limit_bytes > (40 * 1024**3 if model_windows else 1024**3))):
528
+ raise ValueError(
529
+ "vmm_fast native source cache requires slot <=64 MiB, cache <=128 MiB "
530
+ "and registered staging + cache <=1 GiB"
531
+ )
532
+ transport = {
533
+ "native_transport_slot_size_bytes": window_bytes,
534
+ "native_transport_slots": staging_slots,
535
+ }
536
+ if not cache_requested:
537
+ return transport
538
+ config = {
539
+ **transport,
540
+ "native_source_cache_slot_bytes": cache_slot_bytes,
541
+ "native_source_cache_slots": slots,
542
+ "native_source_cache_process_limit_bytes": process_limit_bytes,
543
+ }
544
+ if model_windows:
545
+ config["native_source_cache_model_windows"] = True
546
+ if source_registered_gb:
547
+ registered_bytes = int(source_registered_gb * 1024**3)
548
+ if registered_bytes < cache_slot_bytes or registered_bytes % cache_slot_bytes:
549
+ raise ValueError("native source registration ceiling must cover whole 64 MiB segments")
550
+ config["native_source_cache_registered_limit_bytes"] = registered_bytes
551
+ return config
552
+
553
+
554
+ @dataclass(frozen=True)
555
+ class DynamicOffloadConfig:
556
+ """Configuration for the experimental dynamic offload planner/runtime."""
557
+
558
+ execution_device: str | torch.device = "cuda:0"
559
+ offload_device: str | torch.device = "cpu"
560
+ target_module_classes: tuple[type[nn.Module], ...] = _DEFAULT_TARGET_MODULE_CLASSES
561
+ skip_modules_pattern: tuple[str, ...] = ()
562
+ always_resident_modules_pattern: tuple[str, ...] = ()
563
+ small_tensor_threshold_bytes: int = 16 * 1024
564
+ execution_mode: str = "plan"
565
+ linear_runtime_strategy: str = "functional"
566
+ linear_convolution_offload: bool = False
567
+ vmm_resident_weight_budget_gb: float = 0.0
568
+ vmm_staging_buffer_gb: float = 0.625
569
+ vmm_windows_file_read_chunk_mb: int = 2
570
+ vmm_virtual_host_transport: bool = False
571
+ # Explicitly use native registered-host windows with or without source
572
+ # retention. The staging budget is total capacity, not capacity per slot.
573
+ vmm_native_transport: bool = False
574
+ vmm_source_cache_gb: float = 0.0
575
+ vmm_source_registered_gb: float = 0.0
576
+ vmm_module_pattern: str = r".*"
577
+ # Experimental full-component ownership; never changes the default route.
578
+ vmm_component_tensor_ownership: bool = False
579
+ vmm_float8_weight_only: bool = False
580
+ vmm_execution_auxiliary_ownership: bool = False
581
+ vmm_component_buffer_limit_mb: int = 1
582
+ vmm_page_mb: int = 0
583
+ vmm_dxgi_local_headroom_gb: float = 0.0
584
+ vmm_dxgi_shared_headroom_gb: float = 0.0
585
+ vmm_dxgi_system_headroom_gb: float = 0.0
586
+ # Optional persistent cache of existing CPU source pages registered with
587
+ # CUDA. It never allocates CUDA managed memory. Pages beyond this budget
588
+ # retain the bounded checkpoint-file transport.
589
+ vmm_host_cache_gb: float = 0.0
590
+ # Experimental native retained-source cache. Zero slots preserve the
591
+ # configured staging route; local cache and aggregate process caps
592
+ # are validated separately before constructing the arena.
593
+ vmm_native_source_cache_slot_mb: int = 0
594
+ vmm_native_source_cache_slots: int = 0
595
+ vmm_pin_source_weights: bool = False
596
+ vmm_fault_fallback: bool = False
597
+ pin_cpu_memory: bool = False
598
+ allow_pin_memory_fallback: bool = True
599
+ pin_cpu_workers: int = 1
600
+ cache_plan: bool = True
601
+ cache_pinned_weights: bool = False
602
+ pinned_weight_cache_namespace: str = ""
603
+ auto_budget_policy: str = _AUTO_BUDGET_DISABLED
604
+ max_resident_module_budget_gb: float = 6.0
605
+ auto_vram_headroom_gb: float = 0.0
606
+ profile_vram_headroom_gb: float = 1.0
607
+ profile_name: str = ""
608
+ build_profile: bool = False
609
+ auto_full_pin_min_model_to_vram_ratio: float = 4.0
610
+ # Internal transfer value populated by DynamicOffloadProfileSession. It is
611
+ # deliberately not an environment setting: callers use a stored capacity
612
+ # profile or the explicit resident_module_budget_gb override instead.
613
+ profile_resident_module_budget_gb: float = 0.0
614
+ _profile_budget_applied: bool = False
615
+ max_pin_weight_budget_gb: float = 0.0
616
+ available_system_ram_gb: float = 0.0
617
+ system_ram_headroom_gb: float = 6.0
618
+ pin_weight_budget_gb: float = 0.0
619
+ pin_weight_budget_ratio: float = 0.0
620
+ pin_weight_selection: str = "spread"
621
+ resident_module_budget_gb: float = 0.0
622
+ resident_module_patterns: tuple[str, ...] = ()
623
+ resident_module_selection: str = "spread"
624
+ load_safetensors_backend: str = ""
625
+ verbose: bool = False
626
+ show_profile: bool = True
627
+
628
+ def __post_init__(self):
629
+ if self.linear_convolution_offload:
630
+ if self.execution_mode != "linear_runtime":
631
+ raise ValueError("Convolution offload is only available in linear_runtime")
632
+ targets = self.target_module_classes + tuple(
633
+ kind for kind in (nn.Conv1d, nn.Conv2d, nn.Conv3d) if kind not in self.target_module_classes
634
+ )
635
+ object.__setattr__(self, "target_module_classes", targets)
636
+
637
+
638
+ @dataclass(frozen=True)
639
+ class DynamicOffloadSettings:
640
+ """Environment-derived dynamic offload settings plus the resolved runtime config."""
641
+
642
+ requested_preset: str
643
+ effective_preset: str
644
+ enabled: bool
645
+ plan: bool
646
+ config: DynamicOffloadConfig
647
+ requested_pin_cpu_memory: bool
648
+ effective_pin_cpu_memory: bool
649
+ disable_pin_on_wsl: bool
650
+ running_on_wsl: bool
651
+ component_policies: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
652
+
653
+ @property
654
+ def execution_mode(self) -> str:
655
+ return self.config.execution_mode
656
+
657
+ def preset_value(self, name: str, default: str = "", environ: Mapping[str, str] | None = None) -> str:
658
+ return dynamic_offload_preset_env_value(
659
+ name,
660
+ default,
661
+ requested_preset=self.requested_preset,
662
+ effective_preset=self.effective_preset,
663
+ running_on_wsl=self.running_on_wsl,
664
+ environ=environ,
665
+ )
666
+
667
+ def preset_bool(self, name: str, default: str = "0", environ: Mapping[str, str] | None = None) -> bool:
668
+ return _parse_bool_value(self.preset_value(name, default, environ))
669
+
670
+ def as_metrics(self) -> dict[str, Any]:
671
+ config = self.config
672
+ return {
673
+ "dynamic_offload_requested_preset": self.requested_preset or None,
674
+ "dynamic_offload_effective_preset": self.effective_preset or None,
675
+ "dynamic_offload_execution_mode": config.execution_mode,
676
+ "dynamic_offload_linear_runtime_strategy": config.linear_runtime_strategy,
677
+ "dynamic_offload_vmm_resident_weight_budget_gb": config.vmm_resident_weight_budget_gb,
678
+ "dynamic_offload_vmm_staging_buffer_gb": config.vmm_staging_buffer_gb,
679
+ "dynamic_offload_vmm_windows_file_read_chunk_mb": config.vmm_windows_file_read_chunk_mb,
680
+ "dynamic_offload_vmm_virtual_host_transport": config.vmm_virtual_host_transport,
681
+ "dynamic_offload_vmm_native_transport": config.vmm_native_transport,
682
+ "dynamic_offload_vmm_source_cache_gb": config.vmm_source_cache_gb,
683
+ "dynamic_offload_vmm_source_registered_gb": config.vmm_source_registered_gb,
684
+ "dynamic_offload_vmm_module_pattern": config.vmm_module_pattern,
685
+ "dynamic_offload_vmm_component_tensor_ownership": config.vmm_component_tensor_ownership,
686
+ "dynamic_offload_vmm_float8_weight_only": config.vmm_float8_weight_only,
687
+ "dynamic_offload_vmm_execution_auxiliary_ownership": config.vmm_execution_auxiliary_ownership,
688
+ "dynamic_offload_vmm_component_buffer_limit_mb": config.vmm_component_buffer_limit_mb,
689
+ "dynamic_offload_vmm_page_mb": config.vmm_page_mb,
690
+ "dynamic_offload_vmm_dxgi_local_headroom_gb": config.vmm_dxgi_local_headroom_gb,
691
+ "dynamic_offload_vmm_dxgi_shared_headroom_gb": config.vmm_dxgi_shared_headroom_gb,
692
+ "dynamic_offload_vmm_dxgi_system_headroom_gb": config.vmm_dxgi_system_headroom_gb,
693
+ "dynamic_offload_vmm_host_cache_gb": config.vmm_host_cache_gb,
694
+ "dynamic_offload_vmm_native_source_cache_slot_mb": config.vmm_native_source_cache_slot_mb,
695
+ "dynamic_offload_vmm_native_source_cache_slots": config.vmm_native_source_cache_slots,
696
+ "dynamic_offload_vmm_pin_source_weights": config.vmm_pin_source_weights,
697
+ "dynamic_offload_vmm_fault_fallback": config.vmm_fault_fallback,
698
+ "dynamic_offload_pin_cpu_memory": self.requested_pin_cpu_memory,
699
+ "dynamic_offload_effective_pin_cpu_memory": self.effective_pin_cpu_memory,
700
+ "dynamic_offload_allow_pin_memory_fallback": config.allow_pin_memory_fallback,
701
+ "dynamic_offload_disable_pin_on_wsl": self.disable_pin_on_wsl,
702
+ "dynamic_offload_pin_cpu_workers": config.pin_cpu_workers,
703
+ "dynamic_offload_cache_plan": config.cache_plan,
704
+ "dynamic_offload_cache_pinned_weights": config.cache_pinned_weights,
705
+ "dynamic_offload_pinned_weight_cache_namespace": config.pinned_weight_cache_namespace or None,
706
+ "dynamic_offload_auto_budget_policy": config.auto_budget_policy,
707
+ "dynamic_offload_max_resident_module_budget_gb": config.max_resident_module_budget_gb,
708
+ "dynamic_offload_auto_vram_headroom_gb": config.auto_vram_headroom_gb,
709
+ "dynamic_offload_profile_vram_headroom_gb": config.profile_vram_headroom_gb,
710
+ "dynamic_offload_profile_name": config.profile_name or None,
711
+ "dynamic_offload_build_profile": config.build_profile,
712
+ "dynamic_offload_auto_full_pin_min_model_to_vram_ratio": (
713
+ config.auto_full_pin_min_model_to_vram_ratio
714
+ ),
715
+ "dynamic_offload_profile_resident_module_budget_gb": config.profile_resident_module_budget_gb,
716
+ "dynamic_offload_max_pin_weight_budget_gb": config.max_pin_weight_budget_gb,
717
+ "dynamic_offload_available_system_ram_gb": config.available_system_ram_gb,
718
+ "dynamic_offload_system_ram_headroom_gb": config.system_ram_headroom_gb,
719
+ "dynamic_offload_pin_weight_budget_gb": config.pin_weight_budget_gb,
720
+ "dynamic_offload_pin_weight_budget_ratio": config.pin_weight_budget_ratio,
721
+ "dynamic_offload_pin_weight_selection": config.pin_weight_selection,
722
+ "dynamic_offload_small_tensor_threshold_kb": config.small_tensor_threshold_bytes // 1024,
723
+ "dynamic_offload_resident_module_budget_gb": config.resident_module_budget_gb,
724
+ "dynamic_offload_resident_module_patterns": config.resident_module_patterns,
725
+ "dynamic_offload_resident_module_selection": config.resident_module_selection,
726
+ "dynamic_offload_load_safetensors_backend": config.load_safetensors_backend or None,
727
+ "dynamic_offload_show_profile": config.show_profile,
728
+ "dynamic_offload_component_policies": dict(self.component_policies),
729
+ }
730
+
731
+ @classmethod
732
+ def from_env(cls, **kwargs: Any) -> "DynamicOffloadSettings":
733
+ return load_dynamic_offload_settings_from_env(**kwargs)
734
+
735
+
736
+ def build_dynamic_offload_event_payload(
737
+ settings: DynamicOffloadSettings,
738
+ state: "DynamicOffloadState",
739
+ config: DynamicOffloadConfig | None = None,
740
+ ) -> dict[str, Any]:
741
+ summary = state.as_dict()
742
+ config = config or settings.config
743
+ return {
744
+ "module_count": summary["module_count"],
745
+ "total_gb": summary["total_gb"],
746
+ "bytes_by_placement": summary["bytes_by_placement"],
747
+ "execution_mode": config.execution_mode,
748
+ "pin_cpu_memory": settings.effective_pin_cpu_memory,
749
+ "allow_pin_memory_fallback": config.allow_pin_memory_fallback,
750
+ "cache_plan": config.cache_plan,
751
+ "cache_pinned_weights": config.cache_pinned_weights,
752
+ "pinned_weight_cache_namespace": config.pinned_weight_cache_namespace or None,
753
+ "load_safetensors_backend": config.load_safetensors_backend or None,
754
+ "auto_budget_policy": config.auto_budget_policy,
755
+ "max_resident_module_budget_gb": config.max_resident_module_budget_gb,
756
+ "auto_full_pin_min_model_to_vram_ratio": config.auto_full_pin_min_model_to_vram_ratio,
757
+ "profile_resident_module_budget_gb": config.profile_resident_module_budget_gb,
758
+ "max_pin_weight_budget_gb": config.max_pin_weight_budget_gb,
759
+ "available_system_ram_gb": config.available_system_ram_gb,
760
+ "system_ram_headroom_gb": config.system_ram_headroom_gb,
761
+ "pin_weight_budget_gb": config.pin_weight_budget_gb,
762
+ "pin_weight_budget_ratio": config.pin_weight_budget_ratio,
763
+ "pin_weight_selection": config.pin_weight_selection,
764
+ "patched_module_count": summary["patched_module_count"],
765
+ "sdnq_parameter_pinning": summary["sdnq_parameter_pinning"],
766
+ "resolved_resident_module_patterns": summary["resolved_resident_module_patterns"],
767
+ "planner_decisions": summary["planner_decisions"],
768
+ "setup_runtime": summary["setup_runtime"],
769
+ }
770
+
771
+
772
+ def detect_quantized_backend_modules(module: nn.Module) -> dict[str, Any]:
773
+ sdnq_module_count = sum(1 for child in module.modules() if _is_sdnq_module(child))
774
+ if not sdnq_module_count:
775
+ return {}
776
+ return {"sdnq_module_count": sdnq_module_count, "sdnq_status": "detected_forward_preserved"}
777
+
778
+
779
+ def _is_sdnq_module(module: nn.Module) -> bool:
780
+ """Recognize both SDNQ storage formats without importing SDNQ itself.
781
+
782
+ SDNQ 0.2.x normally exposes ``sdnq_dequantizer`` on a wrapped layer, but
783
+ dynamic checkpoints may instead store an ``SDNQTensor`` directly in its
784
+ ``weight`` parameter. Both retain ``forward_func`` and require the native
785
+ SDNQ forward, never DDO's dense-linear runtime.
786
+ """
787
+ if not hasattr(module, "forward_func"):
788
+ return False
789
+ if hasattr(module, "sdnq_dequantizer"):
790
+ return True
791
+ return getattr(getattr(module, "weight", None).__class__, "__name__", "") == "SDNQTensor"
792
+
793
+
794
+ @dataclass(frozen=True)
795
+ class DynamicOffloadPlanEntry:
796
+ module_name: str
797
+ module_type: str
798
+ tensor_name: str
799
+ shape: tuple[int, ...]
800
+ dtype: str
801
+ device: str
802
+ bytes: int
803
+ placement: str
804
+
805
+
806
+ @dataclass
807
+ class DynamicOffloadLoadResult:
808
+ module: nn.Module
809
+ hook: "DynamicOffloadHook | None" = None
810
+ should_move_to_execution_device: bool = True
811
+ _profile: Any = field(default=None, repr=False)
812
+
813
+ def inspect_vmm_component(self, *, component="model", buffer_limit_bytes=1024**2) -> DynamicOffloadMetrics:
814
+ """Loaded immutable-source/ownership preflight, without CUDA or attach.
815
+
816
+ Returns detached geometry, not an admission/residency decision or proof
817
+ of numerical support. The optional allocator is needed only on request.
818
+ """
819
+ if not isinstance(component, str) or not component.strip():
820
+ raise ValueError("component must be a nonempty string")
821
+ from ddo_vmm_allocator.component_arena_adapter import discover_component_layout
822
+
823
+ if getattr(self.module, "_ddo_float8_weight_only_loaded", False):
824
+ from ddo_vmm_allocator.quantized_arena_adapter import discover_float8_component_layout
825
+
826
+ layout, _ = discover_float8_component_layout(
827
+ self.module, getattr(self.module, "_ddo_safetensor_slices", None),
828
+ buffer_limit_bytes=buffer_limit_bytes)
829
+ else:
830
+ layout = discover_component_layout(
831
+ self.module, getattr(self.module, "_ddo_safetensor_slices", None),
832
+ buffer_limit_bytes=buffer_limit_bytes,
833
+ )
834
+ return DynamicOffloadMetrics(
835
+ route="vmm_component_preflight", configuration={"component": component},
836
+ setup={**self.metrics_snapshot().as_dict()["setup"],
837
+ "component_capacity": layout.capacity_snapshot()},
838
+ )
839
+
840
+ def metrics_snapshot(self) -> DynamicOffloadMetrics:
841
+ """Loader-source metadata only; no CUDA/device queries or hook inspection."""
842
+ from copy import deepcopy
843
+
844
+ return DynamicOffloadMetrics(
845
+ route="model_load",
846
+ setup={"weight_source": deepcopy(getattr(self.module, "_ddo_safetensor_slice_summary", {}))},
847
+ )
848
+
849
+ def profile_run(self):
850
+ """Measure and save a calibration; a no-op for ordinary inference."""
851
+ return self._profile.measure() if self._profile is not None else contextlib.nullcontext()
852
+
853
+
854
+ @dataclass
855
+ class DynamicOffloadApplyResult:
856
+ module: nn.Module
857
+ hook: "DynamicOffloadHook | None" = None
858
+ settings: DynamicOffloadSettings | None = None
859
+ should_move_to_execution_device: bool = True
860
+ event_payload: dict[str, Any] = field(default_factory=dict)
861
+ route: str = "dynamic_offload"
862
+ _profile: Any = field(default=None, repr=False)
863
+
864
+ def detach_auxiliary_cpu_sources(self, *, enabled=False, max_copy_bytes=16 * 1024**2):
865
+ """Opt-in bounded residual CPU source detachment before native inference."""
866
+ from .auxiliary_sources import detach_auxiliary_cpu_sources
867
+
868
+ return detach_auxiliary_cpu_sources(self, enabled=enabled, max_copy_bytes=max_copy_bytes)
869
+
870
+ def profile_run(self):
871
+ """Measure and save a calibration; a no-op for ordinary inference."""
872
+ return self._profile.measure() if self._profile is not None else contextlib.nullcontext()
873
+
874
+ @contextlib.contextmanager
875
+ def cleanup_on_error(self):
876
+ """Unwind an attached component on failure; successful cleanup is unchanged.
877
+
878
+ Keep the original exception when native cleanup also fails. Failed
879
+ retirement remains owned by the hook; this does not reset the device,
880
+ force-release views or claim recovery from a poisoned CUDA context.
881
+ """
882
+ try:
883
+ yield self
884
+ except BaseException as error:
885
+ if self.hook is not None:
886
+ try:
887
+ remove_dynamic_offload(self.module)
888
+ except BaseException as cleanup_error:
889
+ # add_note is unavailable on Python 3.10. Retain a detached
890
+ # diagnostic there, without replacing the forward failure.
891
+ try:
892
+ note = f"DDO component cleanup also failed: {cleanup_error!r}"
893
+ if hasattr(error, "add_note"):
894
+ error.add_note(note)
895
+ else:
896
+ error.ddo_cleanup_error = cleanup_error
897
+ except BaseException:
898
+ pass # Even diagnostic failure must not mask the original.
899
+ raise
900
+
901
+ def allocation_diagnostics(self, *, enabled=False):
902
+ """Diagnostic-only process scope; disabled mode never inspects native/CUDA."""
903
+ from .allocation_diagnostics import DynamicOffloadAllocationDiagnostics
904
+ native = None
905
+ if enabled:
906
+ store = getattr(self.hook, "_vmm_fast_store", None)
907
+ if store is None:
908
+ raise ValueError("Allocation diagnostics require an active vmm_fast component")
909
+ native = store.native._owner
910
+ return DynamicOffloadAllocationDiagnostics(enabled=enabled, native=native)
911
+
912
+ def operator_diagnostics(self, *, enabled=False, module_path=None,
913
+ invocations=(0, 2), output_dir=None, use_cuda=True):
914
+ """Explicit sampled operator profiler; may synchronize, never a benchmark."""
915
+ from .operator_diagnostics import DynamicOffloadOperatorDiagnostics
916
+ return DynamicOffloadOperatorDiagnostics(enabled=enabled, module=self.module,
917
+ module_path=module_path, invocations=invocations, output_dir=output_dir, use_cuda=use_cuda)
918
+
919
+ def execution_timer(self, *, enabled=False, native_units=False, native_capacity=4096,
920
+ diagnostic_step_wait=False):
921
+ """Opt-in event timing; ordinary inference remains unchanged."""
922
+ from .timing import DynamicOffloadExecutionTimer
923
+ device = self.settings.config.execution_device if self.settings is not None else "cuda"
924
+ factory = None
925
+ if diagnostic_step_wait and not native_units:
926
+ raise ValueError("diagnostic step wait requires native unit timing on vmm_fast")
927
+ if native_units:
928
+ if not isinstance(native_capacity, int) or not 1 <= native_capacity <= 8192:
929
+ raise ValueError("native timeline capacity must be an integer in 1..8192")
930
+ store = getattr(self.hook, "_vmm_fast_store", None)
931
+ if not enabled or store is None:
932
+ raise ValueError("native unit timing requires enabled timing and an active vmm_fast component")
933
+ def factory(stream):
934
+ from ddo_vmm_allocator.timeline import NativeTimeline
935
+ timeline = NativeTimeline(store.native._owner, capacity=native_capacity, stream=stream)
936
+ timeline.units = dict(getattr(store, "_timeline_units", {}))
937
+ store._timeline = timeline
938
+ return timeline, lambda: setattr(store, "_timeline", None)
939
+ return DynamicOffloadExecutionTimer(enabled=enabled, device=device, native_factory=factory,
940
+ diagnostic_step_wait=diagnostic_step_wait)
941
+
942
+ def metrics_journal(self, directory, *, enabled=False):
943
+ """Create an opt-in public partial-report journal, without CUDA waits."""
944
+ from .metrics_journal import DynamicOffloadMetricsJournal
945
+
946
+ return DynamicOffloadMetricsJournal(self, directory, enabled=enabled)
947
+
948
+ def metrics_snapshot(self, *, collect_completed=False, execution_timing=None) -> DynamicOffloadMetrics:
949
+ """Return a runner-neutral telemetry snapshot without exposing hook internals."""
950
+ configuration = self.settings.as_metrics() if self.settings is not None else {}
951
+ runtime: dict[str, Any] = {}
952
+ if self.hook is not None:
953
+ if collect_completed:
954
+ runtime["completion_collection"] = self.hook.collect_completed_runtime_resources()
955
+ runtime["state"] = self.hook.state.as_dict()
956
+ vmm_stats = self.hook.vmm_runtime_stats()
957
+ if vmm_stats is not None:
958
+ runtime["vmm"] = vmm_stats
959
+ component_report = getattr(getattr(self.hook, "_vmm_fast_adapter", None), "component_report", None)
960
+ if component_report is not None:
961
+ runtime["component_ownership"] = dict(component_report)
962
+ auxiliary_report = getattr(getattr(self.hook, "_vmm_fast_adapter", None), "auxiliary_report", None)
963
+ if auxiliary_report is not None:
964
+ runtime["execution_auxiliary_ownership"] = dict(auxiliary_report)
965
+ report = DynamicOffloadMetrics(
966
+ route=self.route,
967
+ configuration=configuration,
968
+ setup=self.event_payload,
969
+ runtime=runtime,
970
+ )
971
+ return execution_timing.attach(report) if execution_timing is not None else report
972
+
973
+
974
+ @dataclass
975
+ class DiffusersGroupOffloadResult:
976
+ module: nn.Module
977
+ event_payload: dict[str, Any] = field(default_factory=dict)
978
+
979
+
980
+ @dataclass
981
+ class DynamicOffloadState:
982
+ entries: list[DynamicOffloadPlanEntry] = field(default_factory=list)
983
+ module_count: int = 0
984
+ total_bytes: int = 0
985
+ bytes_by_placement: dict[str, int] = field(default_factory=dict)
986
+ setup_seconds_by_action: dict[str, float] = field(default_factory=dict)
987
+ setup_bytes_by_action: dict[str, int] = field(default_factory=dict)
988
+ copy_seconds_by_name: dict[str, float] = field(default_factory=dict)
989
+ copy_bytes_by_name: dict[str, int] = field(default_factory=dict)
990
+ copy_calls_by_name: dict[str, int] = field(default_factory=dict)
991
+ patched_module_count: int = 0
992
+ selected_resident_modules: list[str] = field(default_factory=list)
993
+ selected_resident_linear_weights: list[str] = field(default_factory=list)
994
+ selected_pinned_linear_weights: list[str] = field(default_factory=list)
995
+ resolved_resident_module_patterns: list[str] = field(default_factory=list)
996
+ sdnq_pinned_parameter_bytes: int = 0
997
+ sdnq_pinned_parameter_count: int = 0
998
+ sdnq_unpinned_parameter_bytes: int = 0
999
+ sdnq_unpinned_parameter_count: int = 0
1000
+ planner_decisions: dict[str, Any] = field(default_factory=dict)
1001
+
1002
+ def clone_for_runtime(self) -> "DynamicOffloadState":
1003
+ return DynamicOffloadState(
1004
+ entries=list(self.entries),
1005
+ module_count=self.module_count,
1006
+ total_bytes=self.total_bytes,
1007
+ bytes_by_placement=dict(self.bytes_by_placement),
1008
+ resolved_resident_module_patterns=list(self.resolved_resident_module_patterns),
1009
+ sdnq_pinned_parameter_bytes=self.sdnq_pinned_parameter_bytes,
1010
+ sdnq_pinned_parameter_count=self.sdnq_pinned_parameter_count,
1011
+ sdnq_unpinned_parameter_bytes=self.sdnq_unpinned_parameter_bytes,
1012
+ sdnq_unpinned_parameter_count=self.sdnq_unpinned_parameter_count,
1013
+ planner_decisions=dict(self.planner_decisions),
1014
+ )
1015
+
1016
+ def add_setup(self, action: str, seconds: float, byte_count: int = 0) -> None:
1017
+ self.setup_seconds_by_action[action] = self.setup_seconds_by_action.get(action, 0.0) + seconds
1018
+ self.setup_bytes_by_action[action] = self.setup_bytes_by_action.get(action, 0) + byte_count
1019
+
1020
+ def add_copy(self, name: str, seconds: float, byte_count: int) -> None:
1021
+ self.copy_seconds_by_name[name] = self.copy_seconds_by_name.get(name, 0.0) + seconds
1022
+ self.copy_bytes_by_name[name] = self.copy_bytes_by_name.get(name, 0) + byte_count
1023
+ self.copy_calls_by_name[name] = self.copy_calls_by_name.get(name, 0) + 1
1024
+
1025
+ def as_dict(self) -> dict[str, Any]:
1026
+ return {
1027
+ "module_count": self.module_count,
1028
+ "patched_module_count": self.patched_module_count,
1029
+ "total_gb": round(self.total_bytes / 1024**3, 4),
1030
+ "bytes_by_placement": {
1031
+ key: round(value / 1024**3, 4) for key, value in sorted(self.bytes_by_placement.items())
1032
+ },
1033
+ "setup_runtime": {
1034
+ key: {
1035
+ "seconds": round(self.setup_seconds_by_action[key], 4),
1036
+ "gb": round(self.setup_bytes_by_action.get(key, 0) / 1024**3, 4),
1037
+ }
1038
+ for key in sorted(self.setup_seconds_by_action)
1039
+ },
1040
+ "copy_runtime": {
1041
+ key: {
1042
+ "calls": self.copy_calls_by_name.get(key, 0),
1043
+ "seconds": round(self.copy_seconds_by_name[key], 4),
1044
+ "gb": round(self.copy_bytes_by_name.get(key, 0) / 1024**3, 4),
1045
+ }
1046
+ for key in sorted(self.copy_seconds_by_name)
1047
+ },
1048
+ "selected_resident_modules": self.selected_resident_modules,
1049
+ "selected_resident_linear_weights": self.selected_resident_linear_weights,
1050
+ "selected_pinned_linear_weights": self.selected_pinned_linear_weights,
1051
+ "resolved_resident_module_patterns": self.resolved_resident_module_patterns,
1052
+ "sdnq_parameter_pinning": {
1053
+ "pinned_count": self.sdnq_pinned_parameter_count,
1054
+ "pinned_gb": round(self.sdnq_pinned_parameter_bytes / 1024**3, 4),
1055
+ "unpinned_count": self.sdnq_unpinned_parameter_count,
1056
+ "unpinned_gb": round(self.sdnq_unpinned_parameter_bytes / 1024**3, 4),
1057
+ },
1058
+ "planner_decisions": self.planner_decisions,
1059
+ "entries": [
1060
+ {
1061
+ "module_name": entry.module_name,
1062
+ "module_type": entry.module_type,
1063
+ "tensor_name": entry.tensor_name,
1064
+ "shape": list(entry.shape),
1065
+ "dtype": entry.dtype,
1066
+ "device": entry.device,
1067
+ "gb": round(entry.bytes / 1024**3, 6),
1068
+ "placement": entry.placement,
1069
+ }
1070
+ for entry in self.entries
1071
+ ],
1072
+ }
1073
+
1074
+
1075
+ class DynamicOffloadHook(ModelHook):
1076
+ def __init__(self, config: DynamicOffloadConfig) -> None:
1077
+ super().__init__()
1078
+ self.config = config
1079
+ self.state = DynamicOffloadState()
1080
+ self._patched_modules: list[tuple[nn.Module, object]] = []
1081
+ self._pin_memory_disabled = False
1082
+ self._skip_pin_weights = False
1083
+ self._force_full_pin_weights = False
1084
+ self._resident_module_names: set[str] = set()
1085
+ self._pinned_weight_cache_namespace = ""
1086
+ self._sdnq_parameters_seen: set[int] = set()
1087
+ self._sdnq_parameters_to_pin: set[int] = set()
1088
+ self.execution_device = torch.device(config.execution_device)
1089
+ self.offload_device = torch.device(config.offload_device)
1090
+ self.execution_mode = config.execution_mode.lower()
1091
+ self.linear_runtime_strategy = config.linear_runtime_strategy.lower()
1092
+ self.vmm_resident_weight_budget_bytes = int(
1093
+ max(0.0, float(config.vmm_resident_weight_budget_gb)) * 1024**3
1094
+ )
1095
+ self.vmm_staging_buffer_bytes = int(max(0.0, float(config.vmm_staging_buffer_gb)) * 1024**3)
1096
+ self._vmm_store = None
1097
+ self._vmm_fast_store = None
1098
+ self._vmm_fast_adapter = None
1099
+ self._vmm_runtime_active = False
1100
+ self._vmm_arena = None
1101
+ self._vmm_host_registry = None
1102
+ self._vmm_file_slices = None
1103
+ self._vmm_staging_pool = None
1104
+ self._vmm_upload_stream = None
1105
+ self._vmm_group_hooks: list[Any] = []
1106
+ self._vmm_execution_groups: list[tuple[str, list[tuple[str, nn.Linear]]]] = []
1107
+ self._vmm_active_group_leases: dict[str, list[Any]] = {}
1108
+ self._vmm_pending_group_leases: dict[str, list[Any]] = {}
1109
+ self._vmm_pending_group_events: dict[str, Any] = {}
1110
+ self._vmm_prefetch_executor: ThreadPoolExecutor | None = None
1111
+ self._vmm_prefetch_futures: dict[str, Any] = {}
1112
+ self._vmm_prefetch_lock = threading.RLock()
1113
+ if self.linear_runtime_strategy not in {"functional", "swap"}:
1114
+ raise ValueError("DynamicOffloadConfig.linear_runtime_strategy must be 'functional' or 'swap'")
1115
+ self.pin_cpu_workers = max(1, int(config.pin_cpu_workers))
1116
+ self.auto_budget_policy = config.auto_budget_policy.lower()
1117
+ if self.auto_budget_policy not in {_AUTO_BUDGET_DISABLED, _AUTO_BUDGET_BALANCED}:
1118
+ raise ValueError("DynamicOffloadConfig.auto_budget_policy must be 'off' or 'balanced'")
1119
+ self.max_resident_module_budget_bytes = int(max(0.0, float(config.max_resident_module_budget_gb)) * 1024**3)
1120
+ self.max_pin_weight_budget_bytes = int(max(0.0, float(config.max_pin_weight_budget_gb)) * 1024**3)
1121
+ self.available_system_ram_bytes = int(max(0.0, float(config.available_system_ram_gb)) * 1024**3)
1122
+ self.system_ram_headroom_bytes = int(max(0.0, float(config.system_ram_headroom_gb)) * 1024**3)
1123
+ self.pin_weight_budget_bytes = int(max(0.0, float(config.pin_weight_budget_gb)) * 1024**3)
1124
+ self.pin_weight_selection = config.pin_weight_selection.lower()
1125
+ if self.pin_weight_selection not in {"first", "spread", "largest"}:
1126
+ raise ValueError("DynamicOffloadConfig.pin_weight_selection must be 'first', 'spread', or 'largest'")
1127
+ self.pin_weight_budget_ratio = max(0.0, min(1.0, float(config.pin_weight_budget_ratio)))
1128
+ self.resident_module_budget_bytes = int(max(0.0, float(config.resident_module_budget_gb)) * 1024**3)
1129
+ self.resident_module_selection = config.resident_module_selection.lower()
1130
+ if self.resident_module_selection not in {"first", "spread", "largest"}:
1131
+ raise ValueError("DynamicOffloadConfig.resident_module_selection must be 'first', 'spread', or 'largest'")
1132
+
1133
+ def initialize_hook(self, module: nn.Module) -> nn.Module:
1134
+ if self.config.vmm_float8_weight_only:
1135
+ from .float8_loading import validate_float8_native_config
1136
+
1137
+ validate_float8_native_config(self.config)
1138
+ if not getattr(module, "_ddo_float8_weight_only_loaded", False):
1139
+ raise ValueError("FP8 native runtime requires the explicit physical-source loader")
1140
+ self._pinned_weight_cache_namespace = (
1141
+ self.config.pinned_weight_cache_namespace.strip()
1142
+ or f"{module.__class__.__module__}.{module.__class__.__qualname__}"
1143
+ )
1144
+ if self.execution_mode == "vmm_fast_runtime":
1145
+ metadata_start = time.perf_counter()
1146
+ self.state = build_dynamic_offload_plan(module, self.config)
1147
+ self.state.add_setup("vmm_fast_plan_metadata", time.perf_counter() - metadata_start)
1148
+ else:
1149
+ self.state = build_dynamic_offload_plan(module, self.config)
1150
+ if self.execution_mode not in {"plan", "linear_runtime", "sdnq_runtime", "vmm_runtime", "vmm_fast_runtime"}:
1151
+ raise ValueError(
1152
+ "DynamicOffloadConfig.execution_mode must be 'plan', 'linear_runtime', 'sdnq_runtime', "
1153
+ "'vmm_runtime', or 'vmm_fast_runtime'"
1154
+ )
1155
+ if self.execution_mode == "linear_runtime":
1156
+ self._prepare_linear_runtime(module)
1157
+ elif self.execution_mode == "sdnq_runtime":
1158
+ self._prepare_sdnq_runtime(module)
1159
+ elif self.execution_mode == "vmm_runtime":
1160
+ self._prepare_vmm_runtime(module)
1161
+ elif self.execution_mode == "vmm_fast_runtime":
1162
+ self._prepare_vmm_fast_runtime(module)
1163
+ if self.config.verbose:
1164
+ summary = self.state.as_dict()
1165
+ print(
1166
+ " [dynamic-offload] "
1167
+ f"mode={self.execution_mode} modules={summary['module_count']} "
1168
+ f"patched={summary['patched_module_count']} total_gb={summary['total_gb']:.4f} "
1169
+ f"placements={summary['bytes_by_placement']}",
1170
+ flush=True,
1171
+ )
1172
+ if self.config.pin_cpu_memory and self.pin_weight_budget_bytes > 0:
1173
+ print(
1174
+ " [dynamic-offload] warning: partial pinned-memory budgets can be slower than full pinning; "
1175
+ "clear DDO_PIN_WEIGHT_BUDGET_GB "
1176
+ "when benchmarking the fast preset.",
1177
+ flush=True,
1178
+ )
1179
+ if summary["setup_runtime"]:
1180
+ print(f" [dynamic-offload] setup={summary['setup_runtime']}", flush=True)
1181
+ auto_pin_decision = self.state.planner_decisions.get("auto_pin_weight_decision")
1182
+ if auto_pin_decision in {"full_pin_zero_resident", "full_pin_residual_vram", "full_pin_profile_resident"}:
1183
+ decisions = self.state.planner_decisions
1184
+ selected_resident_gb = decisions.get("selected_resident_module_gb", 0.0)
1185
+ resident_note = (
1186
+ "no extra resident modules"
1187
+ if selected_resident_gb <= 0
1188
+ else f"{selected_resident_gb:.2f} GiB of resident modules"
1189
+ )
1190
+ print(
1191
+ f" [dynamic-offload] auto plan: full pinned CPU weights with {resident_note} "
1192
+ f"(weights={decisions['candidate_weight_gb']:.2f} GiB, "
1193
+ f"usable_ram={decisions['auto_usable_system_ram_gb']:.2f} GiB, "
1194
+ f"model_to_vram={decisions['auto_model_to_vram_ratio']:.2f}x).",
1195
+ flush=True,
1196
+ )
1197
+ elif self.auto_budget_policy == _AUTO_BUDGET_BALANCED:
1198
+ decisions = self.state.planner_decisions
1199
+ print(
1200
+ " [dynamic-offload] auto plan: "
1201
+ f"pin={auto_pin_decision or 'not_applicable'}, "
1202
+ f"resident_budget={decisions.get('auto_resident_module_budget_gb', 0.0):.2f} GiB, "
1203
+ f"pin_budget={decisions.get('auto_pin_weight_budget_gb', 0.0):.2f} GiB.",
1204
+ flush=True,
1205
+ )
1206
+ return module
1207
+
1208
+ def detach_hook(self, module: nn.Module) -> nn.Module:
1209
+ if getattr(self, "_linear_convolution_active", 0):
1210
+ raise RuntimeError("Cannot detach during an active offloaded convolution")
1211
+ self._clear_vmm_execution_groups()
1212
+ self._restore_patches()
1213
+ self._close_vmm_store(module)
1214
+ return module
1215
+
1216
+ def collect_completed_runtime_resources(self) -> dict[str, Any]:
1217
+ """Explicit phase-boundary native collection; never changes residency."""
1218
+ store = self._vmm_fast_store
1219
+ transport = getattr(store, "_native_shard_transport", None)
1220
+ cache = getattr(transport, "cache", None)
1221
+ if cache is None:
1222
+ return {"status": "not_applicable", "blocking": False}
1223
+ before = cache.snapshot()["live_tickets"]
1224
+ cache.collect_completed()
1225
+ after = cache.snapshot()["live_tickets"]
1226
+ return {"status": "collected", "blocking": False,
1227
+ "tickets_before": before, "tickets_after": after,
1228
+ "tickets_retired": before - after}
1229
+
1230
+ def vmm_runtime_stats(self) -> dict[str, int] | None:
1231
+ """Return a snapshot of VMM cache activity while the hook is active."""
1232
+ if self._vmm_arena is None and self._vmm_fast_store is None:
1233
+ return None
1234
+ result = {
1235
+ "reserved_bytes": 0,
1236
+ "resident_bytes": 0,
1237
+ "materializations": 0,
1238
+ "evictions": 0,
1239
+ "copied_bytes": 0,
1240
+ }
1241
+ if self._vmm_arena is not None:
1242
+ arena_stats = self._vmm_arena.stats
1243
+ result.update(
1244
+ {
1245
+ "arena_reserved_bytes": arena_stats.reserved_bytes,
1246
+ "arena_resident_bytes": arena_stats.resident_bytes,
1247
+ "arena_materializations": arena_stats.materializations,
1248
+ "arena_evictions": arena_stats.evictions,
1249
+ "arena_copied_bytes": arena_stats.copied_bytes,
1250
+ "arena_map_seconds": arena_stats.map_seconds,
1251
+ "arena_direct_dma_seconds": arena_stats.direct_dma_seconds,
1252
+ "arena_staging_seconds": arena_stats.staging_seconds,
1253
+ "arena_file_slice_staging_seconds": arena_stats.file_slice_staging_seconds,
1254
+ "arena_file_slice_bytes": arena_stats.file_slice_bytes,
1255
+ "arena_temporary_fallbacks": arena_stats.temporary_fallbacks,
1256
+ "arena_temporary_bytes": arena_stats.temporary_bytes,
1257
+ "arena_persistent_virtual_views": arena_stats.persistent_virtual_views,
1258
+ }
1259
+ )
1260
+ result["materializations"] += arena_stats.materializations
1261
+ result["evictions"] += arena_stats.evictions
1262
+ result["copied_bytes"] += arena_stats.copied_bytes
1263
+ result["reserved_bytes"] += arena_stats.reserved_bytes
1264
+ result["resident_bytes"] += arena_stats.resident_bytes
1265
+ if self._vmm_host_registry is not None:
1266
+ result["host_cache_registered_bytes"] = self._vmm_host_registry.registered_bytes
1267
+ result["host_cache_skipped_bytes"] = self._vmm_host_registry.skipped_bytes
1268
+ if self._vmm_fast_store is not None:
1269
+ fast_stats = self._vmm_fast_store.runtime_stats()
1270
+ result.update({f"fast_{name}": value for name, value in fast_stats.items()})
1271
+ result["reserved_bytes"] += fast_stats["virtual_bytes"]
1272
+ result["resident_bytes"] += fast_stats["resident_bytes"]
1273
+ result["materializations"] += fast_stats["faults"]
1274
+ result["copied_bytes"] += fast_stats["upload_bytes"]
1275
+ return result
1276
+
1277
+ def deinitalize_hook(self, module: nn.Module) -> nn.Module:
1278
+ self._clear_vmm_execution_groups()
1279
+ self._restore_patches()
1280
+ self._close_vmm_store(module)
1281
+ return module
1282
+
1283
+ def pre_forward(self, module: nn.Module, *args, **kwargs) -> tuple[tuple[Any, ...], dict[str, Any]]:
1284
+ if self.execution_mode == "plan":
1285
+ return args, kwargs
1286
+ if self.execution_mode == "vmm_runtime" and self._vmm_execution_groups:
1287
+ self._schedule_vmm_execution_group(0)
1288
+ return (
1289
+ tuple(self._move_value_to_execution_device(value, "forward_input") for value in args),
1290
+ {
1291
+ key: self._move_value_to_execution_device(value, f"forward_input:{key}")
1292
+ for key, value in kwargs.items()
1293
+ },
1294
+ )
1295
+
1296
+ def _restore_patches(self) -> None:
1297
+ while self._patched_modules:
1298
+ patched_module, original_forward = self._patched_modules.pop()
1299
+ patched_module.forward = original_forward
1300
+ self._pin_memory_disabled = False
1301
+ self._resident_module_names.clear()
1302
+
1303
+ def _move_value_to_execution_device(self, value: Any, name: str) -> Any:
1304
+ if isinstance(value, torch.Tensor):
1305
+ if value.device == self.execution_device:
1306
+ return value
1307
+ if value.device.type == "meta":
1308
+ return value
1309
+ start = time.perf_counter()
1310
+ moved = value.to(device=self.execution_device, non_blocking=True)
1311
+ self.state.add_copy(name, time.perf_counter() - start, _tensor_size_bytes(moved))
1312
+ return moved
1313
+ if isinstance(value, tuple):
1314
+ return tuple(self._move_value_to_execution_device(item, name) for item in value)
1315
+ if isinstance(value, list):
1316
+ return [self._move_value_to_execution_device(item, name) for item in value]
1317
+ if isinstance(value, dict):
1318
+ return {key: self._move_value_to_execution_device(item, f"{name}:{key}") for key, item in value.items()}
1319
+ return value
1320
+
1321
+ def _prepare_linear_runtime(self, module: nn.Module) -> None:
1322
+ if self.config.linear_convolution_offload:
1323
+ from .linear_convolution import validate_convolutions
1324
+
1325
+ validate_convolutions(module, self.config)
1326
+ self.state.planner_decisions["linear_convolution_offload"] = True
1327
+ skip_patterns = tuple(re.compile(pattern) for pattern in self.config.skip_modules_pattern)
1328
+ resident_patterns = tuple(re.compile(pattern) for pattern in self.config.always_resident_modules_pattern)
1329
+ if self.state.resolved_resident_module_patterns:
1330
+ resident_module_patterns = tuple(
1331
+ re.compile(pattern) for pattern in self.state.resolved_resident_module_patterns
1332
+ )
1333
+ else:
1334
+ resident_module_patterns = _resolve_resident_module_patterns(module, self.config)
1335
+ self.state.resolved_resident_module_patterns = [pattern.pattern for pattern in resident_module_patterns]
1336
+ modules_to_pin: list[tuple[str, nn.Module, int]] = []
1337
+
1338
+ self._apply_auto_budget_policy(module, skip_patterns, resident_patterns, resident_module_patterns)
1339
+ if self.config.build_profile:
1340
+ self.resident_module_budget_bytes = 0
1341
+ resident_patterns = ()
1342
+ self.state.planner_decisions["auto_resident_module_budget_gb"] = 0.0
1343
+ self.state.planner_decisions["auto_resident_module_decision"] = "profile_calibration"
1344
+ if self.state.planner_decisions.get("auto_pin_weight_decision") == "full_pin_zero_resident":
1345
+ # A full-pinned, zero-resident plan must not quietly retain the
1346
+ # default "always resident" leaves on CUDA. Besides contradicting
1347
+ # the plan label, those leaves consume the activation headroom that
1348
+ # this mode is explicitly trying to reserve. Treat them as normal
1349
+ # pinned leaves instead; the runtime still onloads them just in time.
1350
+ if resident_patterns:
1351
+ self.state.planner_decisions["auto_always_resident_decision"] = "offload_for_zero_resident"
1352
+ resident_patterns = ()
1353
+ # The automatic budget was calculated before the default resident
1354
+ # leaves joined the pin candidates. Select every one of them rather
1355
+ # than accidentally leaving that residual unpinned.
1356
+ self._force_full_pin_weights = True
1357
+
1358
+ self._move_root_local_tensors_to_device(module)
1359
+ if self.resident_module_budget_bytes > 0 and resident_module_patterns:
1360
+ start = time.perf_counter()
1361
+ selected_bytes = self._select_resident_modules(module, skip_patterns, resident_module_patterns)
1362
+ self.state.add_setup("select_resident_modules", time.perf_counter() - start, selected_bytes)
1363
+ self.state.planner_decisions["selected_resident_module_gb"] = round(selected_bytes / 1024**3, 4)
1364
+
1365
+ for module_name, submodule in module.named_modules():
1366
+ if module_name == "":
1367
+ continue
1368
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
1369
+ continue
1370
+ if self._is_descendant_of_resident_module(module_name):
1371
+ continue
1372
+ if module_name in self._resident_module_names:
1373
+ start = time.perf_counter()
1374
+ before = self._move_resident_module_to_execution_device(module_name, submodule)
1375
+ self.state.add_setup("resident_budget_modules_to_device", time.perf_counter() - start, before)
1376
+ continue
1377
+
1378
+ is_resident_module = bool(
1379
+ resident_patterns and any(pattern.search(module_name) for pattern in resident_patterns)
1380
+ )
1381
+ if is_resident_module:
1382
+ start = time.perf_counter()
1383
+ before = self._move_resident_module_to_execution_device(module_name, submodule)
1384
+ self.state.add_setup("resident_modules_to_device", time.perf_counter() - start, before)
1385
+ continue
1386
+
1387
+ if isinstance(submodule, nn.Linear):
1388
+ if not self._can_patch_linear(submodule):
1389
+ start = time.perf_counter()
1390
+ moved_bytes = self._move_module_tensors_to_execution_device(submodule)
1391
+ self.state.add_setup(
1392
+ "unsupported_linear_modules_to_device",
1393
+ time.perf_counter() - start,
1394
+ moved_bytes,
1395
+ )
1396
+ unsupported_count = self.state.planner_decisions.get("unsupported_linear_module_count", 0)
1397
+ self.state.planner_decisions["unsupported_linear_module_count"] = unsupported_count + 1
1398
+ continue
1399
+ self._move_linear_to_runtime_devices(
1400
+ module_name,
1401
+ submodule,
1402
+ modules_to_pin,
1403
+ )
1404
+ self._patch_linear(submodule)
1405
+ elif self.config.linear_convolution_offload and isinstance(submodule, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
1406
+ self._move_linear_to_runtime_devices(module_name, submodule, modules_to_pin)
1407
+ from .linear_convolution import patch_convolution
1408
+
1409
+ patch_convolution(self, submodule)
1410
+ elif isinstance(submodule, nn.Embedding):
1411
+ self._move_embedding_to_runtime_devices(
1412
+ module_name,
1413
+ submodule,
1414
+ modules_to_pin,
1415
+ )
1416
+ self._patch_embedding(submodule)
1417
+ else:
1418
+ self._move_small_local_tensors_to_device(submodule)
1419
+
1420
+ if self.config.pin_cpu_memory and modules_to_pin and not self._skip_pin_weights:
1421
+ start = time.perf_counter()
1422
+ selected_linears_to_pin = self._select_linear_weights_to_pin(modules_to_pin)
1423
+ pinned_bytes = self._pin_linear_weights(selected_linears_to_pin)
1424
+ self.state.add_setup("pin_linear_weights", time.perf_counter() - start, pinned_bytes)
1425
+ elif self.config.pin_cpu_memory and modules_to_pin:
1426
+ self.state.add_setup("pin_linear_weights_skipped", 0.0, 0)
1427
+
1428
+ def _prepare_vmm_runtime(self, module: nn.Module) -> None:
1429
+ """Prepare the narrow VMM route for standard immutable dense linears.
1430
+
1431
+ VMM owns only streamed linear weights. Biases and small tensors follow
1432
+ the ordinary DDO placement rules, while quantized/custom forwards stay
1433
+ outside this experimental route.
1434
+ """
1435
+ if self.execution_device.type != "cuda" or self.offload_device.type != "cpu":
1436
+ raise ValueError("vmm_runtime requires execution_device='cuda:*' and offload_device='cpu'")
1437
+ if self.vmm_resident_weight_budget_bytes <= 0:
1438
+ raise ValueError("vmm_runtime requires a positive vmm_resident_weight_budget_gb")
1439
+ if self.vmm_staging_buffer_bytes <= 0:
1440
+ raise ValueError("vmm_runtime requires a positive vmm_staging_buffer_gb")
1441
+ if detect_quantized_backend_modules(module):
1442
+ raise ValueError("vmm_runtime supports only standard dense nn.Linear weights, not quantized backends")
1443
+
1444
+ from .vmm_weight_store import PinnedStagingPool, RegisteredHostWeightRegistry, SafetensorSliceRegistry
1445
+
1446
+ self._vmm_runtime_active = True
1447
+ self._vmm_staging_pool = PinnedStagingPool(
1448
+ self.vmm_staging_buffer_bytes,
1449
+ registered_virtual_host=self.config.vmm_virtual_host_transport,
1450
+ windows_file_read_chunk_bytes=max(1, int(self.config.vmm_windows_file_read_chunk_mb)) * 1024**2,
1451
+ )
1452
+ self._vmm_file_slices = getattr(module, "_ddo_safetensor_slices", None)
1453
+ if self._vmm_file_slices is not None and not isinstance(self._vmm_file_slices, SafetensorSliceRegistry):
1454
+ self._vmm_file_slices = None
1455
+ if self._vmm_file_slices is not None:
1456
+ self._vmm_prefetch_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ddo-vmm-read")
1457
+ file_slice_summary = getattr(module, "_ddo_safetensor_slice_summary", {})
1458
+ self._vmm_upload_stream = torch.cuda.Stream(device=self.execution_device)
1459
+ host_cache_bytes = int(max(0.0, self.config.vmm_host_cache_gb) * 1024**3)
1460
+ self._vmm_host_registry = (
1461
+ RegisteredHostWeightRegistry(self.execution_device.index or 0, max_bytes=host_cache_bytes)
1462
+ if host_cache_bytes > 0
1463
+ else None
1464
+ )
1465
+ self.state.planner_decisions.update(
1466
+ {
1467
+ "vmm_runtime": "experimental_dense_linear",
1468
+ "vmm_resident_weight_budget_gb": round(self.vmm_resident_weight_budget_bytes / 1024**3, 4),
1469
+ "vmm_staging_buffer_gb": round(self.vmm_staging_buffer_bytes / 1024**3, 4),
1470
+ "vmm_windows_file_read_chunk_mb": int(self.config.vmm_windows_file_read_chunk_mb),
1471
+ "vmm_staging_slots": self._vmm_staging_pool.slots,
1472
+ "vmm_virtual_host_transport": self._vmm_staging_pool.uses_registered_virtual_host,
1473
+ "vmm_file_slice_transport": self._vmm_file_slices is not None,
1474
+ "vmm_file_slice_background_prefetch": self._vmm_file_slices is not None,
1475
+ "vmm_fault_fallback": self.config.vmm_fault_fallback,
1476
+ "vmm_host_cache_budget_gb": round(host_cache_bytes / 1024**3, 4),
1477
+ "vmm_windows_overlapped_file_io": self._vmm_staging_pool.uses_windows_overlapped_file_io,
1478
+ "vmm_safetensor_slices_bound": int(file_slice_summary.get("bound", 0)),
1479
+ "vmm_safetensor_slices_available": int(file_slice_summary.get("available", 0)),
1480
+ }
1481
+ )
1482
+ skip_patterns = tuple(re.compile(pattern) for pattern in self.config.skip_modules_pattern)
1483
+ self._move_root_local_tensors_to_device(module)
1484
+ # VMM uploads are issued one execution group at a time. Keep the
1485
+ # immutable CPU sources page-locked so the upload stream can DMA
1486
+ # directly from host memory instead of first copying every group from
1487
+ # pageable checkpoint storage into the bounded staging pool. The
1488
+ # latter path is safe but is dominated by pageable->pinned copies on
1489
+ # Windows/WDDM for large transformer blocks.
1490
+ if self.config.vmm_pin_source_weights and not self._pin_memory_disabled:
1491
+ start = time.perf_counter()
1492
+ pinned_bytes = 0
1493
+ for _module_name, submodule in module.named_modules():
1494
+ if not isinstance(submodule, nn.Linear):
1495
+ continue
1496
+ weight = submodule.weight.data
1497
+ if weight.device.type != "cpu" or weight.is_pinned():
1498
+ continue
1499
+ try:
1500
+ submodule.weight.data = weight.pin_memory()
1501
+ pinned_bytes += _tensor_size_bytes(submodule.weight)
1502
+ except RuntimeError as exc:
1503
+ if not self.config.allow_pin_memory_fallback:
1504
+ raise
1505
+ self._disable_pin_memory("vmm_pin_source_weights_failed", exc)
1506
+ break
1507
+ if pinned_bytes:
1508
+ self.state.add_setup("vmm_pin_source_weights", time.perf_counter() - start, pinned_bytes)
1509
+ if self._vmm_host_registry is not None:
1510
+ start = time.perf_counter()
1511
+ registered_bytes = 0
1512
+ rejected_weights = 0
1513
+ for _module_name, submodule in module.named_modules():
1514
+ if not isinstance(submodule, nn.Linear) or not self._can_patch_linear(submodule):
1515
+ continue
1516
+ weight = submodule.weight.data
1517
+ if self._vmm_host_registry.register(weight):
1518
+ registered_bytes += _tensor_size_bytes(weight)
1519
+ else:
1520
+ rejected_weights += 1
1521
+ self.state.add_setup("vmm_host_cache_registration", time.perf_counter() - start, registered_bytes)
1522
+ self.state.planner_decisions["vmm_host_cache_registered_gb"] = round(
1523
+ registered_bytes / 1024**3, 4
1524
+ )
1525
+ self.state.planner_decisions["vmm_host_cache_skipped_weight_count"] = rejected_weights
1526
+ self._register_vmm_execution_groups(module)
1527
+ for module_name, submodule in module.named_modules():
1528
+ if not module_name:
1529
+ continue
1530
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
1531
+ continue
1532
+ if isinstance(submodule, nn.Linear):
1533
+ in_native_arena = self._vmm_arena is not None and self._vmm_arena.contains_weight(module_name)
1534
+ if in_native_arena:
1535
+ if not self._can_patch_linear(submodule):
1536
+ raise ValueError(f"vmm_runtime cannot patch nonstandard dense linear {module_name!r}")
1537
+ if submodule.weight.dtype not in {torch.float16, torch.bfloat16}:
1538
+ raise ValueError(
1539
+ f"vmm_runtime supports only float16/bfloat16 weights; {module_name!r} is {submodule.weight.dtype}"
1540
+ )
1541
+ self._move_linear_to_runtime_devices(module_name, submodule, modules_to_pin=None)
1542
+ self._patch_vmm_linear(module_name, submodule)
1543
+ else:
1544
+ self._move_module_tensors_to_execution_device(submodule)
1545
+ else:
1546
+ self._move_small_local_tensors_to_device(submodule)
1547
+
1548
+ def _prepare_vmm_fast_runtime(self, module: nn.Module) -> None:
1549
+ """Attach the single native model-address arena used by ``vmm_fast``.
1550
+
1551
+ Unlike the protected ``vmm_runtime`` baseline, this route delegates
1552
+ individual range faults, signatures, unpin events, and temporary
1553
+ fallbacks to the allocator submodule. DDO only supplies immutable
1554
+ checkpoint descriptors, bounded staging, and lifecycle ownership.
1555
+ """
1556
+ resources_start = time.perf_counter()
1557
+ if self.execution_device.type != "cuda" or self.offload_device.type != "cpu":
1558
+ raise ValueError("vmm_fast_runtime requires execution_device='cuda:*' and offload_device='cpu'")
1559
+ if self.vmm_resident_weight_budget_bytes <= 0:
1560
+ raise ValueError("vmm_fast_runtime requires a positive vmm_resident_weight_budget_gb")
1561
+ if self.vmm_staging_buffer_bytes <= 0:
1562
+ raise ValueError("vmm_fast_runtime requires a positive vmm_staging_buffer_gb")
1563
+ if self.config.vmm_page_mb < 0:
1564
+ raise ValueError("vmm_fast page size must be non-negative")
1565
+ re.compile(self.config.vmm_module_pattern)
1566
+ if self.config.vmm_execution_auxiliary_ownership:
1567
+ if not self.config.vmm_native_transport or self.config.vmm_component_tensor_ownership:
1568
+ raise ValueError("execution auxiliary ownership requires native transport without component ownership")
1569
+ from ddo_vmm_allocator.execution_auxiliary import discover_execution_auxiliary_layout
1570
+
1571
+ discover_execution_auxiliary_layout(module, self.config.vmm_module_pattern,
1572
+ getattr(module, "_ddo_safetensor_slices", None),
1573
+ small_tensor_threshold_bytes=self.config.small_tensor_threshold_bytes)
1574
+ if self.config.vmm_component_tensor_ownership:
1575
+ if not self.config.vmm_native_transport or self.config.vmm_module_pattern != ".*":
1576
+ raise ValueError("component ownership requires native transport and full-component selection")
1577
+ if type(self.config.vmm_component_buffer_limit_mb) is not int or self.config.vmm_component_buffer_limit_mb < 0:
1578
+ raise ValueError("component buffer limit must be a non-negative integer MiB")
1579
+ if self.config.vmm_float8_weight_only:
1580
+ from ddo_vmm_allocator.quantized_arena_adapter import discover_float8_component_layout
1581
+
1582
+ discover_float8_component_layout(
1583
+ module, getattr(module, "_ddo_safetensor_slices", None),
1584
+ buffer_limit_bytes=self.config.vmm_component_buffer_limit_mb * 1024**2)
1585
+ else:
1586
+ from ddo_vmm_allocator.component_arena_adapter import discover_component_layout
1587
+
1588
+ discover_component_layout(
1589
+ module, getattr(module, "_ddo_safetensor_slices", None),
1590
+ buffer_limit_bytes=self.config.vmm_component_buffer_limit_mb * 1024**2,
1591
+ )
1592
+ if detect_quantized_backend_modules(module) and not self.config.vmm_float8_weight_only:
1593
+ raise ValueError("vmm_fast_runtime supports only standard dense nn.Linear weights, not quantized backends")
1594
+
1595
+ cache_slot_mb = int(self.config.vmm_native_source_cache_slot_mb)
1596
+ cache_slots = int(self.config.vmm_native_source_cache_slots)
1597
+ native_transport_kwargs = _native_source_cache_transport_config(
1598
+ self.vmm_staging_buffer_bytes, cache_slot_mb, cache_slots, self.config.vmm_host_cache_gb,
1599
+ native_transport=self.config.vmm_native_transport,
1600
+ source_cache_gb=self.config.vmm_source_cache_gb,
1601
+ source_registered_gb=self.config.vmm_source_registered_gb,
1602
+ )
1603
+
1604
+ from .vmm_model_arena import _load_native_allocator
1605
+ from .vmm_weight_store import PinnedStagingPool, SafetensorSliceRegistry
1606
+
1607
+ library, _arena_type = _load_native_allocator(None)
1608
+ headrooms = (self.config.vmm_dxgi_local_headroom_gb, self.config.vmm_dxgi_shared_headroom_gb,
1609
+ self.config.vmm_dxgi_system_headroom_gb)
1610
+ if any(not math.isfinite(value) or value < 0 for value in headrooms):
1611
+ raise ValueError("native DXGI headrooms must be finite and non-negative")
1612
+ if any(headrooms):
1613
+ library.set_dxgi_budget_guard(
1614
+ device_ordinal=self.execution_device.index or 0,
1615
+ local_reserve_bytes=int(headrooms[0] * 1024**3),
1616
+ shared_reserve_bytes=int(headrooms[1] * 1024**3),
1617
+ system_reserve_bytes=int(headrooms[2] * 1024**3),
1618
+ )
1619
+ try:
1620
+ from ddo_vmm_allocator.model_arena_adapter import attach_model_linear_modules
1621
+ except ImportError as error: # pragma: no cover - source fallback is covered by _load_native_allocator.
1622
+ raise RuntimeError(
1623
+ "vmm_fast_runtime requires ddo-vmm-allocator. Install the submodule package or run from the DDO source tree."
1624
+ ) from error
1625
+
1626
+ self._vmm_file_slices = getattr(module, "_ddo_safetensor_slices", None)
1627
+ if self._vmm_file_slices is not None and not isinstance(self._vmm_file_slices, SafetensorSliceRegistry):
1628
+ self._vmm_file_slices = None
1629
+ if native_transport_kwargs:
1630
+ self._vmm_staging_pool = None
1631
+ else:
1632
+ self._vmm_staging_pool = PinnedStagingPool(
1633
+ self.vmm_staging_buffer_bytes,
1634
+ registered_virtual_host=self.config.vmm_virtual_host_transport,
1635
+ windows_file_read_chunk_bytes=max(1, int(self.config.vmm_windows_file_read_chunk_mb)) * 1024**2,
1636
+ )
1637
+ file_slice_summary = getattr(module, "_ddo_safetensor_slice_summary", {})
1638
+ self.state.add_setup("vmm_fast_native_resources", time.perf_counter() - resources_start)
1639
+ start = time.perf_counter()
1640
+ ownership_kwargs = dict(
1641
+ module_pattern=self.config.vmm_module_pattern,
1642
+ component_tensor_ownership=self.config.vmm_component_tensor_ownership,
1643
+ execution_auxiliary_ownership=self.config.vmm_execution_auxiliary_ownership,
1644
+ execution_auxiliary_small_tensor_threshold_bytes=self.config.small_tensor_threshold_bytes,
1645
+ component_buffer_limit_bytes=self.config.vmm_component_buffer_limit_mb * 1024**2)
1646
+ if self.config.vmm_float8_weight_only:
1647
+ from ddo_vmm_allocator.quantized_arena_adapter import attach_float8_component_parameters
1648
+
1649
+ attach_model_linear_modules = attach_float8_component_parameters
1650
+ ownership_kwargs = dict(component_buffer_limit_bytes=self.config.vmm_component_buffer_limit_mb * 1024**2)
1651
+ report, store = attach_model_linear_modules(
1652
+ module,
1653
+ library,
1654
+ page_size_bytes=int(self.config.vmm_page_mb) * 1024**2,
1655
+ resident_budget_bytes=self.vmm_resident_weight_budget_bytes,
1656
+ device_ordinal=self.execution_device.index or 0,
1657
+ staging_pool=self._vmm_staging_pool,
1658
+ file_slices=self._vmm_file_slices,
1659
+ host_cache_bytes=int(max(0.0, self.config.vmm_host_cache_gb) * 1024**3),
1660
+ **ownership_kwargs,
1661
+ **native_transport_kwargs,
1662
+ )
1663
+ self._vmm_fast_store = store
1664
+ self._vmm_fast_adapter = report.adapter
1665
+ self._vmm_runtime_active = True
1666
+ self.state.add_setup("vmm_fast_attach_native_model_arena", time.perf_counter() - start, report.payload_bytes)
1667
+ self.state.patched_module_count += report.attached_modules
1668
+ self.state.planner_decisions.update(
1669
+ {
1670
+ "vmm_runtime": "native_model_arena",
1671
+ "vmm_backend": "native_model_arena",
1672
+ "vmm_native_library": str(library.path),
1673
+ "vmm_resident_weight_budget_gb": round(self.vmm_resident_weight_budget_bytes / 1024**3, 4),
1674
+ "vmm_staging_buffer_gb": round(self.vmm_staging_buffer_bytes / 1024**3, 4),
1675
+ "vmm_staging_slots": (
1676
+ self._vmm_staging_pool.slots if self._vmm_staging_pool is not None
1677
+ else native_transport_kwargs["native_transport_slots"]
1678
+ ),
1679
+ "vmm_virtual_host_transport": (
1680
+ self._vmm_staging_pool.uses_registered_virtual_host if self._vmm_staging_pool is not None else True
1681
+ ),
1682
+ "vmm_native_source_cache_slot_mb": native_transport_kwargs.get("native_source_cache_slot_bytes", 0) // 1024**2,
1683
+ "vmm_source_cache_gb": self.config.vmm_source_cache_gb,
1684
+ "vmm_source_registered_gb": self.config.vmm_source_registered_gb,
1685
+ "vmm_native_source_persistent_buffer": bool(self.config.vmm_source_cache_gb),
1686
+ "vmm_native_transport": bool(native_transport_kwargs),
1687
+ "vmm_native_transport_registered_capacity_bytes": (
1688
+ native_transport_kwargs.get("native_transport_slot_size_bytes", 0)
1689
+ * native_transport_kwargs.get("native_transport_slots", 0)
1690
+ ),
1691
+ "vmm_native_source_cache_slots": native_transport_kwargs.get("native_source_cache_slots", 0),
1692
+ "vmm_native_source_cache_model_windows": native_transport_kwargs.get("native_source_cache_model_windows", False),
1693
+ "vmm_native_source_cache_process_limit_bytes": (
1694
+ native_transport_kwargs.get("native_source_cache_process_limit_bytes", 0)
1695
+ ),
1696
+ "vmm_file_slice_transport": self._vmm_file_slices is not None,
1697
+ "vmm_safetensor_slices_bound": int(file_slice_summary.get("bound", 0)),
1698
+ "vmm_safetensor_slices_available": int(file_slice_summary.get("available", 0)),
1699
+ "vmm_fast_attached_modules": report.attached_modules,
1700
+ "vmm_fast_attached_tensors": report.attached_tensors,
1701
+ "vmm_execution_auxiliary_ownership": self.config.vmm_execution_auxiliary_ownership,
1702
+ "vmm_fast_payload_bytes": report.payload_bytes,
1703
+ "vmm_float8_weight_only": self.config.vmm_float8_weight_only,
1704
+ "vmm_fast_virtual_bytes": report.virtual_bytes,
1705
+ "vmm_fast_page_bytes": report.page_bytes,
1706
+ }
1707
+ )
1708
+ self._prepare_vmm_fast_auxiliary_tensors(module)
1709
+
1710
+ def _prepare_vmm_fast_auxiliary_tensors(self, module: nn.Module) -> None:
1711
+ """Preserve auxiliary placement, but account for previously untimed copies.
1712
+
1713
+ This is exclusive to fast VMM. No new stream, async copy, bulk buffer,
1714
+ residency decision or deferred work is introduced by these timers.
1715
+ """
1716
+ if self.config.vmm_component_tensor_ownership:
1717
+ return # Component adapter owns every parameter and bounded buffer.
1718
+ self._move_root_local_tensors_to_device(module)
1719
+ for module_name, submodule in module.named_modules():
1720
+ if isinstance(submodule, nn.Linear) and submodule.weight.device.type == "cpu":
1721
+ moved_bytes = sum(
1722
+ _tensor_size_bytes(tensor)
1723
+ for tensor in (*submodule.parameters(recurse=True), *submodule.buffers(recurse=True))
1724
+ if tensor.device != self.execution_device
1725
+ )
1726
+ start = time.perf_counter()
1727
+ self._move_module_tensors_to_execution_device(submodule)
1728
+ self.state.add_setup(
1729
+ "vmm_fast_auxiliary_linears_to_device", time.perf_counter() - start, moved_bytes,
1730
+ )
1731
+ elif module_name and not isinstance(submodule, nn.Linear):
1732
+ self._move_small_local_tensors_to_device(submodule)
1733
+
1734
+ def _register_vmm_execution_groups(self, module: nn.Module) -> None:
1735
+ """Lease one sequential execution group at a time when one is discoverable.
1736
+
1737
+ The grouping is intentionally model-agnostic: the primary ``ModuleList``
1738
+ is selected by the BF16/FP16 linear weight bytes below its direct items.
1739
+ This turns a sequence of leaf-level VMM eviction barriers into one barrier
1740
+ between substantial execution groups, such as transformer blocks.
1741
+ """
1742
+ if not self._vmm_runtime_active:
1743
+ return
1744
+ candidates: list[tuple[int, list[tuple[str, nn.Module, list[tuple[str, nn.Linear]]]]]] = []
1745
+ for container_name, container in module.named_modules():
1746
+ if not isinstance(container, nn.ModuleList) or len(container) < 2:
1747
+ continue
1748
+ groups: list[tuple[str, nn.Module, list[tuple[str, nn.Linear]]]] = []
1749
+ total_bytes = 0
1750
+ for index, group_module in enumerate(container):
1751
+ group_name = f"{container_name}.{index}" if container_name else str(index)
1752
+ linears: list[tuple[str, nn.Linear]] = []
1753
+ for relative_name, child in group_module.named_modules():
1754
+ if not isinstance(child, nn.Linear) or not self._can_patch_linear(child):
1755
+ continue
1756
+ linear_name = f"{group_name}.{relative_name}" if relative_name else group_name
1757
+ if child.weight.dtype not in {torch.float16, torch.bfloat16}:
1758
+ continue
1759
+ linears.append((linear_name, child))
1760
+ total_bytes += _tensor_size_bytes(child.weight)
1761
+ if linears:
1762
+ groups.append((group_name, group_module, linears))
1763
+ if len(groups) >= 2:
1764
+ candidates.append((total_bytes, groups))
1765
+ if not candidates:
1766
+ return
1767
+
1768
+ _, groups = max(candidates, key=lambda item: item[0])
1769
+ max_group_bytes = max(sum(_tensor_size_bytes(linear.weight) for _, linear in linears) for _, _, linears in groups)
1770
+ if max_group_bytes > self.vmm_resident_weight_budget_bytes:
1771
+ raise ValueError(
1772
+ "vmm_runtime resident budget is smaller than one execution group "
1773
+ f"({max_group_bytes / 1024**3:.2f} GiB required)."
1774
+ )
1775
+ if max_group_bytes * 2 > self.vmm_resident_weight_budget_bytes:
1776
+ raise ValueError(
1777
+ "vmm_runtime resident budget must fit the current and prefetched execution groups "
1778
+ f"({max_group_bytes * 2 / 1024**3:.2f} GiB required)."
1779
+ )
1780
+ if max_group_bytes > self.vmm_staging_buffer_bytes:
1781
+ raise ValueError(
1782
+ "vmm_runtime staging buffer is smaller than one execution group "
1783
+ f"({max_group_bytes / 1024**3:.2f} GiB required)."
1784
+ )
1785
+ self.state.planner_decisions.update(
1786
+ {
1787
+ "vmm_execution_group_count": len(groups),
1788
+ "vmm_execution_group_max_weight_gb": round(max_group_bytes / 1024**3, 4),
1789
+ }
1790
+ )
1791
+ if self._vmm_file_slices is not None:
1792
+ slice_count = 0
1793
+ read_runs = 0
1794
+ for _group_name, _group_module, linears in groups:
1795
+ previous = None
1796
+ previous_size = 0
1797
+ for _linear_name, linear in linears:
1798
+ file_slice = self._vmm_file_slices.lookup(linear.weight.data)
1799
+ if file_slice is None:
1800
+ continue
1801
+ slice_count += 1
1802
+ if (
1803
+ previous is None
1804
+ or previous.path != file_slice.path
1805
+ or previous.offset_bytes + previous_size != file_slice.offset_bytes
1806
+ ):
1807
+ read_runs += 1
1808
+ previous = file_slice
1809
+ previous_size = file_slice.size_bytes
1810
+ self.state.planner_decisions["vmm_file_slice_count"] = slice_count
1811
+ self.state.planner_decisions["vmm_file_read_runs"] = read_runs
1812
+ self._vmm_execution_groups = [(group_name, linears) for group_name, _, linears in groups]
1813
+ from .vmm_model_arena import VmmModelArena
1814
+
1815
+ self._vmm_arena = VmmModelArena(
1816
+ self.execution_device.index or 0,
1817
+ self.vmm_resident_weight_budget_bytes,
1818
+ file_slices=self._vmm_file_slices,
1819
+ staging_pool=self._vmm_staging_pool,
1820
+ registered_host=self._vmm_host_registry,
1821
+ )
1822
+ self.state.planner_decisions["vmm_backend"] = "native_cpp_allocator"
1823
+ self.state.planner_decisions["vmm_native_library"] = self._vmm_arena.native_library_path
1824
+ self.state.planner_decisions["vmm_physical_page_mb"] = round(
1825
+ self._vmm_arena.physical_page_bytes / 1024**2, 4
1826
+ )
1827
+ self._vmm_arena.reserve_groups(
1828
+ [(group_name, [(linear_name, linear.weight.data) for linear_name, linear in linears]) for group_name, _, linears in groups]
1829
+ )
1830
+ self.state.planner_decisions["vmm_persistent_virtual_views"] = self._vmm_arena.stats.persistent_virtual_views
1831
+ for group_index, (group_name, group_module, _linears) in enumerate(groups):
1832
+ pre_handle = group_module.register_forward_pre_hook(
1833
+ lambda _module, _args, index=group_index: self._enter_vmm_execution_group(index)
1834
+ )
1835
+ try:
1836
+ post_handle = group_module.register_forward_hook(
1837
+ lambda _module, _args, _output, name=group_name: self._leave_vmm_execution_group(name),
1838
+ always_call=True,
1839
+ )
1840
+ except TypeError: # pragma: no cover - legacy PyTorch compatibility.
1841
+ post_handle = group_module.register_forward_hook(
1842
+ lambda _module, _args, _output, name=group_name: self._leave_vmm_execution_group(name)
1843
+ )
1844
+ self._vmm_group_hooks.extend((pre_handle, post_handle))
1845
+
1846
+ def _schedule_vmm_execution_group(self, group_index: int) -> None:
1847
+ """Stage and upload a future group without blocking the compute stream."""
1848
+ if group_index >= len(self._vmm_execution_groups):
1849
+ return
1850
+ group_name, linears = self._vmm_execution_groups[group_index]
1851
+ if group_name in self._vmm_pending_group_leases or group_name in self._vmm_active_group_leases:
1852
+ return
1853
+ if self._vmm_staging_pool is None or self._vmm_upload_stream is None:
1854
+ raise RuntimeError("vmm_runtime upload resources were released before scheduling a group")
1855
+ if self._vmm_arena is None:
1856
+ raise RuntimeError("vmm_runtime model arena was not initialized")
1857
+ materializations_before = self._vmm_arena.stats.materializations
1858
+ copied_bytes = 0
1859
+ start = time.perf_counter()
1860
+ leases: list[Any] = []
1861
+ try:
1862
+ leases.append(
1863
+ self._vmm_arena.acquire(
1864
+ group_name,
1865
+ [(linear_name, linear.weight.data) for linear_name, linear in linears],
1866
+ self._vmm_staging_pool,
1867
+ self._vmm_upload_stream,
1868
+ self._vmm_host_registry,
1869
+ self._vmm_file_slices,
1870
+ allow_eviction=not self.config.vmm_fault_fallback,
1871
+ )
1872
+ )
1873
+ copied_bytes = sum(_tensor_size_bytes(linear.weight) for _, linear in linears)
1874
+ except BaseException:
1875
+ for lease in reversed(leases):
1876
+ lease.__exit__(None, None, None)
1877
+ raise
1878
+ ready_event = self._vmm_arena.mark_upload(group_name, self._vmm_upload_stream, self._vmm_staging_pool)
1879
+ self._vmm_pending_group_leases[group_name] = leases
1880
+ self._vmm_pending_group_events[group_name] = ready_event
1881
+ if self._vmm_arena.stats.materializations != materializations_before:
1882
+ self.state.add_copy(f"vmm_prefetch:{group_name}:weights", time.perf_counter() - start, copied_bytes)
1883
+
1884
+ def _submit_vmm_file_prefetch(self, group_index: int) -> None:
1885
+ """Read and enqueue the next group while CUDA computes the current one."""
1886
+ if self._vmm_prefetch_executor is None or group_index >= len(self._vmm_execution_groups):
1887
+ self._schedule_vmm_execution_group(group_index)
1888
+ return
1889
+ group_name, _linears = self._vmm_execution_groups[group_index]
1890
+ with self._vmm_prefetch_lock:
1891
+ if (
1892
+ group_name in self._vmm_prefetch_futures
1893
+ or group_name in self._vmm_pending_group_leases
1894
+ or group_name in self._vmm_active_group_leases
1895
+ ):
1896
+ return
1897
+
1898
+ def worker() -> None:
1899
+ torch.cuda.set_device(self.execution_device)
1900
+ self._schedule_vmm_execution_group(group_index)
1901
+
1902
+ self._vmm_prefetch_futures[group_name] = self._vmm_prefetch_executor.submit(worker)
1903
+
1904
+ def _enter_vmm_execution_group(self, group_index: int) -> None:
1905
+ group_name, _linears = self._vmm_execution_groups[group_index]
1906
+ with self._vmm_prefetch_lock:
1907
+ future = self._vmm_prefetch_futures.pop(group_name, None)
1908
+ if future is not None:
1909
+ future.result()
1910
+ else:
1911
+ self._schedule_vmm_execution_group(group_index)
1912
+ if group_name in self._vmm_active_group_leases:
1913
+ raise RuntimeError(f"vmm_runtime group {group_name!r} was entered while still active")
1914
+ leases = self._vmm_pending_group_leases.pop(group_name)
1915
+ ready_event = self._vmm_pending_group_events.pop(group_name)
1916
+ torch.cuda.current_stream(self.execution_device).wait_event(ready_event)
1917
+ self._vmm_active_group_leases[group_name] = leases
1918
+ self._submit_vmm_file_prefetch(group_index + 1)
1919
+
1920
+ def _leave_vmm_execution_group(self, group_name: str) -> None:
1921
+ leases = self._vmm_active_group_leases.pop(group_name, ())
1922
+ for lease in reversed(leases):
1923
+ lease.__exit__(None, None, None)
1924
+
1925
+ def _clear_vmm_execution_groups(self) -> None:
1926
+ while self._vmm_group_hooks:
1927
+ self._vmm_group_hooks.pop().remove()
1928
+ executor = self._vmm_prefetch_executor
1929
+ if executor is not None:
1930
+ with self._vmm_prefetch_lock:
1931
+ futures = list(self._vmm_prefetch_futures.values())
1932
+ self._vmm_prefetch_futures.clear()
1933
+ for future in futures:
1934
+ future.result()
1935
+ executor.shutdown(wait=True)
1936
+ self._vmm_prefetch_executor = None
1937
+ for group_name in list(self._vmm_active_group_leases):
1938
+ self._leave_vmm_execution_group(group_name)
1939
+ for group_name in list(self._vmm_pending_group_leases):
1940
+ self._leave_vmm_pending_group(group_name)
1941
+ self._vmm_execution_groups.clear()
1942
+
1943
+ def _leave_vmm_pending_group(self, group_name: str) -> None:
1944
+ event = self._vmm_pending_group_events.pop(group_name, None)
1945
+ if event is not None:
1946
+ event.synchronize()
1947
+ leases = self._vmm_pending_group_leases.pop(group_name, ())
1948
+ for lease in reversed(leases):
1949
+ lease.__exit__(None, None, None)
1950
+
1951
+ def _close_vmm_store(self, module: nn.Module | None = None) -> None:
1952
+ if not self._vmm_runtime_active and self._vmm_arena is None and self._vmm_fast_store is None:
1953
+ return
1954
+ self._vmm_store = None
1955
+ self._vmm_runtime_active = False
1956
+ if self._vmm_fast_adapter is not None:
1957
+ self._vmm_fast_adapter.close()
1958
+ self._vmm_fast_adapter = None
1959
+ if self._vmm_fast_store is not None:
1960
+ self._vmm_fast_store.close()
1961
+ self._vmm_fast_store = None
1962
+ if self._vmm_arena is not None:
1963
+ self._vmm_arena.close()
1964
+ self._vmm_arena = None
1965
+ if self._vmm_host_registry is not None:
1966
+ self._vmm_host_registry.close()
1967
+ self._vmm_host_registry = None
1968
+ if self._vmm_staging_pool is not None:
1969
+ self._vmm_staging_pool.close()
1970
+ self._vmm_staging_pool = None
1971
+ self._vmm_upload_stream = None
1972
+ if self._vmm_file_slices is not None:
1973
+ self._vmm_file_slices.close()
1974
+ if module is not None and getattr(module, "_ddo_safetensor_slices", None) is self._vmm_file_slices:
1975
+ delattr(module, "_ddo_safetensor_slices")
1976
+ if hasattr(module, "_ddo_safetensor_slice_summary"):
1977
+ delattr(module, "_ddo_safetensor_slice_summary")
1978
+ self._vmm_file_slices = None
1979
+
1980
+ @staticmethod
1981
+ def _is_sdnq_layer(module: nn.Module) -> bool:
1982
+ """Duck-type SDNQ layers without making SDNQ a DDO dependency."""
1983
+ return _is_sdnq_module(module)
1984
+
1985
+ def _prepare_sdnq_runtime(self, module: nn.Module) -> None:
1986
+ """Preserve SDNQ forwards while swapping their packed parameters on demand.
1987
+
1988
+ This is deliberately separate from ``linear_runtime``: SDNQ's forward
1989
+ owns dequantization/Hadamard behavior and must never be replaced with
1990
+ ``F.linear`` by DDO.
1991
+ """
1992
+ skip_patterns = tuple(re.compile(pattern) for pattern in self.config.skip_modules_pattern)
1993
+ resident_patterns = tuple(re.compile(pattern) for pattern in self.config.always_resident_modules_pattern)
1994
+ if self.state.resolved_resident_module_patterns:
1995
+ resident_module_patterns = tuple(re.compile(pattern) for pattern in self.state.resolved_resident_module_patterns)
1996
+ else:
1997
+ resident_module_patterns = _resolve_resident_module_patterns(module, self.config)
1998
+ self.state.resolved_resident_module_patterns = [pattern.pattern for pattern in resident_module_patterns]
1999
+
2000
+ # Keep SDNQ's own forward/dequantizer, but apply the same generic
2001
+ # capacity planning as the dense runtime before choosing residents.
2002
+ # Without this, a named profile is loaded yet its recommended budget
2003
+ # never reaches ``_select_resident_modules`` in this runtime.
2004
+ self._apply_auto_budget_policy(module, skip_patterns, resident_patterns, resident_module_patterns)
2005
+ self._move_root_local_tensors_to_device(module)
2006
+ # Profile calibration starts from the same zero-resident baseline for
2007
+ # dense and SDNQ runtimes. SDNQ may schedule a later probe only after
2008
+ # that workload peak has been measured.
2009
+ if self.config.build_profile:
2010
+ self.resident_module_budget_bytes = 0
2011
+ self.state.planner_decisions["auto_resident_module_budget_gb"] = 0.0
2012
+ self.state.planner_decisions["auto_resident_module_decision"] = "profile_calibration"
2013
+ if self.resident_module_budget_bytes > 0 and resident_module_patterns:
2014
+ start = time.perf_counter()
2015
+ selected_bytes = self._select_resident_modules(module, skip_patterns, resident_module_patterns)
2016
+ self.state.add_setup("select_resident_modules", time.perf_counter() - start, selected_bytes)
2017
+ self.state.planner_decisions["selected_resident_module_gb"] = round(selected_bytes / 1024**3, 4)
2018
+
2019
+ self._select_sdnq_parameters_to_pin(module, skip_patterns)
2020
+
2021
+ for module_name, submodule in module.named_modules():
2022
+ if not module_name or (skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns)):
2023
+ continue
2024
+ if self._is_descendant_of_resident_module(module_name):
2025
+ continue
2026
+ if module_name in self._resident_module_names:
2027
+ start = time.perf_counter()
2028
+ moved_bytes = self._move_resident_module_to_execution_device(module_name, submodule)
2029
+ self.state.add_setup("resident_budget_modules_to_device", time.perf_counter() - start, moved_bytes)
2030
+ continue
2031
+ if self._is_sdnq_layer(submodule):
2032
+ self._move_sdnq_parameters_to_offload_device(submodule)
2033
+ self._patch_sdnq_layer(module_name, submodule)
2034
+ elif isinstance(submodule, (nn.Linear, nn.Embedding)):
2035
+ start = time.perf_counter()
2036
+ moved_bytes = self._move_module_tensors_to_execution_device(submodule)
2037
+ self.state.add_setup("dense_sdnq_model_modules_to_device", time.perf_counter() - start, moved_bytes)
2038
+ else:
2039
+ self._move_small_local_tensors_to_device(submodule)
2040
+
2041
+ def _collect_sdnq_parameters(
2042
+ self, module: nn.Module, skip_patterns: tuple[re.Pattern[str], ...]
2043
+ ) -> list[tuple[str, nn.Parameter, int]]:
2044
+ """Collect the same packed-parameter population for planning and pinning."""
2045
+ candidates: list[tuple[str, nn.Parameter, int]] = []
2046
+ seen: set[int] = set()
2047
+ for name, layer in module.named_modules():
2048
+ if not name or not self._is_sdnq_layer(layer):
2049
+ continue
2050
+ if (skip_patterns and any(pattern.search(name) for pattern in skip_patterns)) or (
2051
+ name in self._resident_module_names or self._is_descendant_of_resident_module(name)
2052
+ ):
2053
+ continue
2054
+ for parameter_name, parameter in layer.named_parameters(recurse=False):
2055
+ if id(parameter) not in seen:
2056
+ seen.add(id(parameter))
2057
+ candidates.append((f"{name}.{parameter_name}", parameter, _tensor_size_bytes(parameter.data)))
2058
+ return candidates
2059
+
2060
+ def _select_sdnq_parameters_to_pin(
2061
+ self, module: nn.Module, skip_patterns: tuple[re.Pattern[str], ...]
2062
+ ) -> None:
2063
+ """Bound packed-parameter pinning without changing residency heuristics.
2064
+
2065
+ Include scales and other backend parameters, not dense weight shapes.
2066
+ Existing pinned tensors remain owned by their loader and consume the
2067
+ ceiling; DDO never unpins them to satisfy a smaller requested budget.
2068
+ """
2069
+ candidates = self._collect_sdnq_parameters(module, skip_patterns)
2070
+ candidate_bytes = sum(size for _, _, size in candidates)
2071
+ limits = [candidate_bytes]
2072
+ if self.pin_weight_budget_bytes > 0:
2073
+ limits.append(self.pin_weight_budget_bytes)
2074
+ if self.pin_weight_budget_ratio > 0:
2075
+ limits.append(int(candidate_bytes * self.pin_weight_budget_ratio))
2076
+ if self.max_pin_weight_budget_bytes > 0:
2077
+ limits.append(self.max_pin_weight_budget_bytes)
2078
+ if self.available_system_ram_bytes > 0:
2079
+ limits.append(max(0, self.available_system_ram_bytes - self.system_ram_headroom_bytes))
2080
+ budget = min(limits)
2081
+ if not self.config.pin_cpu_memory or self._skip_pin_weights or self._pin_memory_disabled:
2082
+ budget = 0
2083
+ existing_bytes = sum(
2084
+ size for _, parameter, size in candidates
2085
+ if parameter.device.type == "cpu" and parameter.data.is_pinned()
2086
+ )
2087
+ remaining = max(0, budget - existing_bytes)
2088
+ ordered = candidates
2089
+ if self.pin_weight_selection == "largest":
2090
+ ordered = _largest_first_order(candidates)
2091
+ elif self.pin_weight_selection == "spread":
2092
+ ordered = _spread_order(candidates, budget)
2093
+ self._sdnq_parameters_to_pin.clear()
2094
+ self._sdnq_parameters_seen.clear()
2095
+ for _, parameter, size in ordered:
2096
+ if parameter.device.type == "cpu" and parameter.data.is_pinned():
2097
+ continue
2098
+ if budget > 0 and 0 < size <= remaining:
2099
+ self._sdnq_parameters_to_pin.add(id(parameter))
2100
+ remaining -= size
2101
+ self.state.planner_decisions.update({
2102
+ "sdnq_candidate_parameter_bytes": candidate_bytes,
2103
+ "sdnq_pin_parameter_budget_bytes": budget,
2104
+ "sdnq_existing_pinned_parameter_bytes": existing_bytes,
2105
+ "sdnq_existing_pinned_over_budget_bytes": max(0, existing_bytes - budget),
2106
+ })
2107
+
2108
+ def _move_sdnq_parameters_to_offload_device(self, layer: nn.Module) -> None:
2109
+ for parameter_name, parameter in layer.named_parameters(recurse=False):
2110
+ if id(parameter) in self._sdnq_parameters_seen:
2111
+ continue
2112
+ self._sdnq_parameters_seen.add(id(parameter))
2113
+ byte_count = _tensor_size_bytes(parameter.data)
2114
+ if parameter.device != self.offload_device:
2115
+ start = time.perf_counter()
2116
+ parameter.data = parameter.data.to(self.offload_device)
2117
+ self.state.add_setup(f"sdnq_{parameter_name}_to_offload", time.perf_counter() - start, byte_count)
2118
+ if (
2119
+ id(parameter) in self._sdnq_parameters_to_pin
2120
+ and self.offload_device.type == "cpu"
2121
+ and parameter.device.type == "cpu"
2122
+ and not self._pin_memory_disabled
2123
+ and not parameter.data.is_pinned()
2124
+ ):
2125
+ try:
2126
+ parameter.data = parameter.data.pin_memory()
2127
+ except _PIN_MEMORY_ERRORS as exc:
2128
+ if not self.config.allow_pin_memory_fallback:
2129
+ raise
2130
+ self._disable_pin_memory("pin_sdnq_parameters_failed", exc)
2131
+ if parameter.device.type == "cpu":
2132
+ if parameter.data.is_pinned():
2133
+ self.state.sdnq_pinned_parameter_count += 1
2134
+ self.state.sdnq_pinned_parameter_bytes += byte_count
2135
+ else:
2136
+ self.state.sdnq_unpinned_parameter_count += 1
2137
+ self.state.sdnq_unpinned_parameter_bytes += byte_count
2138
+
2139
+ def _patch_sdnq_layer(self, module_name: str, layer: nn.Module) -> None:
2140
+ original_forward = layer.forward
2141
+ self._patched_modules.append((layer, original_forward))
2142
+ self.state.patched_module_count += 1
2143
+
2144
+ def dynamic_sdnq_forward(patched_layer, *args, **kwargs):
2145
+ swapped: list[tuple[torch.nn.Parameter, torch.Tensor]] = []
2146
+ try:
2147
+ for parameter_name, parameter in patched_layer.named_parameters(recurse=False):
2148
+ if parameter.device == self.execution_device:
2149
+ continue
2150
+ source = parameter.data
2151
+ start = time.perf_counter()
2152
+ parameter.data = source.to(self.execution_device, non_blocking=True)
2153
+ self.state.add_copy(
2154
+ f"sdnq:{module_name}:{parameter_name}", time.perf_counter() - start, _tensor_size_bytes(parameter.data)
2155
+ )
2156
+ swapped.append((parameter, source))
2157
+ return original_forward(*args, **kwargs)
2158
+ finally:
2159
+ for parameter, source in reversed(swapped):
2160
+ parameter.data = source
2161
+
2162
+ layer.forward = dynamic_sdnq_forward.__get__(layer, layer.__class__)
2163
+
2164
+ def _collect_linear_modules_to_pin(
2165
+ self,
2166
+ module: nn.Module,
2167
+ skip_patterns: tuple[re.Pattern[str], ...],
2168
+ resident_patterns: tuple[re.Pattern[str], ...],
2169
+ ) -> list[tuple[str, nn.Module, int]]:
2170
+ candidates: list[tuple[str, nn.Module, int]] = []
2171
+ for module_name, submodule in module.named_modules():
2172
+ targets = (nn.Linear, nn.Embedding)
2173
+ if self.config.linear_convolution_offload:
2174
+ targets += (nn.Conv1d, nn.Conv2d, nn.Conv3d)
2175
+ if module_name == "" or not isinstance(submodule, targets):
2176
+ continue
2177
+ if isinstance(submodule, nn.Linear) and not self._can_patch_linear(submodule):
2178
+ continue
2179
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
2180
+ continue
2181
+ if self._is_descendant_of_resident_module(module_name):
2182
+ continue
2183
+ if module_name in self._resident_module_names:
2184
+ continue
2185
+ if resident_patterns and any(pattern.search(module_name) for pattern in resident_patterns):
2186
+ continue
2187
+ if submodule.weight.device.type == "cpu" and not submodule.weight.data.is_pinned():
2188
+ candidates.append((module_name, submodule, _tensor_size_bytes(submodule.weight.data)))
2189
+ return candidates
2190
+
2191
+ def _move_linear_to_runtime_devices(
2192
+ self,
2193
+ module_name: str,
2194
+ linear: nn.Linear,
2195
+ modules_to_pin: list[tuple[str, nn.Module, int]] | None,
2196
+ ) -> None:
2197
+ if linear.weight.device != self.offload_device:
2198
+ start = time.perf_counter()
2199
+ weight_bytes = _tensor_size_bytes(linear.weight.data)
2200
+ linear.weight.data = linear.weight.data.to(self.offload_device)
2201
+ self.state.add_setup("linear_weights_to_offload", time.perf_counter() - start, weight_bytes)
2202
+ if linear.bias is not None and linear.bias.device != self.execution_device:
2203
+ start = time.perf_counter()
2204
+ bias_bytes = _tensor_size_bytes(linear.bias.data)
2205
+ linear.bias.data = linear.bias.data.to(self.execution_device)
2206
+ self.state.add_setup("linear_bias_to_device", time.perf_counter() - start, bias_bytes)
2207
+ if modules_to_pin is not None and linear.weight.device.type == "cpu" and not linear.weight.data.is_pinned():
2208
+ modules_to_pin.append((module_name, linear, _tensor_size_bytes(linear.weight.data)))
2209
+
2210
+ def _move_embedding_to_runtime_devices(
2211
+ self,
2212
+ module_name: str,
2213
+ embedding: nn.Embedding,
2214
+ modules_to_pin: list[tuple[str, nn.Module, int]] | None,
2215
+ ) -> None:
2216
+ if embedding.weight.device != self.offload_device:
2217
+ start = time.perf_counter()
2218
+ weight_bytes = _tensor_size_bytes(embedding.weight.data)
2219
+ embedding.weight.data = embedding.weight.data.to(self.offload_device)
2220
+ self.state.add_setup("embedding_weights_to_offload", time.perf_counter() - start, weight_bytes)
2221
+ if modules_to_pin is not None and embedding.weight.device.type == "cpu" and not embedding.weight.data.is_pinned():
2222
+ modules_to_pin.append((module_name, embedding, _tensor_size_bytes(embedding.weight.data)))
2223
+
2224
+ def _select_linear_weights_to_pin(self, candidates: list[tuple[str, nn.Module, int]]) -> list[tuple[str, nn.Module]]:
2225
+ candidate_bytes = sum(weight_bytes for _, _, weight_bytes in candidates)
2226
+ if self._force_full_pin_weights:
2227
+ self.state.planner_decisions["resolved_pin_weight_budget_mode"] = "snap_to_full_pin"
2228
+ self.state.planner_decisions["resolved_pin_weight_budget_gb"] = round(candidate_bytes / 1024**3, 4)
2229
+ self.state.selected_pinned_linear_weights = [module_name for module_name, _, _ in candidates]
2230
+ return [(module_name, linear) for module_name, linear, _ in candidates]
2231
+ pin_weight_budget_bytes = self.pin_weight_budget_bytes
2232
+ requested_unlimited_pin = pin_weight_budget_bytes <= 0 and self.pin_weight_budget_ratio <= 0
2233
+ if pin_weight_budget_bytes <= 0 and self.pin_weight_budget_ratio > 0:
2234
+ pin_weight_budget_bytes = int(candidate_bytes * self.pin_weight_budget_ratio)
2235
+ if pin_weight_budget_bytes > 0 and self.max_pin_weight_budget_bytes > 0:
2236
+ pin_weight_budget_bytes = min(pin_weight_budget_bytes, self.max_pin_weight_budget_bytes)
2237
+ if candidate_bytes > 0 and pin_weight_budget_bytes >= int(candidate_bytes * 0.95):
2238
+ pin_weight_budget_bytes = 0
2239
+ self.state.planner_decisions["pin_weight_budget_snap_to_full"] = True
2240
+ if pin_weight_budget_bytes <= 0:
2241
+ self.state.planner_decisions["resolved_pin_weight_budget_mode"] = (
2242
+ "unlimited_full_pin" if requested_unlimited_pin else "snap_to_full_pin"
2243
+ )
2244
+ self.state.planner_decisions["resolved_pin_weight_budget_gb"] = round(candidate_bytes / 1024**3, 4)
2245
+ self.state.selected_pinned_linear_weights = [module_name for module_name, _, _ in candidates]
2246
+ return [(module_name, linear) for module_name, linear, _ in candidates]
2247
+
2248
+ self.state.planner_decisions["resolved_pin_weight_budget_mode"] = "limited"
2249
+ self.state.planner_decisions["resolved_pin_weight_budget_gb"] = round(pin_weight_budget_bytes / 1024**3, 4)
2250
+ ordered_candidates = candidates
2251
+ if self.pin_weight_selection == "spread":
2252
+ ordered_candidates = _spread_order(candidates, pin_weight_budget_bytes)
2253
+ elif self.pin_weight_selection == "largest":
2254
+ ordered_candidates = _largest_first_order(candidates)
2255
+
2256
+ selected_linears: list[tuple[str, nn.Module]] = []
2257
+ selected_bytes = 0
2258
+ selected_names: list[str] = []
2259
+ for module_name, linear, weight_bytes in ordered_candidates:
2260
+ if selected_bytes + weight_bytes > pin_weight_budget_bytes:
2261
+ continue
2262
+ selected_linears.append((module_name, linear))
2263
+ selected_names.append(module_name)
2264
+ selected_bytes += weight_bytes
2265
+
2266
+ self.state.selected_pinned_linear_weights = selected_names
2267
+ return selected_linears
2268
+
2269
+ def _apply_auto_budget_policy(
2270
+ self,
2271
+ module: nn.Module,
2272
+ skip_patterns: tuple[re.Pattern[str], ...],
2273
+ resident_patterns: tuple[re.Pattern[str], ...],
2274
+ resident_module_patterns: tuple[re.Pattern[str], ...],
2275
+ ) -> None:
2276
+ if self.auto_budget_policy == _AUTO_BUDGET_DISABLED:
2277
+ return
2278
+
2279
+ if self.execution_mode == "sdnq_runtime":
2280
+ # Packed weights, scales and correction tensors are transferred by
2281
+ # the SDNQ wrapper; dense fallback Linears are kept on the device.
2282
+ # Dense shape eligibility must not define SDNQ pin/RAM admission.
2283
+ candidate_weight_bytes = sum(
2284
+ size for _, _, size in self._collect_sdnq_parameters(module, skip_patterns)
2285
+ )
2286
+ else:
2287
+ candidate_weight_bytes = sum(
2288
+ weight_bytes
2289
+ for _, _, weight_bytes in self._collect_linear_modules_to_pin(module, skip_patterns, resident_patterns)
2290
+ )
2291
+ candidate_module_bytes = 0
2292
+ if resident_module_patterns:
2293
+ candidate_module_bytes = sum(
2294
+ module_bytes
2295
+ for module_name, submodule in module.named_modules()
2296
+ if module_name
2297
+ and not (skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns))
2298
+ and any(pattern.search(module_name) for pattern in resident_module_patterns)
2299
+ for module_bytes in (_module_size_bytes(submodule),)
2300
+ )
2301
+
2302
+ self.state.planner_decisions.update(
2303
+ {
2304
+ "auto_budget_policy": self.auto_budget_policy,
2305
+ "candidate_weight_gb": round(candidate_weight_bytes / 1024**3, 4),
2306
+ "candidate_resident_module_gb": round(candidate_module_bytes / 1024**3, 4),
2307
+ "available_system_ram_gb": round(self.available_system_ram_bytes / 1024**3, 4),
2308
+ "system_ram_headroom_gb": round(self.system_ram_headroom_bytes / 1024**3, 4),
2309
+ }
2310
+ )
2311
+
2312
+ total_vram_gb = get_cuda_total_vram_gb(self.execution_device)
2313
+ total_vram_bytes = int(total_vram_gb * 1024**3)
2314
+ model_to_vram_ratio = candidate_module_bytes / total_vram_bytes if total_vram_bytes > 0 else 0.0
2315
+ if total_vram_gb > 0:
2316
+ self.state.planner_decisions["cuda_total_vram_gb"] = round(total_vram_gb, 4)
2317
+ self.state.planner_decisions["auto_model_to_vram_ratio"] = round(model_to_vram_ratio, 4)
2318
+
2319
+ usable_ram_bytes = max(0, self.available_system_ram_bytes - self.system_ram_headroom_bytes)
2320
+ requested_profile_resident_bytes = int(
2321
+ max(0.0, float(self.config.profile_resident_module_budget_gb)) * 1024**3
2322
+ )
2323
+ can_auto_full_pin = (
2324
+ self.config.pin_cpu_memory
2325
+ and self.pin_weight_budget_bytes <= 0
2326
+ and self.pin_weight_budget_ratio <= 0
2327
+ and self.resident_module_budget_bytes <= 0
2328
+ and self.max_pin_weight_budget_bytes <= 0
2329
+ and self.available_system_ram_bytes > 0
2330
+ and candidate_weight_bytes > 0
2331
+ and usable_ram_bytes >= candidate_weight_bytes
2332
+ and self.config.auto_full_pin_min_model_to_vram_ratio > 0
2333
+ and model_to_vram_ratio >= self.config.auto_full_pin_min_model_to_vram_ratio
2334
+ )
2335
+ profile_resident_budget_bytes = min(requested_profile_resident_bytes, candidate_module_bytes)
2336
+ can_apply_profile_resident_budget = (
2337
+ can_auto_full_pin
2338
+ and profile_resident_budget_bytes > 0
2339
+ and usable_ram_bytes >= candidate_weight_bytes + profile_resident_budget_bytes
2340
+ )
2341
+ self.state.planner_decisions["auto_usable_system_ram_gb"] = round(usable_ram_bytes / 1024**3, 4)
2342
+ self.state.planner_decisions["auto_full_pin_min_model_to_vram_ratio"] = (
2343
+ self.config.auto_full_pin_min_model_to_vram_ratio
2344
+ )
2345
+ self.state.planner_decisions["profile_resident_module_budget_requested_gb"] = round(
2346
+ requested_profile_resident_bytes / 1024**3, 4
2347
+ )
2348
+
2349
+ if self.resident_module_budget_bytes <= 0 and candidate_module_bytes > 0 and not can_auto_full_pin:
2350
+ budget = int(candidate_module_bytes * 0.25)
2351
+ if total_vram_gb > 0:
2352
+ vram_headroom_gb = self.config.auto_vram_headroom_gb
2353
+ if vram_headroom_gb <= 0:
2354
+ if total_vram_gb <= 8.5:
2355
+ vram_headroom_gb = 3.0 if model_to_vram_ratio <= 2.5 else 2.0
2356
+ elif total_vram_gb <= 12.5:
2357
+ vram_headroom_gb = 2.5
2358
+ else:
2359
+ vram_headroom_gb = max(3.0, total_vram_gb * 0.15)
2360
+ self.state.planner_decisions["auto_model_to_vram_ratio"] = round(model_to_vram_ratio, 4)
2361
+ vram_target_gb = max(1.0, total_vram_gb - vram_headroom_gb)
2362
+ vram_target_bytes = int(vram_target_gb * 1024**3)
2363
+ candidate_exceeds_vram = candidate_module_bytes > int(total_vram_gb * 1024**3)
2364
+ if candidate_exceeds_vram:
2365
+ budget = max(budget, vram_target_bytes)
2366
+ budget = min(budget, candidate_module_bytes)
2367
+ self.state.planner_decisions["auto_resident_module_budget_vram_target_gb"] = round(
2368
+ vram_target_gb, 4
2369
+ )
2370
+ self.state.planner_decisions["auto_vram_headroom_gb"] = round(vram_headroom_gb, 4)
2371
+ if budget > vram_target_bytes:
2372
+ budget = vram_target_bytes
2373
+ self.state.planner_decisions["auto_resident_module_budget_vram_cap_gb"] = round(vram_target_gb, 4)
2374
+ self.state.planner_decisions["auto_vram_headroom_gb"] = round(vram_headroom_gb, 4)
2375
+ self.state.planner_decisions["auto_resident_module_budget_vram_cap_reason"] = (
2376
+ "cuda_vram_headroom"
2377
+ )
2378
+ if self.config._profile_budget_applied:
2379
+ budget = min(requested_profile_resident_bytes, candidate_module_bytes)
2380
+ if self.max_resident_module_budget_bytes > 0:
2381
+ budget = min(budget, self.max_resident_module_budget_bytes)
2382
+ self.resident_module_budget_bytes = budget
2383
+ self.state.planner_decisions["auto_resident_module_budget_gb"] = round(budget / 1024**3, 4)
2384
+ elif can_auto_full_pin:
2385
+ if can_apply_profile_resident_budget:
2386
+ self.resident_module_budget_bytes = profile_resident_budget_bytes
2387
+ self.state.planner_decisions["auto_resident_module_budget_gb"] = round(
2388
+ profile_resident_budget_bytes / 1024**3, 4
2389
+ )
2390
+ self.state.planner_decisions["auto_resident_module_decision"] = "full_pin_profile_resident"
2391
+ else:
2392
+ self.state.planner_decisions["auto_resident_module_budget_gb"] = 0.0
2393
+ self.state.planner_decisions["auto_resident_module_decision"] = "zero_for_full_pin"
2394
+ if requested_profile_resident_bytes > 0:
2395
+ self.state.planner_decisions["profile_resident_module_skip_reason"] = "insufficient_ram"
2396
+
2397
+ if self.pin_weight_budget_bytes <= 0 and self.pin_weight_budget_ratio <= 0 and candidate_weight_bytes > 0:
2398
+ if can_auto_full_pin:
2399
+ ratio = 1.0
2400
+ budget = candidate_weight_bytes
2401
+ self.state.planner_decisions["auto_pin_weight_decision"] = (
2402
+ "full_pin_profile_resident" if can_apply_profile_resident_budget else "full_pin_zero_resident"
2403
+ )
2404
+ elif candidate_weight_bytes <= 8 * 1024**3:
2405
+ ratio = 1.0
2406
+ budget = int(candidate_weight_bytes * ratio)
2407
+ elif candidate_weight_bytes <= 16 * 1024**3:
2408
+ ratio = 0.85
2409
+ budget = int(candidate_weight_bytes * ratio)
2410
+ else:
2411
+ ratio = 0.75
2412
+ budget = int(candidate_weight_bytes * ratio)
2413
+ if self.max_pin_weight_budget_bytes > 0:
2414
+ budget = min(budget, self.max_pin_weight_budget_bytes)
2415
+ if self.available_system_ram_bytes > 0:
2416
+ required_ram_bytes = candidate_weight_bytes + self.resident_module_budget_bytes
2417
+ self.state.planner_decisions["auto_required_system_ram_gb"] = round(required_ram_bytes / 1024**3, 4)
2418
+ if usable_ram_bytes < required_ram_bytes:
2419
+ budget = 0
2420
+ ratio = 0.0
2421
+ self._skip_pin_weights = True
2422
+ self.state.planner_decisions["auto_pin_weight_decision"] = "skip_insufficient_ram"
2423
+ elif not can_auto_full_pin:
2424
+ self.state.planner_decisions["auto_pin_weight_decision"] = "budgeted"
2425
+ elif not can_auto_full_pin:
2426
+ self.state.planner_decisions["auto_pin_weight_decision"] = "budgeted"
2427
+ self.pin_weight_budget_bytes = budget
2428
+ self.state.planner_decisions["auto_pin_weight_budget_gb"] = round(budget / 1024**3, 4)
2429
+ self.state.planner_decisions["auto_pin_weight_budget_ratio"] = ratio
2430
+
2431
+ def _select_resident_modules(
2432
+ self,
2433
+ module: nn.Module,
2434
+ skip_patterns: tuple[re.Pattern[str], ...],
2435
+ module_patterns: tuple[re.Pattern[str], ...],
2436
+ ) -> int:
2437
+ candidates: list[tuple[str, nn.Module, int]] = []
2438
+ for module_name, submodule in module.named_modules():
2439
+ if module_name == "":
2440
+ continue
2441
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
2442
+ continue
2443
+ if not any(pattern.search(module_name) for pattern in module_patterns):
2444
+ continue
2445
+ if any(_is_module_descendant(module_name, selected_name) for selected_name in self._resident_module_names):
2446
+ continue
2447
+ candidates.append((module_name, submodule, _module_size_bytes(submodule)))
2448
+
2449
+ ordered_candidates = candidates
2450
+ if self.resident_module_selection == "spread":
2451
+ ordered_candidates = _spread_order(candidates, self.resident_module_budget_bytes)
2452
+ elif self.resident_module_selection == "largest":
2453
+ ordered_candidates = _largest_first_order(candidates)
2454
+
2455
+ selected_bytes = 0
2456
+ for module_name, _, module_bytes in ordered_candidates:
2457
+ if selected_bytes + module_bytes > self.resident_module_budget_bytes:
2458
+ continue
2459
+ self._resident_module_names.add(module_name)
2460
+ self.state.selected_resident_modules.append(module_name)
2461
+ selected_bytes += module_bytes
2462
+ return selected_bytes
2463
+
2464
+ def _is_descendant_of_resident_module(self, module_name: str) -> bool:
2465
+ return any(_is_module_descendant(module_name, resident_name) for resident_name in self._resident_module_names)
2466
+
2467
+ def _move_resident_module_to_execution_device(self, _module_name: str, module: nn.Module) -> int:
2468
+ return self._move_module_tensors_to_execution_device(module)
2469
+
2470
+ def _move_module_tensors_to_execution_device(self, module: nn.Module) -> int:
2471
+ moved_bytes = 0
2472
+ for parameter in module.parameters(recurse=True):
2473
+ tensor_bytes = _tensor_size_bytes(parameter.data)
2474
+ moved_bytes += tensor_bytes
2475
+ if parameter.device != self.execution_device:
2476
+ parameter.data = parameter.data.to(self.execution_device)
2477
+ for buffer in module.buffers(recurse=True):
2478
+ tensor_bytes = _tensor_size_bytes(buffer.data)
2479
+ moved_bytes += tensor_bytes
2480
+ if buffer.device != self.execution_device:
2481
+ buffer.data = buffer.data.to(self.execution_device)
2482
+ return moved_bytes
2483
+
2484
+ def _move_root_local_tensors_to_device(self, module: nn.Module) -> None:
2485
+ start = time.perf_counter()
2486
+ moved_bytes = 0
2487
+ for parameter in module.parameters(recurse=False):
2488
+ if parameter.device == self.execution_device:
2489
+ continue
2490
+ tensor_bytes = _tensor_size_bytes(parameter.data)
2491
+ parameter.data = parameter.data.to(self.execution_device)
2492
+ moved_bytes += tensor_bytes
2493
+ for buffer in module.buffers(recurse=False):
2494
+ if buffer.device == self.execution_device:
2495
+ continue
2496
+ tensor_bytes = _tensor_size_bytes(buffer.data)
2497
+ buffer.data = buffer.data.to(self.execution_device)
2498
+ moved_bytes += tensor_bytes
2499
+ if moved_bytes:
2500
+ self.state.add_setup("root_tensors_to_device", time.perf_counter() - start, moved_bytes)
2501
+
2502
+ def _move_small_local_tensors_to_device(self, module: nn.Module) -> int:
2503
+ moved_bytes = 0
2504
+ for parameter in module.parameters(recurse=False):
2505
+ if parameter.device == self.execution_device:
2506
+ continue
2507
+ tensor_bytes = _tensor_size_bytes(parameter.data)
2508
+ if tensor_bytes > self.config.small_tensor_threshold_bytes:
2509
+ continue
2510
+ start = time.perf_counter()
2511
+ parameter.data = parameter.data.to(self.execution_device)
2512
+ self.state.add_setup("small_parameters_to_device", time.perf_counter() - start, tensor_bytes)
2513
+ moved_bytes += tensor_bytes
2514
+ for buffer in module.buffers(recurse=False):
2515
+ if buffer.device == self.execution_device:
2516
+ continue
2517
+ tensor_bytes = _tensor_size_bytes(buffer.data)
2518
+ if tensor_bytes > self.config.small_tensor_threshold_bytes:
2519
+ continue
2520
+ start = time.perf_counter()
2521
+ buffer.data = buffer.data.to(self.execution_device)
2522
+ self.state.add_setup("small_buffers_to_device", time.perf_counter() - start, tensor_bytes)
2523
+ moved_bytes += tensor_bytes
2524
+ return moved_bytes
2525
+
2526
+ def _pin_linear_weights(self, linears: list[tuple[str, nn.Module]]) -> int:
2527
+ pinned_bytes = 0
2528
+ assignment_lock = threading.Lock()
2529
+
2530
+ def pin_linear(module_name: str, linear: nn.Module) -> tuple[int, bool]:
2531
+ weight = linear.weight.data
2532
+ cached = self._get_cached_pinned_weight(module_name, weight)
2533
+ if cached is not None:
2534
+ pinned = cached
2535
+ cache_hit = True
2536
+ else:
2537
+ pinned = weight.pin_memory()
2538
+ cache_hit = False
2539
+ pinned = self._store_cached_pinned_weight(module_name, pinned)
2540
+ tensor_bytes = _tensor_size_bytes(pinned)
2541
+ with assignment_lock:
2542
+ linear.weight.data = pinned
2543
+ return tensor_bytes, cache_hit
2544
+
2545
+ def record_pinned(result: tuple[int, bool]) -> None:
2546
+ nonlocal pinned_bytes
2547
+ tensor_bytes, cache_hit = result
2548
+ pinned_bytes += tensor_bytes
2549
+ if cache_hit:
2550
+ self.state.add_setup("pinned_weight_cache_hit", 0.0, tensor_bytes)
2551
+
2552
+ if self.pin_cpu_workers == 1:
2553
+ for module_name, linear in linears:
2554
+ try:
2555
+ record_pinned(pin_linear(module_name, linear))
2556
+ except _PIN_MEMORY_ERRORS as exc:
2557
+ if not self.config.allow_pin_memory_fallback:
2558
+ raise
2559
+ self._disable_pin_memory("pin_linear_weights_failed", exc)
2560
+ break
2561
+ return pinned_bytes
2562
+
2563
+ linears_iter = iter(linears)
2564
+ with ThreadPoolExecutor(max_workers=self.pin_cpu_workers) as executor:
2565
+ futures = set()
2566
+
2567
+ def submit_next() -> bool:
2568
+ try:
2569
+ module_name, linear = next(linears_iter)
2570
+ except StopIteration:
2571
+ return False
2572
+ futures.add(executor.submit(pin_linear, module_name, linear))
2573
+ return True
2574
+
2575
+ for _ in range(self.pin_cpu_workers):
2576
+ if not submit_next():
2577
+ break
2578
+
2579
+ while futures:
2580
+ for future in as_completed(futures):
2581
+ futures.remove(future)
2582
+ try:
2583
+ record_pinned(future.result())
2584
+ except _PIN_MEMORY_ERRORS as exc:
2585
+ if not self.config.allow_pin_memory_fallback:
2586
+ raise
2587
+ self._disable_pin_memory("pin_linear_weights_failed", exc)
2588
+ for pending in futures:
2589
+ pending.cancel()
2590
+ return pinned_bytes
2591
+ if not self._pin_memory_disabled:
2592
+ submit_next()
2593
+ break
2594
+ return pinned_bytes
2595
+
2596
+ def _get_cached_pinned_weight(self, module_name: str, tensor: torch.Tensor) -> torch.Tensor | None:
2597
+ if not self.config.cache_pinned_weights:
2598
+ return None
2599
+ cache_key = self._pinned_weight_cache_key(module_name, tensor)
2600
+ with _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE_LOCK:
2601
+ cached = _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE.get(cache_key)
2602
+ if cached is None:
2603
+ return None
2604
+ if cached.shape != tensor.shape or cached.dtype != tensor.dtype:
2605
+ return None
2606
+ return cached
2607
+
2608
+ def _store_cached_pinned_weight(self, module_name: str, tensor: torch.Tensor) -> torch.Tensor:
2609
+ if not self.config.cache_pinned_weights or not tensor.is_pinned():
2610
+ return tensor
2611
+ cache_key = self._pinned_weight_cache_key(module_name, tensor)
2612
+ with _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE_LOCK:
2613
+ cached = _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE.setdefault(cache_key, tensor)
2614
+ return cached
2615
+
2616
+ def _pinned_weight_cache_key(self, module_name: str, tensor: torch.Tensor) -> tuple[Any, ...]:
2617
+ return (
2618
+ "v1",
2619
+ self._pinned_weight_cache_namespace,
2620
+ module_name,
2621
+ tuple(tensor.shape),
2622
+ str(tensor.dtype),
2623
+ tensor.numel(),
2624
+ tensor.element_size(),
2625
+ )
2626
+
2627
+ def _disable_pin_memory(self, action: str, exc: BaseException) -> None:
2628
+ if self._pin_memory_disabled:
2629
+ return
2630
+ self._pin_memory_disabled = True
2631
+ self.state.add_setup(action, 0.0, 0)
2632
+ if self.config.verbose:
2633
+ print(
2634
+ f" [dynamic-offload] {action}: disabling pinned CPU memory fallback after {type(exc).__name__}: {exc}",
2635
+ flush=True,
2636
+ )
2637
+
2638
+ @staticmethod
2639
+ def _can_patch_linear(linear: nn.Linear) -> bool:
2640
+ weight = getattr(linear, "weight", None)
2641
+ in_features = getattr(linear, "in_features", None)
2642
+ out_features = getattr(linear, "out_features", None)
2643
+ return (
2644
+ isinstance(weight, torch.Tensor)
2645
+ and weight.ndim == 2
2646
+ and in_features is not None
2647
+ and out_features is not None
2648
+ and tuple(weight.shape) == (out_features, in_features)
2649
+ )
2650
+
2651
+ def _patch_linear(self, linear: nn.Linear) -> None:
2652
+ original_forward = linear.forward
2653
+ self._patched_modules.append((linear, original_forward))
2654
+ self.state.patched_module_count += 1
2655
+
2656
+ def dynamic_linear_forward(patched_linear, input):
2657
+ weight = self._to_input_device(patched_linear.weight, input, "linear_weight")
2658
+ bias = self._to_input_device(patched_linear.bias, input, "linear_bias")
2659
+ if self.linear_runtime_strategy == "swap":
2660
+ source_weight = patched_linear.weight.data
2661
+ source_bias = None if patched_linear.bias is None else patched_linear.bias.data
2662
+ patched_linear.weight.data = weight
2663
+ if patched_linear.bias is not None:
2664
+ patched_linear.bias.data = bias
2665
+ try:
2666
+ return original_forward(input)
2667
+ finally:
2668
+ patched_linear.weight.data = source_weight
2669
+ if patched_linear.bias is not None:
2670
+ patched_linear.bias.data = source_bias
2671
+ return F.linear(input, weight, bias)
2672
+
2673
+ linear.forward = dynamic_linear_forward.__get__(linear, linear.__class__)
2674
+
2675
+ def _patch_vmm_linear(self, module_name: str, linear: nn.Linear) -> None:
2676
+ """Execute one standard linear with a scoped VMM-backed weight view."""
2677
+ if not self._vmm_runtime_active:
2678
+ raise RuntimeError("vmm_runtime was not initialized")
2679
+ original_forward = linear.forward
2680
+ self._patched_modules.append((linear, original_forward))
2681
+ self.state.patched_module_count += 1
2682
+
2683
+ def dynamic_vmm_linear_forward(patched_linear, input):
2684
+ source_weight = patched_linear.weight.data
2685
+ if source_weight.device.type != "cpu":
2686
+ raise RuntimeError(f"vmm_runtime weight {module_name!r} must remain on CPU")
2687
+ if input.device != self.execution_device:
2688
+ input = self._move_value_to_execution_device(input, f"vmm:{module_name}:input")
2689
+
2690
+ if self._vmm_arena is not None and self._vmm_arena.contains_weight(module_name):
2691
+ mapped_weight = self._vmm_arena.weight(module_name)
2692
+ weight = mapped_weight if mapped_weight.dtype == input.dtype else mapped_weight.to(dtype=input.dtype)
2693
+ bias = self._to_input_device(patched_linear.bias, input, f"vmm:{module_name}:bias")
2694
+ return F.linear(input, weight, bias)
2695
+
2696
+ raise RuntimeError(
2697
+ f"vmm_runtime linear {module_name!r} was patched but not assigned to the native VMM arena"
2698
+ )
2699
+
2700
+ linear.forward = dynamic_vmm_linear_forward.__get__(linear, linear.__class__)
2701
+
2702
+ def _patch_embedding(self, embedding: nn.Embedding) -> None:
2703
+ original_forward = embedding.forward
2704
+ self._patched_modules.append((embedding, original_forward))
2705
+ self.state.patched_module_count += 1
2706
+
2707
+ def dynamic_embedding_forward(patched_embedding, input):
2708
+ weight = self._to_input_device(patched_embedding.weight, input, "embedding_weight", cast_to_input_dtype=False)
2709
+ if self.linear_runtime_strategy == "swap":
2710
+ source_weight = patched_embedding.weight.data
2711
+ patched_embedding.weight.data = weight
2712
+ try:
2713
+ return original_forward(input)
2714
+ finally:
2715
+ patched_embedding.weight.data = source_weight
2716
+ return F.embedding(
2717
+ input,
2718
+ weight,
2719
+ patched_embedding.padding_idx,
2720
+ patched_embedding.max_norm,
2721
+ patched_embedding.norm_type,
2722
+ patched_embedding.scale_grad_by_freq,
2723
+ patched_embedding.sparse,
2724
+ )
2725
+
2726
+ embedding.forward = dynamic_embedding_forward.__get__(embedding, embedding.__class__)
2727
+
2728
+ def _to_input_device(
2729
+ self,
2730
+ tensor: torch.Tensor | None,
2731
+ input: torch.Tensor,
2732
+ name: str,
2733
+ *,
2734
+ cast_to_input_dtype: bool = True,
2735
+ ) -> torch.Tensor | None:
2736
+ if tensor is None:
2737
+ return None
2738
+ if tensor.device == input.device and (not cast_to_input_dtype or tensor.dtype == input.dtype):
2739
+ return tensor
2740
+ start = time.perf_counter()
2741
+ dtype = input.dtype if cast_to_input_dtype else tensor.dtype
2742
+ moved = tensor.to(device=input.device, dtype=dtype, non_blocking=True)
2743
+ self.state.add_copy(name, time.perf_counter() - start, _tensor_size_bytes(moved))
2744
+ return moved
2745
+
2746
+ def print_profile_summary(self, *, top_n: int = 8) -> None:
2747
+ summary = self.state.as_dict()
2748
+ setup_runtime = summary["setup_runtime"]
2749
+ setup_seconds = sum(item["seconds"] for item in setup_runtime.values())
2750
+ setup_gb = sum(item["gb"] for item in setup_runtime.values())
2751
+ copy_runtime = summary["copy_runtime"]
2752
+ copy_seconds = sum(item["seconds"] for item in copy_runtime.values())
2753
+ copy_gb = sum(item["gb"] for item in copy_runtime.values())
2754
+ print(
2755
+ " [dynamic-offload-profile] "
2756
+ f"summary: mode={self.execution_mode} modules={summary['module_count']} "
2757
+ f"patched={summary['patched_module_count']} setup_seconds={setup_seconds:.4f} "
2758
+ f"setup_gb={setup_gb:.4f} copy_seconds={copy_seconds:.4f} "
2759
+ f"copy_gb={copy_gb:.4f}",
2760
+ flush=True,
2761
+ )
2762
+
2763
+ selected_modules = summary["selected_resident_modules"]
2764
+ resolved_patterns = summary["resolved_resident_module_patterns"]
2765
+ if resolved_patterns:
2766
+ print(
2767
+ " [dynamic-offload-profile] "
2768
+ f"resolved_resident_module_patterns={resolved_patterns}",
2769
+ flush=True,
2770
+ )
2771
+
2772
+ planner_decisions = summary["planner_decisions"]
2773
+ if planner_decisions:
2774
+ print(
2775
+ " [dynamic-offload-profile] "
2776
+ f"planner_decisions={planner_decisions}",
2777
+ flush=True,
2778
+ )
2779
+
2780
+ vmm_stats = self.vmm_runtime_stats()
2781
+ if vmm_stats is not None and "arena_materializations" in vmm_stats:
2782
+ print(
2783
+ " [dynamic-offload-profile] "
2784
+ "vmm_arena: "
2785
+ f"resident_gb={vmm_stats['arena_resident_bytes'] / 1024**3:.4f} "
2786
+ f"materializations={vmm_stats['arena_materializations']} "
2787
+ f"temporary_fallbacks={vmm_stats['arena_temporary_fallbacks']} "
2788
+ f"temporary_gb={vmm_stats['arena_temporary_bytes'] / 1024**3:.4f} "
2789
+ f"persistent_virtual_views={vmm_stats.get('arena_persistent_virtual_views', 0)} "
2790
+ f"file_stage_seconds={vmm_stats['arena_file_slice_staging_seconds']:.4f} "
2791
+ f"direct_dma_seconds={vmm_stats['arena_direct_dma_seconds']:.4f} "
2792
+ f"host_cache_gb={vmm_stats.get('host_cache_registered_bytes', 0) / 1024**3:.4f} "
2793
+ f"host_cache_skipped_gb={vmm_stats.get('host_cache_skipped_bytes', 0) / 1024**3:.4f}",
2794
+ flush=True,
2795
+ )
2796
+
2797
+ if selected_modules:
2798
+ print(
2799
+ " [dynamic-offload-profile] "
2800
+ f"resident_modules={selected_modules}",
2801
+ flush=True,
2802
+ )
2803
+
2804
+ selected_linear_weights = summary["selected_resident_linear_weights"]
2805
+ if selected_linear_weights:
2806
+ print(
2807
+ " [dynamic-offload-profile] "
2808
+ f"resident_linear_weights={selected_linear_weights[:top_n]} "
2809
+ f"count={len(selected_linear_weights)}",
2810
+ flush=True,
2811
+ )
2812
+
2813
+ selected_pinned_linear_weights = summary["selected_pinned_linear_weights"]
2814
+ if selected_pinned_linear_weights:
2815
+ print(
2816
+ " [dynamic-offload-profile] "
2817
+ f"pinned_linear_weights={selected_pinned_linear_weights[:top_n]} "
2818
+ f"count={len(selected_pinned_linear_weights)}",
2819
+ flush=True,
2820
+ )
2821
+
2822
+ if setup_runtime:
2823
+ print(" [dynamic-offload-profile] setup_runtime_by_type:", flush=True)
2824
+ for key, item in sorted(setup_runtime.items(), key=lambda pair: pair[1]["seconds"], reverse=True)[:top_n]:
2825
+ print(
2826
+ f" {key}: seconds={item['seconds']:.4f} gb={item['gb']:.4f}",
2827
+ flush=True,
2828
+ )
2829
+
2830
+ if copy_runtime:
2831
+ print(" [dynamic-offload-profile] copy_runtime_by_type:", flush=True)
2832
+ for name, item in sorted(copy_runtime.items(), key=lambda pair: pair[1]["seconds"], reverse=True)[:top_n]:
2833
+ print(
2834
+ f" {name}: calls={item['calls']} seconds={item['seconds']:.4f} gb={item['gb']:.4f}",
2835
+ flush=True,
2836
+ )
2837
+
2838
+
2839
+ def load_dynamic_offload_settings_from_env(
2840
+ *,
2841
+ execution_device: str | torch.device = "cuda:0",
2842
+ offload_device: str | torch.device = "cpu",
2843
+ target_module_classes: tuple[type[nn.Module], ...] = _DEFAULT_TARGET_MODULE_CLASSES,
2844
+ skip_modules_pattern: tuple[str, ...] = (),
2845
+ always_resident_modules_pattern: tuple[str, ...] | None = None,
2846
+ running_on_wsl: bool | None = None,
2847
+ environ: Mapping[str, str] | None = None,
2848
+ default_preset: str = "",
2849
+ component_policies: Mapping[str, Mapping[str, Any]] | None = None,
2850
+ ) -> DynamicOffloadSettings:
2851
+ env = os.environ if environ is None else environ
2852
+ is_wsl = is_wsl_environment() if running_on_wsl is None else running_on_wsl
2853
+ requested_preset = dynamic_offload_env_value("DDO_PRESET", default_preset, env).strip().lower()
2854
+ effective_preset = resolve_dynamic_offload_preset(requested_preset, running_on_wsl=is_wsl)
2855
+
2856
+ def preset_env(name: str, default: str = "") -> str:
2857
+ return dynamic_offload_preset_env_value(
2858
+ name,
2859
+ default,
2860
+ requested_preset=requested_preset,
2861
+ effective_preset=effective_preset,
2862
+ running_on_wsl=is_wsl,
2863
+ environ=env,
2864
+ )
2865
+
2866
+ def preset_bool(name: str, default: str = "0") -> bool:
2867
+ return _parse_bool_value(preset_env(name, default))
2868
+
2869
+ default_always_resident_patterns = _DEFAULT_ALWAYS_RESIDENT_MODULE_PATTERNS
2870
+ if always_resident_modules_pattern is not None:
2871
+ default_always_resident_patterns = always_resident_modules_pattern
2872
+
2873
+ available_system_ram_override = preset_env("DDO_AVAILABLE_SYSTEM_RAM_GB", "").strip()
2874
+ available_system_ram_gb = (
2875
+ float(available_system_ram_override)
2876
+ if available_system_ram_override
2877
+ else round(get_available_system_ram_gb(), 4)
2878
+ )
2879
+
2880
+ plan = preset_bool("DDO_PLAN")
2881
+ execution_mode = preset_env("DDO_EXECUTION_MODE", "plan").lower()
2882
+ requested_pin_cpu_memory = preset_bool("DDO_PIN_CPU_MEMORY")
2883
+ allow_pin_memory_fallback = preset_bool("DDO_ALLOW_PIN_MEMORY_FALLBACK", "1")
2884
+ disable_pin_on_wsl = preset_bool("DDO_DISABLE_PIN_ON_WSL", "1")
2885
+ effective_pin_cpu_memory = requested_pin_cpu_memory and not (is_wsl and disable_pin_on_wsl)
2886
+ load_safetensors_backend = preset_env("DDO_LOAD_SAFETENSORS_BACKEND", "").strip().lower()
2887
+ if not load_safetensors_backend:
2888
+ load_safetensors_backend = preset_env("DDO_SAFETENSORS_BACKEND", "").strip().lower()
2889
+
2890
+ config = DynamicOffloadConfig(
2891
+ execution_device=execution_device,
2892
+ offload_device=offload_device,
2893
+ target_module_classes=target_module_classes,
2894
+ skip_modules_pattern=skip_modules_pattern,
2895
+ always_resident_modules_pattern=_parse_pattern_list_value(
2896
+ preset_env(
2897
+ "DDO_ALWAYS_RESIDENT_MODULE_PATTERNS",
2898
+ ",".join(default_always_resident_patterns),
2899
+ )
2900
+ ),
2901
+ small_tensor_threshold_bytes=int(preset_env("DDO_SMALL_TENSOR_THRESHOLD_KB", "1024")) * 1024,
2902
+ execution_mode=execution_mode,
2903
+ linear_runtime_strategy=preset_env("DDO_LINEAR_RUNTIME_STRATEGY", "functional").lower(),
2904
+ vmm_resident_weight_budget_gb=float(preset_env("DDO_VMM_RESIDENT_WEIGHT_BUDGET_GB", "0.0")),
2905
+ vmm_staging_buffer_gb=float(preset_env("DDO_VMM_STAGING_BUFFER_GB", "0.625")),
2906
+ vmm_windows_file_read_chunk_mb=int(preset_env("DDO_VMM_WINDOWS_FILE_READ_CHUNK_MB", "2")),
2907
+ vmm_virtual_host_transport=preset_bool("DDO_VMM_VIRTUAL_HOST_TRANSPORT", "0"),
2908
+ vmm_native_transport=preset_bool("DDO_VMM_NATIVE_TRANSPORT", "0"),
2909
+ vmm_source_cache_gb=float(preset_env("DDO_VMM_SOURCE_CACHE_GB", "0")),
2910
+ vmm_source_registered_gb=float(preset_env("DDO_VMM_SOURCE_REGISTERED_GB", "0")),
2911
+ vmm_module_pattern=preset_env("DDO_VMM_MODULE_PATTERN", r".*"),
2912
+ vmm_page_mb=int(preset_env("DDO_VMM_PAGE_MB", "0")),
2913
+ vmm_dxgi_local_headroom_gb=float(preset_env("DDO_VMM_DXGI_LOCAL_HEADROOM_GB", "0")),
2914
+ vmm_dxgi_shared_headroom_gb=float(preset_env("DDO_VMM_DXGI_SHARED_HEADROOM_GB", "0")),
2915
+ vmm_dxgi_system_headroom_gb=float(preset_env("DDO_VMM_DXGI_SYSTEM_HEADROOM_GB", "0")),
2916
+ vmm_host_cache_gb=float(preset_env("DDO_VMM_HOST_CACHE_GB", "0")),
2917
+ vmm_native_source_cache_slot_mb=int(preset_env("DDO_VMM_NATIVE_SOURCE_CACHE_SLOT_MB", "0")),
2918
+ vmm_native_source_cache_slots=int(preset_env("DDO_VMM_NATIVE_SOURCE_CACHE_SLOTS", "0")),
2919
+ vmm_pin_source_weights=preset_bool("DDO_VMM_PIN_SOURCE_WEIGHTS", "0"),
2920
+ vmm_fault_fallback=preset_bool("DDO_VMM_FAULT_FALLBACK", "0"),
2921
+ pin_cpu_memory=effective_pin_cpu_memory,
2922
+ allow_pin_memory_fallback=allow_pin_memory_fallback,
2923
+ pin_cpu_workers=int(preset_env("DDO_PIN_CPU_WORKERS", "4")),
2924
+ cache_plan=preset_bool("DDO_CACHE_PLAN", "1"),
2925
+ cache_pinned_weights=preset_bool("DDO_CACHE_PINNED_WEIGHTS", "0"),
2926
+ pinned_weight_cache_namespace=preset_env("DDO_PINNED_WEIGHT_CACHE_NAMESPACE", ""),
2927
+ auto_budget_policy=preset_env("DDO_AUTO_BUDGET_POLICY", "off").lower(),
2928
+ max_resident_module_budget_gb=float(
2929
+ preset_env("DDO_MAX_RESIDENT_MODULE_BUDGET_GB", "6.0")
2930
+ ),
2931
+ auto_vram_headroom_gb=float(preset_env("DDO_AUTO_VRAM_HEADROOM_GB", "0.0")),
2932
+ profile_vram_headroom_gb=float(preset_env("DDO_PROFILE_VRAM_HEADROOM_GB", "1.0")),
2933
+ auto_full_pin_min_model_to_vram_ratio=float(
2934
+ preset_env("DDO_AUTO_FULL_PIN_MIN_MODEL_TO_VRAM_RATIO", "4.0")
2935
+ ),
2936
+ max_pin_weight_budget_gb=float(preset_env("DDO_MAX_PIN_WEIGHT_BUDGET_GB", "0.0")),
2937
+ available_system_ram_gb=available_system_ram_gb,
2938
+ system_ram_headroom_gb=float(preset_env("DDO_SYSTEM_RAM_HEADROOM_GB", "6.0")),
2939
+ pin_weight_budget_gb=float(preset_env("DDO_PIN_WEIGHT_BUDGET_GB", "0.0")),
2940
+ pin_weight_budget_ratio=float(preset_env("DDO_PIN_WEIGHT_BUDGET_RATIO", "0.0")),
2941
+ pin_weight_selection=preset_env("DDO_PIN_WEIGHT_SELECTION", "spread").lower(),
2942
+ resident_module_budget_gb=float(preset_env("DDO_RESIDENT_MODULE_BUDGET_GB", "0.0")),
2943
+ resident_module_patterns=_parse_pattern_list_value(preset_env("DDO_RESIDENT_MODULE_PATTERNS", "")),
2944
+ resident_module_selection=preset_env("DDO_RESIDENT_MODULE_SELECTION", "spread").lower(),
2945
+ load_safetensors_backend=load_safetensors_backend,
2946
+ verbose=preset_bool("DDO_VERBOSE", "0"),
2947
+ show_profile=preset_bool("DDO_SHOW_PROFILE", "0"),
2948
+ )
2949
+ return DynamicOffloadSettings(
2950
+ requested_preset=requested_preset,
2951
+ effective_preset=effective_preset,
2952
+ enabled=plan or execution_mode != "plan",
2953
+ plan=plan,
2954
+ config=config,
2955
+ requested_pin_cpu_memory=requested_pin_cpu_memory,
2956
+ effective_pin_cpu_memory=effective_pin_cpu_memory,
2957
+ disable_pin_on_wsl=disable_pin_on_wsl,
2958
+ running_on_wsl=is_wsl,
2959
+ component_policies=component_policies or {},
2960
+ )
2961
+
2962
+
2963
+ def apply_dynamic_offload(module: nn.Module, config: DynamicOffloadConfig | None = None) -> DynamicOffloadHook:
2964
+ config = config or DynamicOffloadConfig()
2965
+ if config.vmm_float8_weight_only:
2966
+ from .float8_loading import validate_float8_native_config
2967
+
2968
+ validate_float8_native_config(config)
2969
+ if not getattr(module, "_ddo_float8_weight_only_loaded", False):
2970
+ raise ValueError("FP8 native runtime requires the explicit physical-source loader")
2971
+ registry = HookRegistry.check_if_exists_or_initialize(module)
2972
+ existing_hook = registry.get_hook(_DYNAMIC_OFFLOAD_HOOK)
2973
+ if existing_hook is not None:
2974
+ registry.remove_hook(_DYNAMIC_OFFLOAD_HOOK)
2975
+ hook = DynamicOffloadHook(config)
2976
+ registry.register_hook(hook, _DYNAMIC_OFFLOAD_HOOK)
2977
+ return hook
2978
+
2979
+
2980
+ def _component_prefix(component: str) -> str:
2981
+ return re.sub(r"[^A-Z0-9]+", "_", component.upper()).strip("_") or "MODEL"
2982
+
2983
+
2984
+ def _component_policy(settings: DynamicOffloadSettings, component: str) -> Mapping[str, Any]:
2985
+ prefix = _component_prefix(component)
2986
+ candidates = (
2987
+ component,
2988
+ component.lower(),
2989
+ prefix,
2990
+ prefix.lower(),
2991
+ )
2992
+ for candidate in candidates:
2993
+ policy = settings.component_policies.get(candidate)
2994
+ if policy is not None:
2995
+ return policy
2996
+ return {}
2997
+
2998
+
2999
+ def _policy_value(policy: Mapping[str, Any], name: str) -> Any:
3000
+ key = name.lower()
3001
+ candidates = (
3002
+ key,
3003
+ name,
3004
+ name.upper(),
3005
+ key.replace("_", "-"),
3006
+ )
3007
+ for candidate in candidates:
3008
+ if candidate in policy:
3009
+ return policy[candidate]
3010
+ return None
3011
+
3012
+
3013
+ def _component_preset_value(
3014
+ settings: DynamicOffloadSettings,
3015
+ component: str,
3016
+ name: str,
3017
+ default: str = "",
3018
+ environ: Mapping[str, str] | None = None,
3019
+ *,
3020
+ allow_preset_policy: bool = True,
3021
+ ) -> str:
3022
+ policy_item = _policy_value(_component_policy(settings, component), name)
3023
+ if policy_item is not None:
3024
+ return str(policy_item)
3025
+
3026
+ prefix = _component_prefix(component)
3027
+ for candidate in (f"DDO_{prefix}_{name}", f"DDO_RUNNER_{prefix}_{name}"):
3028
+ value = settings.preset_value(candidate, "", environ)
3029
+ if value != "":
3030
+ return value
3031
+ if allow_preset_policy:
3032
+ preset_policy = _PRESET_COMPONENT_POLICIES.get(settings.effective_preset, {}).get(component.lower(), {})
3033
+ return str(preset_policy.get(name, default))
3034
+ return default
3035
+
3036
+
3037
+ def _component_preset_bool(
3038
+ settings: DynamicOffloadSettings,
3039
+ component: str,
3040
+ name: str,
3041
+ default: str = "0",
3042
+ environ: Mapping[str, str] | None = None,
3043
+ ) -> bool:
3044
+ return _parse_bool_value(_component_preset_value(settings, component, name, default, environ))
3045
+
3046
+
3047
+ def enable_diffusers_group_offload(
3048
+ module: nn.Module,
3049
+ *,
3050
+ onload_device: str | torch.device = "cuda:0",
3051
+ offload_device: str | torch.device = "cpu",
3052
+ offload_type: str = "leaf_level",
3053
+ use_stream: bool = True,
3054
+ record_stream: bool = False,
3055
+ low_cpu_mem_usage: bool = True,
3056
+ num_blocks_per_group: int = 1,
3057
+ apply_hook: bool = True,
3058
+ record_event: Any | None = None,
3059
+ event_name: str = "setup_diffusers_group_offload",
3060
+ ) -> DiffusersGroupOffloadResult:
3061
+ """Apply the official Diffusers group offload helper with DDO-style reporting."""
3062
+ start = time.perf_counter()
3063
+ kwargs: dict[str, Any] = {
3064
+ "onload_device": torch.device(onload_device),
3065
+ "offload_device": torch.device(offload_device),
3066
+ "offload_type": offload_type,
3067
+ "use_stream": use_stream,
3068
+ "record_stream": record_stream,
3069
+ "low_cpu_mem_usage": low_cpu_mem_usage,
3070
+ }
3071
+ if offload_type == "block_level":
3072
+ kwargs["num_blocks_per_group"] = num_blocks_per_group
3073
+
3074
+ if apply_hook:
3075
+ from diffusers.hooks import apply_group_offloading
3076
+
3077
+ apply_group_offloading(module, **kwargs)
3078
+
3079
+ event_payload = {
3080
+ "offload_type": offload_type,
3081
+ "use_stream": use_stream,
3082
+ "record_stream": record_stream,
3083
+ "low_cpu_mem_usage": low_cpu_mem_usage,
3084
+ }
3085
+ if offload_type == "block_level":
3086
+ event_payload["num_blocks_per_group"] = num_blocks_per_group
3087
+
3088
+ if record_event is not None:
3089
+ record_event(event_name, time.perf_counter() - start, **event_payload)
3090
+
3091
+ return DiffusersGroupOffloadResult(module=module, event_payload=event_payload)
3092
+
3093
+
3094
+ def enable_offload(
3095
+ module: nn.Module,
3096
+ *,
3097
+ settings: DynamicOffloadSettings | None = None,
3098
+ config: DynamicOffloadConfig | None = None,
3099
+ component: str = "model",
3100
+ preset: str = "auto",
3101
+ route: str | None = None,
3102
+ group_offload: bool | None = None,
3103
+ dynamic_offload: bool | None = None,
3104
+ offload_type: str | None = None,
3105
+ use_stream: bool | None = None,
3106
+ record_stream: bool | None = None,
3107
+ group_low_cpu_mem_usage: bool | None = None,
3108
+ num_blocks_per_group: int | None = None,
3109
+ execution_device: str | torch.device = "cuda:0",
3110
+ offload_device: str | torch.device = "cpu",
3111
+ low_cpu_mem_usage: bool = True,
3112
+ running_on_wsl: bool | None = None,
3113
+ environ: Mapping[str, str] | None = None,
3114
+ use_environment: bool = True,
3115
+ apply_hook: bool = True,
3116
+ record_event: Any | None = None,
3117
+ dynamic_event_name: str | None = None,
3118
+ group_event_name: str | None = None,
3119
+ **config_overrides: Any,
3120
+ ) -> DynamicOffloadApplyResult:
3121
+ """Enable the offload route requested by DDO settings for one component."""
3122
+ if not use_environment:
3123
+ environ = {}
3124
+ if settings is None:
3125
+ settings = load_dynamic_offload_settings_from_env(
3126
+ execution_device=execution_device,
3127
+ offload_device=offload_device,
3128
+ running_on_wsl=running_on_wsl,
3129
+ environ=environ if use_environment else {},
3130
+ default_preset=preset,
3131
+ )
3132
+
3133
+ explicit_runtime = config is not None or bool(config_overrides) or group_offload is not None or dynamic_offload is not None
3134
+ route_value = route or _component_preset_value(
3135
+ settings, component, "ROUTE", "auto", environ, allow_preset_policy=not explicit_runtime
3136
+ )
3137
+ route_value = route_value.strip().lower()
3138
+ if route_value in {"diffusers", "diffusers_group", "group", "group_offload"}:
3139
+ route_value = "diffusers_group_offload"
3140
+ elif route_value in {"dynamic", "ddo"}:
3141
+ route_value = "dynamic_offload"
3142
+ elif route_value in {"cuda", "standard", "none", "off"}:
3143
+ route_value = "none"
3144
+
3145
+ group_enabled = (
3146
+ group_offload
3147
+ if group_offload is not None
3148
+ else _component_preset_bool(settings, component, "GROUP_OFFLOAD", "0", environ)
3149
+ )
3150
+ dynamic_setting = _component_preset_value(settings, component, "DYNAMIC_OFFLOAD", "", environ)
3151
+ dynamic_enabled = (
3152
+ dynamic_offload
3153
+ if dynamic_offload is not None
3154
+ else (_parse_bool_value(dynamic_setting) if dynamic_setting != "" else settings.enabled)
3155
+ )
3156
+ quantized_backend_payload = detect_quantized_backend_modules(module)
3157
+
3158
+ if route_value == "linear_convolution":
3159
+ if quantized_backend_payload:
3160
+ raise ValueError("Convolution offload requires dense, non-quantized parameters")
3161
+ config = config or DynamicOffloadConfig(
3162
+ execution_device=execution_device,
3163
+ offload_device=offload_device,
3164
+ execution_mode="linear_runtime",
3165
+ linear_convolution_offload=True,
3166
+ pin_cpu_memory=True,
3167
+ )
3168
+ if not config.linear_convolution_offload:
3169
+ raise ValueError("linear_convolution route requires linear_convolution_offload=True in an explicit config")
3170
+ route_value = "dynamic_offload"
3171
+
3172
+ if route_value == "auto":
3173
+ if group_enabled or (quantized_backend_payload and dynamic_enabled):
3174
+ route_value = "diffusers_group_offload"
3175
+ elif dynamic_enabled:
3176
+ route_value = "dynamic_offload"
3177
+ else:
3178
+ route_value = "none"
3179
+
3180
+ if route_value != "dynamic_offload" and config_overrides.get("build_profile", (config or settings.config).build_profile):
3181
+ raise ValueError("Profile calibration requires the dynamic_offload route.")
3182
+
3183
+ if route_value == "diffusers_group_offload":
3184
+ group_use_stream = (
3185
+ use_stream
3186
+ if use_stream is not None
3187
+ else _component_preset_bool(settings, component, "OFFLOAD_STREAM", "1", environ)
3188
+ )
3189
+ group_record_stream = (
3190
+ record_stream
3191
+ if record_stream is not None
3192
+ else _component_preset_bool(settings, component, "OFFLOAD_RECORD_STREAM", "0", environ)
3193
+ )
3194
+ if settings.running_on_wsl and settings.disable_pin_on_wsl and group_use_stream:
3195
+ group_use_stream = False
3196
+ group_record_stream = False
3197
+
3198
+ resolved_offload_type = offload_type or _component_preset_value(settings, component, "OFFLOAD_TYPE", "leaf_level", environ)
3199
+ resolved_low_cpu_mem_usage = (
3200
+ group_low_cpu_mem_usage
3201
+ if group_low_cpu_mem_usage is not None
3202
+ else _component_preset_bool(
3203
+ settings,
3204
+ component,
3205
+ "OFFLOAD_LOW_CPU_MEM_USAGE",
3206
+ "1" if low_cpu_mem_usage else "0",
3207
+ environ,
3208
+ )
3209
+ )
3210
+ resolved_num_blocks = (
3211
+ num_blocks_per_group
3212
+ if num_blocks_per_group is not None
3213
+ else int(_component_preset_value(settings, component, "NUM_BLOCKS_PER_GROUP", "1", environ))
3214
+ )
3215
+ result = enable_diffusers_group_offload(
3216
+ module,
3217
+ onload_device=execution_device,
3218
+ offload_device=offload_device,
3219
+ offload_type=resolved_offload_type,
3220
+ use_stream=group_use_stream,
3221
+ record_stream=group_record_stream,
3222
+ low_cpu_mem_usage=resolved_low_cpu_mem_usage,
3223
+ num_blocks_per_group=resolved_num_blocks,
3224
+ apply_hook=apply_hook,
3225
+ record_event=record_event,
3226
+ event_name=group_event_name or f"setup_{component}_group_offload",
3227
+ )
3228
+ if quantized_backend_payload:
3229
+ result.event_payload["quantized_backend"] = quantized_backend_payload
3230
+ return DynamicOffloadApplyResult(
3231
+ module=result.module,
3232
+ hook=None,
3233
+ settings=settings,
3234
+ should_move_to_execution_device=False,
3235
+ event_payload=result.event_payload,
3236
+ route="diffusers_group_offload",
3237
+ )
3238
+
3239
+ if route_value == "dynamic_offload":
3240
+ result = enable_dynamic_offload(
3241
+ module,
3242
+ component=component,
3243
+ settings=settings,
3244
+ config=config,
3245
+ execution_device=execution_device,
3246
+ offload_device=offload_device,
3247
+ apply_hook=apply_hook,
3248
+ record_event=record_event,
3249
+ event_name=dynamic_event_name or f"setup_{component}_dynamic_offload",
3250
+ **config_overrides,
3251
+ )
3252
+ result.route = "dynamic_offload"
3253
+ return result
3254
+
3255
+ if route_value != "none":
3256
+ raise ValueError(
3257
+ f"Invalid offload route {route_value!r}. "
3258
+ "Valid values: auto, dynamic_offload, linear_convolution, diffusers_group_offload, none."
3259
+ )
3260
+
3261
+ event_payload: dict[str, Any] = {}
3262
+ should_move = True
3263
+ if apply_hook:
3264
+ move_start = time.perf_counter()
3265
+ module.to(execution_device)
3266
+ move_seconds = time.perf_counter() - move_start
3267
+ should_move = False
3268
+ event_payload["unmanaged_module_moved_to_execution_device"] = str(execution_device)
3269
+ if record_event is not None:
3270
+ record_event(
3271
+ f"move_{component}_to_execution_device",
3272
+ move_seconds,
3273
+ route="none",
3274
+ execution_device=str(execution_device),
3275
+ )
3276
+
3277
+ return DynamicOffloadApplyResult(
3278
+ module=module,
3279
+ hook=None,
3280
+ settings=settings,
3281
+ should_move_to_execution_device=should_move,
3282
+ event_payload=event_payload,
3283
+ route="none",
3284
+ )
3285
+
3286
+
3287
+ def enable_pipeline_offload(
3288
+ pipeline: Any,
3289
+ *,
3290
+ settings: DynamicOffloadSettings | None = None,
3291
+ components: Mapping[str, nn.Module] | tuple[str, ...] | list[str] | None = None,
3292
+ preset: str = "auto",
3293
+ execution_device: str | torch.device = "cuda:0",
3294
+ offload_device: str | torch.device = "cpu",
3295
+ low_cpu_mem_usage: bool = True,
3296
+ running_on_wsl: bool | None = None,
3297
+ environ: Mapping[str, str] | None = None,
3298
+ use_environment: bool = True,
3299
+ apply_hook: bool = True,
3300
+ record_event: Any | None = None,
3301
+ **config_overrides: Any,
3302
+ ) -> dict[str, DynamicOffloadApplyResult]:
3303
+ """Apply DDO routing to modules exposed by a Diffusers-style pipeline.
3304
+
3305
+ Each component is resolved through `enable_offload(...)`, so global presets,
3306
+ component policies, environment overrides, and quantized-backend compatibility
3307
+ all follow the same path. If a component resolves to the unmanaged `none`
3308
+ route, this high-level helper moves it to the execution device automatically.
3309
+ """
3310
+ if settings is None:
3311
+ settings = load_dynamic_offload_settings_from_env(
3312
+ execution_device=execution_device,
3313
+ offload_device=offload_device,
3314
+ running_on_wsl=running_on_wsl,
3315
+ environ=environ if use_environment else {},
3316
+ default_preset=preset,
3317
+ )
3318
+
3319
+ if isinstance(components, Mapping):
3320
+ selected_components = components.items()
3321
+ else:
3322
+ component_names: tuple[str, ...]
3323
+ if components is not None:
3324
+ component_names = tuple(components)
3325
+ else:
3326
+ pipeline_components = getattr(pipeline, "components", None)
3327
+ if isinstance(pipeline_components, Mapping):
3328
+ component_names = tuple(pipeline_components)
3329
+ else:
3330
+ component_names = (
3331
+ "text_encoder",
3332
+ "text_encoder_2",
3333
+ "transformer",
3334
+ "unet",
3335
+ "vae",
3336
+ )
3337
+
3338
+ selected_components = (
3339
+ (name, getattr(pipeline, name))
3340
+ for name in component_names
3341
+ if isinstance(getattr(pipeline, name, None), nn.Module)
3342
+ )
3343
+
3344
+ results: dict[str, DynamicOffloadApplyResult] = {}
3345
+ for component_name, component_module in selected_components:
3346
+ if not isinstance(component_module, nn.Module):
3347
+ continue
3348
+ result = enable_offload(
3349
+ component_module,
3350
+ settings=settings,
3351
+ component=component_name,
3352
+ execution_device=execution_device,
3353
+ offload_device=offload_device,
3354
+ low_cpu_mem_usage=low_cpu_mem_usage,
3355
+ environ=environ if use_environment else {},
3356
+ apply_hook=apply_hook,
3357
+ record_event=record_event,
3358
+ **config_overrides,
3359
+ )
3360
+ if apply_hook and result.should_move_to_execution_device:
3361
+ result.module.to(execution_device)
3362
+ result.should_move_to_execution_device = False
3363
+ result.event_payload["unmanaged_module_moved_to_execution_device"] = str(execution_device)
3364
+ results[component_name] = result
3365
+ return results
3366
+
3367
+
3368
+ def enable_dynamic_offload(
3369
+ module: nn.Module,
3370
+ *,
3371
+ component: str = "model",
3372
+ settings: DynamicOffloadSettings | None = None,
3373
+ config: DynamicOffloadConfig | None = None,
3374
+ preset: str = "auto",
3375
+ execution_device: str | torch.device = "cuda:0",
3376
+ offload_device: str | torch.device = "cpu",
3377
+ target_module_classes: tuple[type[nn.Module], ...] = _DEFAULT_TARGET_MODULE_CLASSES,
3378
+ skip_modules_pattern: tuple[str, ...] = (),
3379
+ always_resident_modules_pattern: tuple[str, ...] | None = None,
3380
+ running_on_wsl: bool | None = None,
3381
+ environ: Mapping[str, str] | None = None,
3382
+ use_environment: bool = True,
3383
+ apply_hook: bool = True,
3384
+ record_event: Any | None = None,
3385
+ event_name: str = "setup_dynamic_offload",
3386
+ **config_overrides: Any,
3387
+ ) -> DynamicOffloadApplyResult:
3388
+ """Resolve DDO settings, optionally apply the hook, and return the prepared module.
3389
+
3390
+ This is the high-level, Diffusers-style entry point. Environment variables are
3391
+ read by default for CLI/runner use, while explicit keyword overrides always
3392
+ take precedence over preset and environment values.
3393
+ """
3394
+ start = time.perf_counter()
3395
+ if settings is None:
3396
+ settings = load_dynamic_offload_settings_from_env(
3397
+ execution_device=execution_device,
3398
+ offload_device=offload_device,
3399
+ target_module_classes=target_module_classes,
3400
+ skip_modules_pattern=skip_modules_pattern,
3401
+ always_resident_modules_pattern=always_resident_modules_pattern,
3402
+ running_on_wsl=running_on_wsl,
3403
+ environ=environ if use_environment else {},
3404
+ default_preset=preset,
3405
+ )
3406
+
3407
+ explicit_config = config is not None or bool(config_overrides)
3408
+ effective_config = config or settings.config
3409
+ if config_overrides:
3410
+ unknown = sorted(set(config_overrides) - set(DynamicOffloadConfig.__dataclass_fields__))
3411
+ if unknown:
3412
+ raise TypeError(f"Unknown DynamicOffloadConfig override(s): {', '.join(unknown)}")
3413
+ effective_config = replace(effective_config, **config_overrides)
3414
+
3415
+ # An SDNQ layer is often also an ``nn.Linear`` subclass. It must not
3416
+ # enter the dense functional runtime: that path materializes its weight as
3417
+ # BF16 and loses the backend-owned forward. Switch before profile setup so
3418
+ # profile calibration and normal execution share the SDNQ runtime.
3419
+ quantized_backend_payload = detect_quantized_backend_modules(module)
3420
+ if quantized_backend_payload and effective_config.execution_mode.lower() == "linear_runtime":
3421
+ effective_config = replace(effective_config, execution_mode="sdnq_runtime")
3422
+
3423
+ if effective_config is not settings.config:
3424
+ settings = replace(
3425
+ settings,
3426
+ config=effective_config,
3427
+ enabled=explicit_config or settings.plan or effective_config.execution_mode.lower() != "plan",
3428
+ effective_pin_cpu_memory=effective_config.pin_cpu_memory,
3429
+ )
3430
+
3431
+ from .profiles import _NamedProfile
3432
+
3433
+ profile = _NamedProfile(module, effective_config, component=component)
3434
+ effective_config = profile.prepare()
3435
+ if effective_config is not settings.config:
3436
+ settings = replace(settings, config=effective_config)
3437
+
3438
+ hook = None
3439
+ event_payload: dict[str, Any] = {}
3440
+ quantized_backend_payload = detect_quantized_backend_modules(module)
3441
+ if apply_hook and settings.enabled:
3442
+ hook = apply_dynamic_offload(module, effective_config)
3443
+ profile.attach_hook(hook)
3444
+ event_payload = build_dynamic_offload_event_payload(settings, hook.state, effective_config)
3445
+ if quantized_backend_payload:
3446
+ event_payload["quantized_backend"] = quantized_backend_payload
3447
+
3448
+ elapsed = time.perf_counter() - start
3449
+ if record_event is not None:
3450
+ record_event(event_name, elapsed, **event_payload)
3451
+
3452
+ return DynamicOffloadApplyResult(
3453
+ module=module,
3454
+ hook=hook,
3455
+ settings=settings,
3456
+ should_move_to_execution_device=hook is None or effective_config.execution_mode.lower() == "plan",
3457
+ event_payload=event_payload,
3458
+ _profile=profile,
3459
+ )
3460
+
3461
+
3462
+ @contextlib.contextmanager
3463
+ def _temporary_safetensors_backend(backend: str):
3464
+ """Apply an optional backend and report the actual local files opened."""
3465
+ opened_files: set[Path] = set()
3466
+ backend = backend.strip().lower()
3467
+ if backend and backend not in {"mmap", "pread"}:
3468
+ raise ValueError("DynamicOffloadConfig.load_safetensors_backend must be '', 'mmap', or 'pread'")
3469
+
3470
+ try:
3471
+ import safetensors
3472
+ import safetensors.torch
3473
+ except ImportError:
3474
+ yield opened_files
3475
+ return
3476
+
3477
+ original_safe_open = safetensors.safe_open
3478
+ original_torch_load_file = safetensors.torch.load_file
3479
+
3480
+ def safe_open_with_backend(filename, framework, device=None, **kwargs):
3481
+ with contextlib.suppress(OSError, TypeError):
3482
+ opened_files.add(Path(filename).resolve())
3483
+ if backend:
3484
+ kwargs.setdefault("backend", backend)
3485
+ if device is None:
3486
+ return original_safe_open(filename, framework=framework, **kwargs)
3487
+ return original_safe_open(filename, framework=framework, device=device, **kwargs)
3488
+
3489
+ def torch_load_file_with_backend(filename, device="cpu", **kwargs):
3490
+ with contextlib.suppress(OSError, TypeError):
3491
+ opened_files.add(Path(filename).resolve())
3492
+ if backend:
3493
+ kwargs.setdefault("backend", backend)
3494
+ return original_torch_load_file(filename, device=device, **kwargs)
3495
+
3496
+ safetensors.safe_open = safe_open_with_backend
3497
+ safetensors.torch.load_file = torch_load_file_with_backend
3498
+
3499
+ patched_modules: list[tuple[Any, str, Any]] = []
3500
+ for module_name in (
3501
+ "accelerate.utils.modeling",
3502
+ "transformers.modeling_utils",
3503
+ "diffusers.models.model_loading_utils",
3504
+ ):
3505
+ try:
3506
+ imported_module = __import__(module_name, fromlist=["_"])
3507
+ except ImportError:
3508
+ continue
3509
+ if getattr(imported_module, "safe_open", None) is original_safe_open:
3510
+ imported_module.safe_open = safe_open_with_backend
3511
+ patched_modules.append((imported_module, "safe_open", original_safe_open))
3512
+ if getattr(imported_module, "safe_load_file", None) is original_torch_load_file:
3513
+ imported_module.safe_load_file = torch_load_file_with_backend
3514
+ patched_modules.append((imported_module, "safe_load_file", original_torch_load_file))
3515
+
3516
+ try:
3517
+ yield opened_files
3518
+ finally:
3519
+ for imported_module, attr_name, original_value in reversed(patched_modules):
3520
+ setattr(imported_module, attr_name, original_value)
3521
+ safetensors.safe_open = original_safe_open
3522
+ safetensors.torch.load_file = original_torch_load_file
3523
+
3524
+
3525
+ def _safetensor_file_slices(paths: list[Path], *, diagnostics=None) -> dict[str, Any]:
3526
+ """Read local safetensors headers without materializing any tensor payload."""
3527
+ from .vmm_weight_store import SafetensorFileSlice
3528
+
3529
+ result: dict[str, SafetensorFileSlice] = {}
3530
+ ambiguous = set()
3531
+ diagnostics = diagnostics if diagnostics is not None else {}
3532
+ diagnostics.update(invalid_files=0, invalid_entries=0, ambiguous_key_count=0)
3533
+ for checkpoint in paths:
3534
+ if checkpoint.suffix != ".safetensors" or not checkpoint.is_file():
3535
+ continue
3536
+ try:
3537
+ file_size = checkpoint.stat().st_size
3538
+ with checkpoint.open("rb") as source:
3539
+ header_size = int.from_bytes(source.read(8), "little")
3540
+ if header_size <= 0 or header_size > min(file_size - 8, 100 * 1024**2):
3541
+ diagnostics["invalid_files"] += 1
3542
+ continue
3543
+ header = json.loads(source.read(header_size))
3544
+ data_start = 8 + header_size
3545
+ except (OSError, ValueError, json.JSONDecodeError):
3546
+ diagnostics["invalid_files"] += 1
3547
+ continue
3548
+ if not isinstance(header, dict):
3549
+ diagnostics["invalid_files"] += 1
3550
+ continue
3551
+ for tensor_name, entry in header.items():
3552
+ if tensor_name == "__metadata__" or not isinstance(entry, dict):
3553
+ if tensor_name != "__metadata__":
3554
+ diagnostics["invalid_entries"] += 1
3555
+ continue
3556
+ offsets = entry.get("data_offsets")
3557
+ if not isinstance(offsets, list) or len(offsets) != 2:
3558
+ diagnostics["invalid_entries"] += 1
3559
+ continue
3560
+ start, end = offsets
3561
+ if type(start) is not int or type(end) is not int or start < 0 or end < start or data_start + end > file_size:
3562
+ diagnostics["invalid_entries"] += 1
3563
+ continue
3564
+ shape, dtype = entry.get("shape"), entry.get("dtype")
3565
+ if not isinstance(shape, list) or any(type(size) is not int or size < 0 for size in shape) or not isinstance(dtype, str):
3566
+ diagnostics["invalid_entries"] += 1
3567
+ continue
3568
+ descriptor = SafetensorFileSlice(checkpoint, data_start + start, end - start, tuple(shape), dtype)
3569
+ if tensor_name in ambiguous:
3570
+ continue
3571
+ if tensor_name in result and result[tensor_name] != descriptor:
3572
+ ambiguous.add(tensor_name)
3573
+ del result[tensor_name]
3574
+ continue
3575
+ result[tensor_name] = descriptor
3576
+ # A duplicate checkpoint key may also alias a different parameter name.
3577
+ # Do not publish partial provenance from an ambiguous shard set.
3578
+ diagnostics["ambiguous_key_count"] = len(ambiguous)
3579
+ return {} if ambiguous else result
3580
+
3581
+
3582
+ def _attach_safetensor_file_slices(module: nn.Module, paths: list[Path], *, key_mapping=None) -> tuple[int, int]:
3583
+ """Associate loaded parameter storage with its original safetensors bytes.
3584
+
3585
+ This metadata is intentionally private to the optional VMM runtime. It
3586
+ leaves Diffusers/Transformers loader semantics and normal CPU tensors
3587
+ unchanged.
3588
+ """
3589
+ from .weight_source_metadata import associate_source_metadata
3590
+
3591
+ if getattr(module, "_ddo_safetensor_slices", None) is not None:
3592
+ raise RuntimeError("Source descriptors are already associated; close their lifecycle before rebinding")
3593
+ diagnostics = {}
3594
+ available = _safetensor_file_slices(paths, diagnostics=diagnostics)
3595
+ if not available:
3596
+ if paths:
3597
+ module._ddo_safetensor_slice_summary = {
3598
+ "bound": 0, "available": 0, "resolver": "no_valid_source_metadata",
3599
+ "header": diagnostics, "rejected_storage_groups": 0,
3600
+ "missing_storage_groups": 0, "ineligible_parameter_aliases": 0,
3601
+ }
3602
+ return 0, 0
3603
+ registry, summary = associate_source_metadata(module, available, key_mapping=key_mapping)
3604
+ summary["header"] = diagnostics
3605
+ bound = registry.descriptor_count
3606
+ module._ddo_safetensor_slice_summary = summary
3607
+ if bound:
3608
+ module._ddo_safetensor_slices = registry
3609
+ return bound, len(available)
3610
+
3611
+
3612
+ def from_pretrained_with_dynamic_offload(
3613
+ pretrained_model_name_or_path: str | os.PathLike[str],
3614
+ *,
3615
+ model_loader: Any | None = None,
3616
+ dynamic_offload_config: DynamicOffloadConfig | None = None,
3617
+ apply_dynamic: bool = False,
3618
+ profile_name: str | None = None,
3619
+ build_profile: bool | None = None,
3620
+ **from_pretrained_kwargs: Any,
3621
+ ) -> DynamicOffloadLoadResult:
3622
+ if model_loader is None:
3623
+ from diffusers import AutoModel
3624
+
3625
+ model_loader = AutoModel
3626
+ from_pretrained = getattr(model_loader, "from_pretrained", model_loader)
3627
+ config = dynamic_offload_config or DynamicOffloadConfig()
3628
+ if profile_name is not None:
3629
+ config = replace(config, profile_name=profile_name)
3630
+ if build_profile is not None:
3631
+ config = replace(config, build_profile=build_profile)
3632
+ if (config.profile_name or config.build_profile) and not apply_dynamic:
3633
+ raise ValueError("Pass profile options to enable_offload after staged loading, or set apply_dynamic=True.")
3634
+ if config.vmm_float8_weight_only:
3635
+ from .float8_loading import load_float8_component_cpu, validate_float8_native_config
3636
+
3637
+ validate_float8_native_config(config)
3638
+ allowed = {"subfolder", "torch_dtype", "low_cpu_mem_usage", "local_files_only"}
3639
+ if set(from_pretrained_kwargs) - allowed:
3640
+ raise ValueError("FP8 native loading only supports local component loading without device maps or key remapping")
3641
+ if from_pretrained_kwargs.get("torch_dtype", torch.bfloat16) != torch.bfloat16:
3642
+ raise ValueError("FP8 weight-only requires logical BF16")
3643
+ checkpoint = Path(pretrained_model_name_or_path)
3644
+ if from_pretrained_kwargs.get("subfolder"):
3645
+ checkpoint /= from_pretrained_kwargs["subfolder"]
3646
+ module = load_float8_component_cpu(checkpoint, model_loader)
3647
+ opened_safetensor_files = []
3648
+ else:
3649
+ with _temporary_safetensors_backend(config.load_safetensors_backend) as opened_safetensor_files:
3650
+ module = from_pretrained(pretrained_model_name_or_path, **from_pretrained_kwargs)
3651
+ # Preserve only file offsets for a local checkpoint. Normal presets do
3652
+ # not consume this metadata; VMM can later refill its bounded pinned ring
3653
+ # directly from those file slices instead of copying materialized CPU
3654
+ # tensors into it.
3655
+ checkpoint_directory = Path(pretrained_model_name_or_path)
3656
+ subfolder = from_pretrained_kwargs.get("subfolder")
3657
+ if isinstance(subfolder, str) and subfolder:
3658
+ checkpoint_directory /= subfolder
3659
+ fallback_files = list(checkpoint_directory.glob("*.safetensors")) if checkpoint_directory.is_dir() else []
3660
+ source_files = list(opened_safetensor_files) or fallback_files
3661
+ if not config.vmm_float8_weight_only:
3662
+ _attach_safetensor_file_slices(module, source_files, key_mapping=from_pretrained_kwargs.get("key_mapping"))
3663
+ if not apply_dynamic:
3664
+ return DynamicOffloadLoadResult(module=module)
3665
+
3666
+ from .profiles import _NamedProfile
3667
+
3668
+ profile = _NamedProfile(module, config)
3669
+ config = profile.prepare()
3670
+ hook = apply_dynamic_offload(module, config)
3671
+ profile.attach_hook(hook)
3672
+ return DynamicOffloadLoadResult(
3673
+ module=module,
3674
+ hook=hook,
3675
+ should_move_to_execution_device=config.execution_mode.lower() == "plan",
3676
+ _profile=profile,
3677
+ )
3678
+
3679
+
3680
+ def remove_dynamic_offload(module: nn.Module, recurse: bool = True) -> None:
3681
+ if hasattr(module, "_diffusers_hook"):
3682
+ module._diffusers_hook.remove_hook(_DYNAMIC_OFFLOAD_HOOK, recurse=recurse)
3683
+
3684
+
3685
+ def get_dynamic_offload_state(module: nn.Module) -> DynamicOffloadState | None:
3686
+ if not hasattr(module, "_diffusers_hook"):
3687
+ return None
3688
+ hook = module._diffusers_hook.get_hook(_DYNAMIC_OFFLOAD_HOOK)
3689
+ if hook is None:
3690
+ return None
3691
+ return hook.state
3692
+
3693
+
3694
+ def clear_dynamic_offload_plan_cache() -> None:
3695
+ with _DYNAMIC_OFFLOAD_PLAN_CACHE_LOCK:
3696
+ _DYNAMIC_OFFLOAD_PLAN_CACHE.clear()
3697
+
3698
+
3699
+ def clear_dynamic_offload_pinned_tensor_cache() -> None:
3700
+ with _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE_LOCK:
3701
+ _DYNAMIC_OFFLOAD_PINNED_TENSOR_CACHE.clear()
3702
+
3703
+
3704
+ def build_dynamic_offload_plan(module: nn.Module, config: DynamicOffloadConfig) -> DynamicOffloadState:
3705
+ if not config.cache_plan:
3706
+ state = _build_dynamic_offload_plan_uncached(module, config)
3707
+ state.planner_decisions["plan_cache"] = "disabled"
3708
+ return state
3709
+
3710
+ cache_key = _dynamic_offload_plan_cache_key(module, config)
3711
+ with _DYNAMIC_OFFLOAD_PLAN_CACHE_LOCK:
3712
+ cached_state = _DYNAMIC_OFFLOAD_PLAN_CACHE.get(cache_key)
3713
+ if cached_state is not None:
3714
+ state = cached_state.clone_for_runtime()
3715
+ state.planner_decisions["plan_cache"] = "hit"
3716
+ return state
3717
+
3718
+ state = _build_dynamic_offload_plan_uncached(module, config)
3719
+ state.resolved_resident_module_patterns = [
3720
+ pattern.pattern for pattern in _resolve_resident_module_patterns(module, config)
3721
+ ]
3722
+ state.planner_decisions["plan_cache"] = "miss"
3723
+ with _DYNAMIC_OFFLOAD_PLAN_CACHE_LOCK:
3724
+ _DYNAMIC_OFFLOAD_PLAN_CACHE[cache_key] = state.clone_for_runtime()
3725
+ return state
3726
+
3727
+
3728
+ def _build_dynamic_offload_plan_uncached(module: nn.Module, config: DynamicOffloadConfig) -> DynamicOffloadState:
3729
+ state = DynamicOffloadState()
3730
+ skip_patterns = tuple(re.compile(pattern) for pattern in config.skip_modules_pattern)
3731
+ resident_patterns = tuple(re.compile(pattern) for pattern in config.always_resident_modules_pattern)
3732
+
3733
+ for module_name, submodule in module.named_modules():
3734
+ if module_name == "":
3735
+ continue
3736
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
3737
+ continue
3738
+ if not isinstance(submodule, config.target_module_classes):
3739
+ continue
3740
+
3741
+ state.module_count += 1
3742
+ module_resident = bool(resident_patterns and any(pattern.search(module_name) for pattern in resident_patterns))
3743
+ for tensor_name, tensor in _iter_local_tensors(submodule):
3744
+ placement = _classify_tensor(tensor, module_resident, config.small_tensor_threshold_bytes)
3745
+ entry = DynamicOffloadPlanEntry(
3746
+ module_name=module_name,
3747
+ module_type=submodule.__class__.__name__,
3748
+ tensor_name=tensor_name,
3749
+ shape=tuple(tensor.shape),
3750
+ dtype=str(tensor.dtype),
3751
+ device=str(tensor.device),
3752
+ bytes=_tensor_size_bytes(tensor),
3753
+ placement=placement,
3754
+ )
3755
+ state.entries.append(entry)
3756
+ state.total_bytes += entry.bytes
3757
+ state.bytes_by_placement[placement] = state.bytes_by_placement.get(placement, 0) + entry.bytes
3758
+
3759
+ return state
3760
+
3761
+
3762
+ def _dynamic_offload_plan_cache_key(module: nn.Module, config: DynamicOffloadConfig) -> tuple[Any, ...]:
3763
+ return (
3764
+ module.__class__.__module__,
3765
+ module.__class__.__qualname__,
3766
+ tuple(cls.__module__ + "." + cls.__qualname__ for cls in config.target_module_classes),
3767
+ tuple(config.skip_modules_pattern),
3768
+ tuple(config.always_resident_modules_pattern),
3769
+ tuple(config.resident_module_patterns),
3770
+ int(config.small_tensor_threshold_bytes),
3771
+ _dynamic_offload_plan_structure_signature(module, config),
3772
+ )
3773
+
3774
+
3775
+ def _dynamic_offload_plan_structure_signature(
3776
+ module: nn.Module,
3777
+ config: DynamicOffloadConfig,
3778
+ ) -> tuple[tuple[Any, ...], ...]:
3779
+ skip_patterns = tuple(re.compile(pattern) for pattern in config.skip_modules_pattern)
3780
+ signature: list[tuple[Any, ...]] = []
3781
+ for module_name, submodule in module.named_modules():
3782
+ if module_name == "":
3783
+ continue
3784
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
3785
+ continue
3786
+ if not isinstance(submodule, config.target_module_classes):
3787
+ continue
3788
+ tensor_signature = tuple(
3789
+ (
3790
+ tensor_name,
3791
+ tuple(tensor.shape),
3792
+ str(tensor.dtype),
3793
+ str(tensor.device),
3794
+ tensor.numel(),
3795
+ tensor.element_size(),
3796
+ )
3797
+ for tensor_name, tensor in _iter_local_tensors(submodule)
3798
+ )
3799
+ signature.append(
3800
+ (
3801
+ module_name,
3802
+ submodule.__class__.__module__,
3803
+ submodule.__class__.__qualname__,
3804
+ tensor_signature,
3805
+ )
3806
+ )
3807
+ return tuple(signature)
3808
+
3809
+
3810
+ def _iter_local_tensors(module: nn.Module):
3811
+ for name, parameter in module.named_parameters(recurse=False):
3812
+ yield name, parameter.data
3813
+ for name, buffer in module.named_buffers(recurse=False):
3814
+ yield name, buffer.data
3815
+
3816
+
3817
+ def _resolve_resident_module_patterns(
3818
+ module: nn.Module,
3819
+ config: DynamicOffloadConfig,
3820
+ ) -> tuple[re.Pattern[str], ...]:
3821
+ raw_patterns = tuple(pattern.strip() for pattern in config.resident_module_patterns if pattern.strip())
3822
+ explicit_patterns = tuple(pattern for pattern in raw_patterns if pattern.lower() != "auto")
3823
+ compiled_patterns = [re.compile(pattern) for pattern in explicit_patterns]
3824
+ if not any(pattern.lower() == "auto" for pattern in raw_patterns):
3825
+ return tuple(compiled_patterns)
3826
+
3827
+ inferred_patterns = _infer_repeated_resident_module_patterns(module, config)
3828
+ return (*compiled_patterns, *inferred_patterns)
3829
+
3830
+
3831
+ def _infer_repeated_resident_module_patterns(
3832
+ module: nn.Module,
3833
+ config: DynamicOffloadConfig,
3834
+ ) -> tuple[re.Pattern[str], ...]:
3835
+ skip_patterns = tuple(re.compile(pattern) for pattern in config.skip_modules_pattern)
3836
+ repeated_module_pattern = re.compile(r"^(.+)\.(\d+)$")
3837
+ groups: dict[str, list[tuple[str, int]]] = {}
3838
+
3839
+ for module_name, submodule in module.named_modules():
3840
+ match = repeated_module_pattern.match(module_name)
3841
+ if match is None:
3842
+ continue
3843
+ if skip_patterns and any(pattern.search(module_name) for pattern in skip_patterns):
3844
+ continue
3845
+ target_bytes = _target_module_size_bytes(submodule, config.target_module_classes)
3846
+ if target_bytes <= 0:
3847
+ continue
3848
+ groups.setdefault(match.group(1), []).append((module_name, target_bytes))
3849
+
3850
+ candidates = [
3851
+ (prefix, members, sum(member_bytes for _, member_bytes in members))
3852
+ for prefix, members in groups.items()
3853
+ if len(members) >= 2
3854
+ ]
3855
+ if not candidates:
3856
+ return ()
3857
+
3858
+ prefix, _, _ = max(candidates, key=lambda item: (item[2], len(item[1])))
3859
+ return (re.compile(rf"^{re.escape(prefix)}\.\d+$"),)
3860
+
3861
+
3862
+ def _classify_tensor(tensor: torch.Tensor, module_resident: bool, small_tensor_threshold_bytes: int) -> str:
3863
+ if module_resident:
3864
+ return "resident_module"
3865
+ if _tensor_size_bytes(tensor) <= small_tensor_threshold_bytes:
3866
+ return "resident_small"
3867
+ return "streamed_large"
3868
+
3869
+
3870
+ def _module_size_bytes(module: nn.Module) -> int:
3871
+ size = sum(_tensor_size_bytes(parameter.data) for parameter in module.parameters(recurse=True))
3872
+ size += sum(_tensor_size_bytes(buffer.data) for buffer in module.buffers(recurse=True))
3873
+ return size
3874
+
3875
+
3876
+ def _target_module_size_bytes(module: nn.Module, target_module_classes: tuple[type[nn.Module], ...]) -> int:
3877
+ size = 0
3878
+ for submodule in module.modules():
3879
+ if not isinstance(submodule, target_module_classes):
3880
+ continue
3881
+ size += sum(_tensor_size_bytes(parameter.data) for parameter in submodule.parameters(recurse=False))
3882
+ size += sum(_tensor_size_bytes(buffer.data) for buffer in submodule.buffers(recurse=False))
3883
+ return size
3884
+
3885
+
3886
+ def _is_module_descendant(module_name: str, parent_name: str) -> bool:
3887
+ return module_name.startswith(f"{parent_name}.")
3888
+
3889
+
3890
+ def _spread_order(items: list[tuple[str, Any, int]], budget_bytes: int) -> list[tuple[str, Any, int]]:
3891
+ if len(items) <= 2:
3892
+ return items
3893
+ average_bytes = max(1, sum(item[2] for item in items) // len(items))
3894
+ target_count = max(1, min(len(items), budget_bytes // average_bytes))
3895
+ if target_count == 1:
3896
+ spread_indices = [len(items) // 2]
3897
+ else:
3898
+ spread_indices = [
3899
+ round(position * (len(items) - 1) / (target_count - 1))
3900
+ for position in range(target_count)
3901
+ ]
3902
+ seen = set()
3903
+ ordered: list[tuple[str, nn.Linear, int]] = []
3904
+ for index in spread_indices:
3905
+ if index not in seen:
3906
+ seen.add(index)
3907
+ ordered.append(items[index])
3908
+ for index, item in enumerate(items):
3909
+ if index not in seen:
3910
+ ordered.append(item)
3911
+ return ordered
3912
+
3913
+
3914
+ def _largest_first_order(items: list[tuple[str, Any, int]]) -> list[tuple[str, Any, int]]:
3915
+ return sorted(items, key=lambda item: item[2], reverse=True)
3916
+
3917
+
3918
+ def _tensor_size_bytes(tensor: torch.Tensor) -> int:
3919
+ return tensor.numel() * tensor.element_size()