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
ddo_native_check.py ADDED
@@ -0,0 +1,44 @@
1
+ """Small opt-in installed-allocator check, without model loading or benchmarking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+
7
+
8
+ def _run_cuda() -> None:
9
+ # Bootstrap must have installed the allocator before these imports.
10
+ import torch
11
+ from ddo_vmm_allocator.torch_allocator import installed_library_path
12
+
13
+ library = installed_library_path()
14
+ if library is None:
15
+ raise RuntimeError("DDO native allocator was not installed")
16
+
17
+ x = torch.ones(1024, device="cuda:0", dtype=torch.int32)
18
+ y = x + 1
19
+ torch.cuda.synchronize()
20
+ if y.sum().item() != 2048:
21
+ raise RuntimeError("Native CUDA result mismatch")
22
+
23
+ print("Native library:", library)
24
+ print("DDO native CUDA: PASS")
25
+
26
+
27
+ def main(argv: list[str] | None = None) -> None:
28
+ parser = argparse.ArgumentParser(description=__doc__)
29
+ parser.add_argument(
30
+ "--run-cuda", action="store_true",
31
+ help="Explicitly run a small CUDA operation through the native allocator.",
32
+ )
33
+ args = parser.parse_args(argv)
34
+ if not args.run_cuda:
35
+ parser.error("pass --run-cuda to authorize GPU execution")
36
+
37
+ from ddo_vmm_bootstrap import ensure_vmm_fast_process
38
+
39
+ ensure_vmm_fast_process(allocator_cache_mib=32, argv=[__file__, "--run-cuda"])
40
+ _run_cuda()
41
+
42
+
43
+ if __name__ == "__main__":
44
+ main()
ddo_vmm_bootstrap.py ADDED
@@ -0,0 +1,142 @@
1
+ """Fresh-process bootstrap for the experimental native VMM backend.
2
+
3
+ This module deliberately has no dependency on :mod:`torch` or the DDO package.
4
+ Import it as the first executable action in a VMM-fast runner, so the child can
5
+ install the native allocator before the runner imports Torch or Diffusers.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from importlib.util import find_spec
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import Mapping, Sequence
16
+
17
+ _CHILD_MARKER = "DDO_VMM_FAST_CHILD"
18
+ _BOOTSTRAP = """
19
+ from ddo_vmm_allocator.torch_allocator import install_pytorch_vmm_allocator
20
+ import runpy
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ install_pytorch_vmm_allocator()
25
+ target = sys.argv[1]
26
+ sys.path.insert(0, str(Path(target).resolve().parent))
27
+ sys.argv = [target, *sys.argv[2:]]
28
+ runpy.run_path(target, run_name='__main__')
29
+ """
30
+
31
+
32
+ def vmm_fast_requested(argv: Sequence[str] | None = None, *, default_backend: str = "linear") -> bool:
33
+ """Return whether a runner invocation selects the native VMM route.
34
+
35
+ It reads only the two public runner arguments before CUDA-owning imports.
36
+ The protected NVMe baseline and linear routes stay in the original process.
37
+ """
38
+ arguments = list(sys.argv[1:] if argv is None else argv)
39
+ backend = default_backend
40
+ preset = "auto"
41
+ for index, argument in enumerate(arguments):
42
+ if argument.startswith("--ddo-backend="):
43
+ backend = argument.partition("=")[2]
44
+ elif argument == "--ddo-backend" and index + 1 < len(arguments):
45
+ backend = arguments[index + 1]
46
+ elif argument.startswith("--ddo-preset="):
47
+ preset = argument.partition("=")[2]
48
+ elif argument == "--ddo-preset" and index + 1 < len(arguments):
49
+ preset = arguments[index + 1]
50
+ return backend.strip().lower() == "vmm" and preset.strip().lower() == "auto"
51
+
52
+
53
+ def _default_allocator_root() -> Path | None:
54
+ """Find the checked-out optional allocator without importing it."""
55
+ candidate = Path(__file__).resolve().parents[1] / "ddo-vmm-allocator"
56
+ return candidate if candidate.is_dir() else None
57
+
58
+
59
+ def _installed_allocator_root() -> Path | None:
60
+ """Locate a top-level adapter package without importing it or CUDA."""
61
+ try:
62
+ spec = find_spec("ddo_vmm_allocator")
63
+ except (ImportError, ValueError):
64
+ return None
65
+ if spec is None or spec.origin is None or not spec.submodule_search_locations:
66
+ return None
67
+ return Path(spec.origin).resolve().parent
68
+
69
+
70
+ def _discover_library(checkout: Path | None, package: Path | None) -> Path | None:
71
+ """Use conventional build or platform package paths, never scan candidates."""
72
+ if sys.platform == "win32":
73
+ builds = ("build/Release/ddo_vmm.dll",)
74
+ packaged = "native/win32/ddo_vmm.dll"
75
+ elif sys.platform == "linux":
76
+ builds = ("build-linux/libddo_vmm.so", "build/libddo_vmm.so")
77
+ packaged = "native/linux/libddo_vmm.so"
78
+ else:
79
+ return None
80
+ candidates = [checkout / name for name in builds] if checkout is not None else []
81
+ if package is not None:
82
+ candidates.append(package / packaged)
83
+ return next((path for path in candidates if path.is_file()), None)
84
+
85
+
86
+ def ensure_vmm_fast_process(
87
+ *,
88
+ library_path: str | os.PathLike[str] | None = None,
89
+ allocator_cache_mib: int = 512,
90
+ argv: Sequence[str] | None = None,
91
+ environ: Mapping[str, str] | None = None,
92
+ ) -> None:
93
+ """Run this script under the native allocator or exit the parent process.
94
+
95
+ Call this as the first executable statement of a VMM-fast runner. In the
96
+ child this function is a no-op. Discover a conventional checkout build or
97
+ platform-packaged binary automatically. Explicit paths and the environment
98
+ override discovery for diagnostics; missing binaries are never downloaded
99
+ or built during execution.
100
+ """
101
+ environment = os.environ if environ is None else environ
102
+ if environment.get(_CHILD_MARKER) == "1":
103
+ return
104
+ if allocator_cache_mib < 0:
105
+ raise ValueError("allocator_cache_mib must be non-negative")
106
+ torch_module = sys.modules.get("torch")
107
+ if torch_module is not None and torch_module.cuda.is_initialized():
108
+ raise RuntimeError("vmm_fast bootstrap must run before CUDA is initialized")
109
+
110
+ arguments = list(sys.argv if argv is None else argv)
111
+ if not arguments or not arguments[0]:
112
+ raise RuntimeError("VMM bootstrap requires a runner script in argv[0]")
113
+ target = Path(arguments[0]).resolve(strict=True)
114
+ root = _default_allocator_root()
115
+ package = _installed_allocator_root()
116
+ library = library_path or environment.get("DDO_VMM_LIBRARY_PATH")
117
+ if not library:
118
+ library = _discover_library(root, package)
119
+ if not library:
120
+ raise RuntimeError(
121
+ "vmm_fast requires a platform native binary: install an allocator package "
122
+ "containing its binary or build the checkout's conventional native target. "
123
+ "For diagnostics, it requires DDO_VMM_LIBRARY_PATH or an explicit library_path."
124
+ )
125
+ library = str(Path(library).resolve(strict=True))
126
+
127
+ if root is None and package is None:
128
+ raise RuntimeError("vmm_fast requires the ddo-vmm-allocator submodule or installed package")
129
+ child_environment = dict(environment)
130
+ child_environment[_CHILD_MARKER] = "1"
131
+ child_environment["DDO_VMM_LIBRARY_PATH"] = library
132
+ child_environment["DDO_VMM_TORCH_CACHE_MIB"] = str(allocator_cache_mib)
133
+ if root is not None:
134
+ source_root = str(root / "src")
135
+ existing_path = child_environment.get("PYTHONPATH")
136
+ child_environment["PYTHONPATH"] = source_root if not existing_path else source_root + os.pathsep + existing_path
137
+ result = subprocess.run(
138
+ [sys.executable, "-c", _BOOTSTRAP, str(target), *arguments[1:]],
139
+ env=child_environment,
140
+ check=False,
141
+ )
142
+ raise SystemExit(result.returncode)
@@ -0,0 +1,116 @@
1
+ from .backend import (
2
+ DynamicOffloadBackend, add_dynamic_offload_arguments,
3
+ add_dynamic_offload_lifecycle_arguments, resolve_dynamic_offload_backend,
4
+ )
5
+ from .dynamic_offload import (
6
+ DDO_PRESETS,
7
+ DiffusersGroupOffloadResult,
8
+ DynamicOffloadApplyResult,
9
+ DynamicOffloadConfig,
10
+ DynamicOffloadHook,
11
+ DynamicOffloadLoadResult,
12
+ DynamicOffloadPlanEntry,
13
+ DynamicOffloadSettings,
14
+ DynamicOffloadState,
15
+ apply_dynamic_offload,
16
+ build_dynamic_offload_event_payload,
17
+ clear_dynamic_offload_pinned_tensor_cache,
18
+ clear_dynamic_offload_plan_cache,
19
+ detect_quantized_backend_modules,
20
+ dynamic_offload_env_value,
21
+ dynamic_offload_preset_env_value,
22
+ enable_diffusers_group_offload,
23
+ enable_dynamic_offload,
24
+ enable_offload,
25
+ enable_pipeline_offload,
26
+ format_dynamic_offload_presets,
27
+ from_pretrained_with_dynamic_offload,
28
+ get_available_system_ram_gb,
29
+ get_dynamic_offload_presets,
30
+ get_dynamic_offload_state,
31
+ is_wsl_environment,
32
+ load_dynamic_offload_settings_from_env,
33
+ maybe_purge_windows_standby_cache,
34
+ purge_windows_standby_cache,
35
+ purge_windows_standby_cache_event,
36
+ remove_dynamic_offload,
37
+ resolve_dynamic_offload_preset,
38
+ )
39
+ from .metrics import DYNAMIC_OFFLOAD_METRICS_SCHEMA_VERSION, DynamicOffloadMetrics
40
+ from .host_cache import release_pytorch_host_cache
41
+ from .device_cache import release_native_vmm_idle_cache
42
+ from .host_memory import inspect_host_memory
43
+ from .timing import DynamicOffloadExecutionTimer
44
+ from .profiles import (
45
+ DYNAMIC_OFFLOAD_PROFILE_SCHEMA_VERSION,
46
+ DynamicOffloadProfileSession,
47
+ dynamic_offload_profile_key,
48
+ dynamic_offload_profile_path,
49
+ get_dynamic_offload_profile_capacity,
50
+ get_dynamic_offload_profile_dir,
51
+ get_dynamic_offload_profile_recommendation,
52
+ inspect_vmm_component,
53
+ load_dynamic_offload_profile,
54
+ normalize_dynamic_offload_profile_context,
55
+ record_dynamic_offload_profile,
56
+ )
57
+ from .vmm_weight_store import VmmWeightLease, VmmWeightStore, VmmWeightStoreStats
58
+
59
+ __all__ = [
60
+ "DDO_PRESETS",
61
+ "DynamicOffloadConfig",
62
+ "DynamicOffloadHook",
63
+ "DynamicOffloadLoadResult",
64
+ "DynamicOffloadApplyResult",
65
+ "DynamicOffloadPlanEntry",
66
+ "DynamicOffloadSettings",
67
+ "DynamicOffloadState",
68
+ "DiffusersGroupOffloadResult",
69
+ "DYNAMIC_OFFLOAD_METRICS_SCHEMA_VERSION",
70
+ "DynamicOffloadMetrics",
71
+ "release_pytorch_host_cache",
72
+ "release_native_vmm_idle_cache",
73
+ "inspect_host_memory",
74
+ "DynamicOffloadExecutionTimer",
75
+ "DynamicOffloadBackend",
76
+ "add_dynamic_offload_arguments",
77
+ "add_dynamic_offload_lifecycle_arguments",
78
+ "resolve_dynamic_offload_backend",
79
+ "apply_dynamic_offload",
80
+ "detect_quantized_backend_modules",
81
+ "enable_dynamic_offload",
82
+ "enable_offload",
83
+ "enable_pipeline_offload",
84
+ "enable_diffusers_group_offload",
85
+ "build_dynamic_offload_event_payload",
86
+ "clear_dynamic_offload_pinned_tensor_cache",
87
+ "clear_dynamic_offload_plan_cache",
88
+ "dynamic_offload_env_value",
89
+ "dynamic_offload_preset_env_value",
90
+ "format_dynamic_offload_presets",
91
+ "from_pretrained_with_dynamic_offload",
92
+ "get_available_system_ram_gb",
93
+ "get_dynamic_offload_presets",
94
+ "get_dynamic_offload_state",
95
+ "is_wsl_environment",
96
+ "load_dynamic_offload_settings_from_env",
97
+ "maybe_purge_windows_standby_cache",
98
+ "purge_windows_standby_cache",
99
+ "purge_windows_standby_cache_event",
100
+ "remove_dynamic_offload",
101
+ "resolve_dynamic_offload_preset",
102
+ "DYNAMIC_OFFLOAD_PROFILE_SCHEMA_VERSION",
103
+ "DynamicOffloadProfileSession",
104
+ "dynamic_offload_profile_key",
105
+ "dynamic_offload_profile_path",
106
+ "get_dynamic_offload_profile_capacity",
107
+ "get_dynamic_offload_profile_dir",
108
+ "get_dynamic_offload_profile_recommendation",
109
+ "inspect_vmm_component",
110
+ "load_dynamic_offload_profile",
111
+ "normalize_dynamic_offload_profile_context",
112
+ "record_dynamic_offload_profile",
113
+ "VmmWeightLease",
114
+ "VmmWeightStore",
115
+ "VmmWeightStoreStats",
116
+ ]
@@ -0,0 +1,96 @@
1
+ """Explicit native allocation diagnosis, without changing allocation policy."""
2
+ from dataclasses import replace
3
+ from time import perf_counter
4
+
5
+
6
+ class DynamicOffloadAllocationDiagnostics:
7
+ """Process-wide native host counters sampled at CPU submission boundaries.
8
+
9
+ Driver timers include host blocking inside the call, not GPU kernel time.
10
+ Boundaries do not wait for CUDA: work in flight can cross snapshots. Timers
11
+ are cumulative/delta observations, not disjoint partitions of GPU duration.
12
+ Pool peak is a process-wide high-water mark observed on new backing creation,
13
+ excludes model arenas and is not an absolute driver-memory peak.
14
+ """
15
+
16
+ def __init__(self, *, enabled=False, native=None):
17
+ self.enabled, self._native = bool(enabled), native
18
+ self._used = self._active = self._failed = False
19
+ self._steps = []
20
+ self._error = None
21
+ self._last = self._baseline = self._final = None
22
+
23
+ def _read(self):
24
+ snapshot = self._native.allocation_diagnostics_snapshot()
25
+ if not snapshot:
26
+ raise RuntimeError("native allocation diagnostics are unavailable")
27
+ return snapshot
28
+
29
+ def __enter__(self):
30
+ if self._used:
31
+ raise RuntimeError("Allocation diagnostic scopes cannot be reused")
32
+ self._used = True
33
+ if self.enabled:
34
+ if self._native is None:
35
+ raise ValueError("Allocation diagnostics require an active native component")
36
+ self._native.set_allocation_diagnostics(True)
37
+ try:
38
+ self._baseline = self._last = self._read()
39
+ self._started = self._last_time = perf_counter()
40
+ except BaseException:
41
+ self._native.set_allocation_diagnostics(False)
42
+ raise
43
+ self._active = True
44
+ return self
45
+
46
+ @staticmethod
47
+ def _delta(before, after):
48
+ return {key: after[key] - value for key, value in before.items()
49
+ if key.endswith(("_calls", "_host_seconds", "_backings"))}
50
+
51
+ def mark_step(self):
52
+ if not self.enabled:
53
+ return
54
+ if not self._active:
55
+ raise RuntimeError("Allocation step marker requires an active scope")
56
+ current = self._read()
57
+ now = perf_counter()
58
+ self._steps.append({"step_index": len(self._steps),
59
+ "host_submission_seconds": now - self._last_time,
60
+ "driver_delta": self._delta(self._last, current),
61
+ "pool_observed_peak_mapped_bytes": current["pool_observed_peak_mapped_bytes"]})
62
+ self._last, self._last_time = current, now
63
+
64
+ def __exit__(self, exc_type, exc_value, traceback):
65
+ self._failed, self._active = exc_type is not None, False
66
+ if self.enabled:
67
+ try:
68
+ try:
69
+ self._final = self._read()
70
+ self._elapsed = perf_counter() - self._started
71
+ finally:
72
+ self._native.set_allocation_diagnostics(False)
73
+ except BaseException as error:
74
+ self._failed, self._error = True, repr(error)
75
+ if exc_value is None:
76
+ raise
77
+ if hasattr(exc_value, "add_note"):
78
+ exc_value.add_note("Allocation diagnostic cleanup also failed: " + repr(error))
79
+
80
+ def snapshot(self):
81
+ result = {"schema_version": 1, "scope": "process_native_driver_host_calls",
82
+ "boundary": "cpu_submission_no_cuda_wait", "benchmark_eligible": False,
83
+ "failed": self._failed}
84
+ if not self.enabled:
85
+ return {**result, "status": "disabled"}
86
+ if self._error is not None:
87
+ return {**result, "status": "failed", "error": self._error}
88
+ if self._final is None:
89
+ return {**result, "status": "not_finished"}
90
+ return {**result, "status": "complete", "native_schema_version": self._final["schema_version"],
91
+ "host_scope_seconds": self._elapsed,
92
+ "steps": list(self._steps), "total_delta": self._delta(self._baseline, self._final),
93
+ "pool_observed_peak_mapped_bytes": self._final["pool_observed_peak_mapped_bytes"]}
94
+
95
+ def attach(self, report):
96
+ return replace(report, runtime={**report.runtime, "allocation_diagnostics": self.snapshot()})
@@ -0,0 +1,126 @@
1
+ """Bounded, opt-in detachment of residual loader-owned CPU inference tensors."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ import torch
7
+
8
+ from .metrics import DynamicOffloadMetrics
9
+ from .host_cache import _host_snapshot
10
+ from .vmm_weight_store import SafetensorSliceRegistry
11
+
12
+
13
+ def _detach_cpu_sources(module, registry, max_copy_bytes):
14
+ """Transactional CPU-only worker; native readiness is checked by the caller."""
15
+ if not isinstance(registry, SafetensorSliceRegistry):
16
+ raise ValueError("Residual source detachment requires DDO source provenance")
17
+ if any(child.training for child in module.modules()):
18
+ raise ValueError("Residual source detachment requires an eval component")
19
+ groups = {}
20
+ for kind, iterator in (("parameter", module.named_parameters(remove_duplicate=False)),
21
+ ("buffer", module.named_buffers(remove_duplicate=False))):
22
+ for name, tensor in iterator:
23
+ if tensor.device.type != "cpu" or tensor.numel() == 0:
24
+ continue
25
+ start = tensor.data_ptr()
26
+ size = tensor.numel() * tensor.element_size()
27
+ group = groups.setdefault((start, size), {"owners": {}, "names": [], "descriptor": None})
28
+ group["owners"][id(tensor)] = tensor
29
+ group["names"].append(f"{kind}:{name}")
30
+ descriptor = registry.lookup(tensor)
31
+ if descriptor is not None:
32
+ if group["descriptor"] is not None and group["descriptor"] != descriptor:
33
+ raise ValueError("Conflicting residual source aliases")
34
+ group["descriptor"] = descriptor
35
+ selected = {key: group for key, group in groups.items() if group["descriptor"] is not None}
36
+ # Partial overlaps/strides need a more general storage-preserving transform.
37
+ # Refuse instead of silently severing alias semantics or copying shard gaps.
38
+ intervals = sorted(groups)
39
+ for index, key in enumerate(intervals):
40
+ start, size = key
41
+ for other in intervals[index + 1:]:
42
+ if other[0] >= start + size:
43
+ break
44
+ if key in selected or other in selected:
45
+ raise ValueError("Overlapping residual CPU views are unsupported")
46
+ total = sum(size for _start, size in selected)
47
+ if total > max_copy_bytes:
48
+ raise ValueError(f"Residual source copy requires {total} bytes, above the explicit {max_copy_bytes} byte limit")
49
+ for group in selected.values():
50
+ descriptor = group["descriptor"]
51
+ for tensor in group["owners"].values():
52
+ if (type(tensor) not in (torch.Tensor, torch.nn.Parameter) or not tensor.is_contiguous()
53
+ or tensor.layout != torch.strided or tensor.is_pinned()):
54
+ raise ValueError("Residual source ownership/layout is unsupported")
55
+ probe = SafetensorSliceRegistry()
56
+ if not probe.bind(tensor, descriptor):
57
+ raise ValueError("Residual alias shape/dtype does not match source provenance")
58
+ prepared = []
59
+ with torch.no_grad():
60
+ for group in selected.values():
61
+ owners = list(group["owners"].values())
62
+ old = owners[0].detach()
63
+ new = old.clone(memory_format=torch.preserve_format)
64
+ prepared.append((group, owners, old, new))
65
+ changed = []
66
+ try:
67
+ for group, owners, _old, new in prepared:
68
+ for tensor in owners:
69
+ old_data = tensor.detach()
70
+ tensor.data = new
71
+ changed.append((tensor, old_data))
72
+ registry.rebind_many([(old, new) for _group, _owners, old, new in prepared])
73
+ except BaseException:
74
+ for tensor, old in reversed(changed):
75
+ tensor.data = old
76
+ raise
77
+ paths = sorted({str(group["descriptor"].path) for group in selected.values()})
78
+ return {"copied_bytes": total, "copied_storage_groups": len(selected),
79
+ "copied_tensor_owners": sum(len(group["owners"]) for group in selected.values()),
80
+ "copied_named_references": sum(len(group["names"]) for group in selected.values()),
81
+ "unbound_cpu_storage_groups": len(groups) - len(selected),
82
+ "source_shard_count": len(paths), "source_shard_samples": paths[:16],
83
+ "scope": "source_backed_registered_cpu_tensors_after_fast_attach",
84
+ "gpu_placement_changed": False, "commit_recovery_proven": False}
85
+
86
+
87
+ def detach_auxiliary_cpu_sources(result, *, enabled=False, max_copy_bytes=16 * 1024**2):
88
+ """Detach bounded CPU loader views once before the first native forward.
89
+
90
+ Diagnostic opt-in only. Requires exclusive component ownership; cannot find
91
+ arbitrary escaped tensor references. Exact registered aliases retain object
92
+ identity, values, device and dtype. Unsupported/partial aliases fail closed.
93
+ Never changes CUDA residency, native cache budgets or a protected route.
94
+ """
95
+ if type(max_copy_bytes) is not int or max_copy_bytes <= 0:
96
+ raise ValueError("max_copy_bytes must be a positive integer")
97
+ started = time.perf_counter()
98
+ observation = {"status": "disabled", "copied_bytes": 0}
99
+ if enabled:
100
+ hook = result.hook
101
+ if hook is None or hook.execution_mode != "vmm_fast_runtime" or not hook._vmm_runtime_active:
102
+ raise ValueError("Residual source detachment requires an attached vmm_fast component")
103
+ previous = getattr(hook, "_auxiliary_source_detachment_report", None)
104
+ if previous is not None:
105
+ return previous
106
+ store = hook._vmm_fast_store
107
+ if store is None:
108
+ raise ValueError("Native source ownership is unavailable")
109
+ stats = store.runtime_stats()
110
+ required = ("cpu_source_bindings", "faults", "execution_plan_passes")
111
+ if any(stats.get(key) != 0 for key in required):
112
+ raise ValueError("Residual source detachment requires zero CPU native bindings and no started execution")
113
+ if hook.config.vmm_component_tensor_ownership:
114
+ raise ValueError("Whole-component ownership is outside residual CPU detachment scope")
115
+ host_before = _host_snapshot()
116
+ observation = _detach_cpu_sources(result.module, hook._vmm_file_slices, max_copy_bytes)
117
+ observation["host_before"] = host_before
118
+ observation["host_after"] = _host_snapshot()
119
+ observation["status"] = "detached" if observation["copied_bytes"] else "no_source_backed_cpu_tensors"
120
+ observation["elapsed_seconds"] = time.perf_counter() - started
121
+ report = DynamicOffloadMetrics(route="vmm_auxiliary_source_detachment",
122
+ configuration={"enabled": bool(enabled), "max_copy_bytes": max_copy_bytes},
123
+ setup={"auxiliary_source_detachment": observation})
124
+ if enabled:
125
+ hook._auxiliary_source_detachment_report = report
126
+ return report