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,166 @@
1
+ """Public backend selection contract for thin host runners."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import math
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from .dynamic_offload import DynamicOffloadConfig, resolve_dynamic_offload_preset
11
+
12
+ _BACKENDS = ("linear", "vmm")
13
+ _VMM_PRESETS = ("auto", "nvme_baseline")
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class DynamicOffloadBackend:
18
+ """The resolved route a runner passes to DDO.
19
+
20
+ ``backend`` is intentionally distinct from ``effective_preset``: the
21
+ stable linear default keeps its existing preset semantics, while VMM has
22
+ only an automatic native route and its protected NVMe fallback.
23
+ """
24
+
25
+ backend: str
26
+ requested_preset: str
27
+ effective_preset: str
28
+ execution_mode: str
29
+
30
+ @property
31
+ def requires_native_bootstrap(self) -> bool:
32
+ return self.effective_preset == "vmm_fast"
33
+
34
+ def build_config(self, **overrides: Any) -> DynamicOffloadConfig:
35
+ """Create the DDO configuration without exposing runtime internals to a host.
36
+
37
+ A runner may provide normal DDO options such as the VMM capacity and
38
+ staging budgets, but it never needs to select an execution mode.
39
+ """
40
+ if "execution_mode" in overrides:
41
+ raise ValueError("execution_mode is selected by the resolved DDO backend")
42
+ if overrides.get("vmm_component_tensor_ownership") and self.execution_mode != "vmm_fast_runtime":
43
+ raise ValueError("component ownership is exclusive to experimental vmm_fast")
44
+ if overrides.get("vmm_execution_auxiliary_ownership") and self.execution_mode != "vmm_fast_runtime":
45
+ raise ValueError("execution auxiliary ownership is exclusive to experimental vmm_fast")
46
+ return DynamicOffloadConfig(execution_mode=self.execution_mode, **overrides)
47
+
48
+ def build_config_from_args(self, args: argparse.Namespace) -> DynamicOffloadConfig:
49
+ """Build the route configuration from the standard runner arguments."""
50
+ staging = args.ddo_vmm_staging_buffer_gb
51
+ total = getattr(args, "ddo_vmm_total_staging_gb", None)
52
+ if total is not None:
53
+ if not math.isfinite(total) or total <= 0:
54
+ raise ValueError("--ddo-vmm-total-staging-gb must be finite and positive")
55
+ # Protected NVMe config is per slot; native config is total capacity.
56
+ staging = total / 2 if self.execution_mode == "vmm_runtime" else total
57
+ return self.build_config(
58
+ vmm_resident_weight_budget_gb=args.ddo_vmm_resident_weight_budget_gb,
59
+ vmm_staging_buffer_gb=staging,
60
+ vmm_native_transport=getattr(args, "ddo_vmm_native_transport", False),
61
+ vmm_native_source_cache_slot_mb=getattr(args, "ddo_vmm_native_source_cache_slot_mb", 0),
62
+ vmm_native_source_cache_slots=getattr(args, "ddo_vmm_native_source_cache_slots", 0),
63
+ vmm_source_cache_gb=getattr(args, "ddo_vmm_source_cache_gb", 0.0),
64
+ vmm_source_registered_gb=getattr(args, "ddo_vmm_source_registered_gb", 0.0),
65
+ vmm_component_tensor_ownership=getattr(args, "ddo_vmm_component_tensor_ownership", False),
66
+ vmm_execution_auxiliary_ownership=getattr(args, "ddo_vmm_execution_auxiliary_ownership", False),
67
+ vmm_component_buffer_limit_mb=getattr(args, "ddo_vmm_component_buffer_limit_mb", 1),
68
+ )
69
+
70
+
71
+ def resolve_dynamic_offload_backend(
72
+ backend: str = "linear", preset: str = "auto", *, running_on_wsl: bool | None = None
73
+ ) -> DynamicOffloadBackend:
74
+ """Resolve CLI backend and preset without requiring environment variables.
75
+
76
+ ``linear/auto`` remains the established ``one_shot_fast`` default. For
77
+ ``vmm``, ``auto`` selects the native fast route and an explicit
78
+ ``nvme_baseline`` selects the known-safe VMM fallback.
79
+ """
80
+ normalized_backend = backend.strip().lower()
81
+ normalized_preset = preset.strip().lower()
82
+ if normalized_backend not in _BACKENDS:
83
+ raise ValueError(f"Invalid DDO backend {backend!r}. Valid values: {', '.join(_BACKENDS)}")
84
+ if normalized_backend == "linear":
85
+ return DynamicOffloadBackend(
86
+ backend="linear",
87
+ requested_preset=normalized_preset,
88
+ effective_preset=resolve_dynamic_offload_preset(normalized_preset, running_on_wsl=running_on_wsl),
89
+ execution_mode="linear_runtime",
90
+ )
91
+ if normalized_preset not in _VMM_PRESETS:
92
+ raise ValueError(f"Invalid VMM preset {preset!r}. Valid values: {', '.join(_VMM_PRESETS)}")
93
+ return DynamicOffloadBackend(
94
+ backend="vmm",
95
+ requested_preset=normalized_preset,
96
+ effective_preset="vmm_fast" if normalized_preset == "auto" else "nvme_baseline",
97
+ execution_mode="vmm_fast_runtime" if normalized_preset == "auto" else "vmm_runtime",
98
+ )
99
+
100
+
101
+ def add_dynamic_offload_lifecycle_arguments(
102
+ parser: argparse.ArgumentParser,
103
+ phases: tuple[str, ...] = ("before_run", "after_text_encoder", "before_transformer", "after_run"),
104
+ ) -> argparse.ArgumentParser:
105
+ """Expose tri-state Windows lifecycle controls without mutating the environment."""
106
+ for phase in phases:
107
+ if phase not in ("before_run", "after_text_encoder", "before_transformer", "after_run"):
108
+ raise ValueError(f"Unsupported standby lifecycle phase: {phase}")
109
+ parser.add_argument(
110
+ "--purge-" + phase.replace("_", "-"),
111
+ action=argparse.BooleanOptionalAction,
112
+ default=None,
113
+ help="Windows standby purge: explicit CLI overrides environment/preset; omitted inherits them.",
114
+ )
115
+ return parser
116
+
117
+
118
+ def add_dynamic_offload_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
119
+ """Add the standard DDO route arguments to a host runner parser."""
120
+ parser.add_argument("--ddo-backend", choices=_BACKENDS, default="linear", help="DDO backend (default: linear).")
121
+ parser.add_argument("--ddo-preset", default="auto", help="DDO preset; VMM accepts auto or nvme_baseline.")
122
+ parser.add_argument(
123
+ "--ddo-vmm-resident-weight-budget-gb",
124
+ type=float,
125
+ default=4.0,
126
+ help="Native VMM active-residency capacity in GiB (default: 4).",
127
+ )
128
+ parser.add_argument(
129
+ "--ddo-vmm-total-staging-gb", type=float, default=None,
130
+ help="Total reusable host-staging capacity in GiB for either VMM route; omitted preserves legacy defaults.",
131
+ )
132
+ parser.add_argument(
133
+ "--ddo-vmm-staging-buffer-gb",
134
+ type=float,
135
+ default=0.625,
136
+ help="Legacy route-specific staging value; prefer --ddo-vmm-total-staging-gb for total capacity.",
137
+ )
138
+ parser.add_argument(
139
+ "--ddo-vmm-native-transport", action="store_true",
140
+ help="Use the experimental vmm_fast native host ring, also with source cache disabled.",
141
+ )
142
+ parser.add_argument(
143
+ "--ddo-vmm-native-source-cache-slot-mb", type=int, default=0,
144
+ help="Experimental vmm_fast retained-source slot size in MiB (0 disables; maximum 64).",
145
+ )
146
+ parser.add_argument(
147
+ "--ddo-vmm-native-source-cache-slots", type=int, default=0,
148
+ help="Retained-source slots (set with slot size; current total cache maximum 128 MiB).",
149
+ )
150
+ parser.add_argument("--show-profile", action="store_true", help="Print the DDO profile report.")
151
+ parser.add_argument(
152
+ "--ddo-vmm-source-cache-gb", type=float, default=0.0,
153
+ help="Opt-in native shared-window source capacity in GiB (maximum 32; lazy registration; default off).",
154
+ )
155
+ parser.add_argument(
156
+ "--ddo-vmm-source-registered-gb", type=float, default=0.0,
157
+ help="Separate CUDA registration ceiling within retained source storage, in GiB (0 uses the storage ceiling).",
158
+ )
159
+ parser.add_argument("--ddo-vmm-component-tensor-ownership", action="store_true",
160
+ help="Experimental whole-component ownership; requires native file transport; selected text-only workloads validated, not general encoder support.")
161
+ parser.add_argument("--ddo-vmm-execution-auxiliary-ownership", action="store_true",
162
+ help="Experimental auxiliary parameters in native execution-unit batches; unchanged GPU ceiling; default off.")
163
+ parser.add_argument("--ddo-vmm-component-buffer-limit-mb", type=int, default=1,
164
+ help="Explicit device-buffer ceiling in MiB for the opt-in component route.")
165
+ parser.add_argument("--show-metrics", action="store_true", help="Print the DDO metrics JSON.")
166
+ return parser
@@ -0,0 +1,60 @@
1
+ """Opt-in native idle device-cache release at completed phase boundaries."""
2
+
3
+ import gc
4
+ import time
5
+
6
+ import torch
7
+
8
+ from .metrics import DynamicOffloadMetrics
9
+
10
+
11
+ def _installed_native():
12
+ from ddo_vmm_allocator.native import NativeVmmLibrary
13
+ from ddo_vmm_allocator.torch_allocator import installed_library_path
14
+
15
+ path = installed_library_path()
16
+ return NativeVmmLibrary(path) if path is not None else None
17
+
18
+
19
+ def release_native_vmm_idle_cache(*, enabled=False, phase="", device=None, clear_cublas_workspaces=False):
20
+ """Release only whole-idle backing, never live tensors or model weights.
21
+
22
+ Caller must detach previous components and drop their references first.
23
+ Synchronizes once at this explicit phase boundary. Does not initialize CUDA,
24
+ alter budgets, purge CPU standby or promise all process VRAM becomes free.
25
+ Native proof/release failures propagate; unsupported is not success.
26
+ Optional cuBLAS cleanup uses a guarded private PyTorch API, restricted to
27
+ a quiescent single-GPU process on the compute thread without graph capture.
28
+ No concurrent compute may run during this explicit boundary operation.
29
+ """
30
+ started = time.perf_counter()
31
+ observation = {"phase": phase, "status": "disabled", "trim_executed": False}
32
+ if enabled:
33
+ if not torch.cuda.is_initialized():
34
+ observation["status"] = "cuda_not_initialized"
35
+ else:
36
+ native = _installed_native()
37
+ if native is None:
38
+ observation["status"] = "native_allocator_not_installed"
39
+ else:
40
+ clear_blas = None
41
+ if clear_cublas_workspaces:
42
+ clear_blas = getattr(torch._C, "_cuda_clearCublasWorkspaces", None)
43
+ if not callable(clear_blas):
44
+ raise RuntimeError("PyTorch cuBLAS workspace cleanup is unsupported")
45
+ if torch.cuda.device_count() != 1 or torch.cuda.is_current_stream_capturing():
46
+ raise RuntimeError("cuBLAS cleanup requires a single GPU without graph capture")
47
+ gc.collect()
48
+ torch.cuda.synchronize(device)
49
+ if clear_blas is not None:
50
+ observation["pool_before_cublas_clear"] = native.torch_pool_stats()
51
+ clear_blas()
52
+ observation["cublas_workspaces_cleared"] = True
53
+ observation.update(native.trim_idle_torch_pool())
54
+ observation["library"] = str(native.path)
55
+ observation["elapsed_seconds"] = time.perf_counter() - started
56
+ return DynamicOffloadMetrics(
57
+ route="native_vmm_idle_cache_release",
58
+ configuration={"enabled": bool(enabled), "clear_cublas_workspaces": bool(clear_cublas_workspaces)},
59
+ setup={"device_cache_release": observation},
60
+ )