diffusers-dynamic-offloader 0.1.0rc2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ddo_native_check.py +44 -0
- ddo_vmm_bootstrap.py +142 -0
- diffusers_dynamic_offloader/__init__.py +116 -0
- diffusers_dynamic_offloader/allocation_diagnostics.py +96 -0
- diffusers_dynamic_offloader/auxiliary_sources.py +126 -0
- diffusers_dynamic_offloader/backend.py +166 -0
- diffusers_dynamic_offloader/device_cache.py +60 -0
- diffusers_dynamic_offloader/dynamic_offload.py +3919 -0
- diffusers_dynamic_offloader/float8_compile.py +77 -0
- diffusers_dynamic_offloader/float8_loading.py +130 -0
- diffusers_dynamic_offloader/host_cache.py +101 -0
- diffusers_dynamic_offloader/host_memory.py +70 -0
- diffusers_dynamic_offloader/linear_convolution.py +105 -0
- diffusers_dynamic_offloader/metrics.py +217 -0
- diffusers_dynamic_offloader/metrics_journal.py +66 -0
- diffusers_dynamic_offloader/operator_diagnostics.py +167 -0
- diffusers_dynamic_offloader/profiles.py +495 -0
- diffusers_dynamic_offloader/quantized_sources.py +58 -0
- diffusers_dynamic_offloader/timing.py +129 -0
- diffusers_dynamic_offloader/vmm_model_arena.py +277 -0
- diffusers_dynamic_offloader/vmm_weight_store.py +840 -0
- diffusers_dynamic_offloader/weight_source_metadata.py +81 -0
- diffusers_dynamic_offloader/windows_file_reader.py +106 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/METADATA +90 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/RECORD +28 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/WHEEL +5 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/licenses/LICENSE +201 -0
- diffusers_dynamic_offloader-0.1.0rc2.dist-info/top_level.txt +3 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Explicit experimental FP8 Linear compute compilation, not residency policy."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from functools import partial
|
|
5
|
+
from types import FunctionType
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _linear_compute(input, weight, bias):
|
|
9
|
+
import torch
|
|
10
|
+
return torch.nn.functional.linear(input, weight, bias)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _dispatch_linear(module, compiled, input):
|
|
14
|
+
# Read the current native-published views on every invocation.
|
|
15
|
+
return compiled(input, module.weight, module.bias)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Float8CompileHandle:
|
|
20
|
+
bindings: list
|
|
21
|
+
|
|
22
|
+
def remove(self):
|
|
23
|
+
"""Remove compute wrappers only after native wrappers have retired."""
|
|
24
|
+
if any(module.forward is not compiled for module, compiled in self.bindings):
|
|
25
|
+
raise RuntimeError("Retire native forward boundaries before removing FP8 compilation")
|
|
26
|
+
for module, _ in self.bindings:
|
|
27
|
+
del module.forward
|
|
28
|
+
self.bindings.clear()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def configure_float8_linear_compile(model):
|
|
32
|
+
"""Compile supported standard Linear computation before native attachment.
|
|
33
|
+
|
|
34
|
+
Lazy CUDA compilation errors propagate. No eager fallback, dtype changes,
|
|
35
|
+
parameter replacement, source retention, or custom math implementation.
|
|
36
|
+
"""
|
|
37
|
+
import torch
|
|
38
|
+
from ddo_vmm_allocator.quantized_payload import _supported_backend
|
|
39
|
+
|
|
40
|
+
cls = _supported_backend()
|
|
41
|
+
if not isinstance(model, torch.nn.Module) or any(module.training for module in model.modules()):
|
|
42
|
+
raise ValueError("FP8 compilation requires an eval component")
|
|
43
|
+
modules = [module for module in model.modules()
|
|
44
|
+
if isinstance(module, torch.nn.Linear) and type(module.weight) is cls]
|
|
45
|
+
if not modules:
|
|
46
|
+
raise ValueError("No supported FP8 Linear weights found")
|
|
47
|
+
if any(type(module) is not torch.nn.Linear for module in modules):
|
|
48
|
+
raise ValueError("FP8 compilation requires standard Linear forward semantics")
|
|
49
|
+
if any("forward" in vars(module) or module._compiled_call_impl is not None for module in modules):
|
|
50
|
+
raise ValueError("Configure FP8 compilation before native forward wrappers or module compilation")
|
|
51
|
+
options = {"triton.cudagraphs": False, "emulate_precision_casts": True,
|
|
52
|
+
"pattern_matcher": False, "epilogue_fusion": False}
|
|
53
|
+
handle = Float8CompileHandle([])
|
|
54
|
+
geometries = {}
|
|
55
|
+
try:
|
|
56
|
+
for module in modules:
|
|
57
|
+
key = (tuple(module.weight.shape), module.weight.dtype,
|
|
58
|
+
None if module.bias is None else (tuple(module.bias.shape), module.bias.dtype))
|
|
59
|
+
if key not in geometries:
|
|
60
|
+
# Dynamo caches by code object. Separate geometries without
|
|
61
|
+
# increasing global limits or compiling the native boundaries.
|
|
62
|
+
compute = FunctionType(_linear_compute.__code__.replace(),
|
|
63
|
+
_linear_compute.__globals__, _linear_compute.__name__)
|
|
64
|
+
geometries[key] = torch.compile(compute, backend="inductor", fullgraph=True,
|
|
65
|
+
dynamic=False, options=options.copy())
|
|
66
|
+
dispatch = partial(_dispatch_linear, module, geometries[key])
|
|
67
|
+
handle.bindings.append((module, dispatch))
|
|
68
|
+
module.forward = dispatch
|
|
69
|
+
except BaseException:
|
|
70
|
+
handle.remove()
|
|
71
|
+
raise
|
|
72
|
+
return {"requested": True, "configuration_applied": True, "denoise_completed": False,
|
|
73
|
+
"compiled_linear_count": len(modules), "backend": "inductor", "fullgraph": True,
|
|
74
|
+
"compiled_geometry_count": len(geometries), "cache_scope": "linear_weight_geometry",
|
|
75
|
+
"dynamic": False, "options": options, "boundary": "linear_compute_before_native_attach",
|
|
76
|
+
"module_call_compilation": False,
|
|
77
|
+
"timing_note": "Lazy compilation is included in the first denoise interval"}, handle
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Explicit local TorchAO checkpoint loading for the experimental native route.
|
|
2
|
+
|
|
3
|
+
No CUDA placement, conversion, math-forward replacement or checkpoint key guesses.
|
|
4
|
+
Physical descriptor names come from upstream serialization of reconstructed tensors.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def validate_float8_native_config(config):
|
|
13
|
+
if (config.execution_mode != "vmm_fast_runtime" or not config.vmm_native_transport
|
|
14
|
+
or not config.vmm_component_tensor_ownership or config.vmm_execution_auxiliary_ownership
|
|
15
|
+
or config.vmm_module_pattern != ".*" or not math.isfinite(config.vmm_source_cache_gb)
|
|
16
|
+
or config.vmm_source_cache_gb <= 0):
|
|
17
|
+
raise ValueError("FP8 weight-only requires native fast VMM, persistent source cache and full component ownership")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_float8_component_cpu(directory, model_class):
|
|
21
|
+
"""Reconstruct saved backend wrappers and bind their physical source ranges."""
|
|
22
|
+
import torch
|
|
23
|
+
from accelerate import init_empty_weights
|
|
24
|
+
from diffusers import TorchAoConfig
|
|
25
|
+
from diffusers.models.modeling_utils import ModelMixin
|
|
26
|
+
from diffusers.quantizers.torchao.torchao_quantizer import TorchAoHfQuantizer
|
|
27
|
+
from safetensors.torch import load_file
|
|
28
|
+
from torchao.quantization import Float8WeightOnlyConfig
|
|
29
|
+
from ddo_vmm_allocator.quantized_payload import _supported_backend, describe_float8_weight_only_cpu
|
|
30
|
+
from .dynamic_offload import _safetensor_file_slices
|
|
31
|
+
from .vmm_weight_store import SafetensorSliceRegistry
|
|
32
|
+
|
|
33
|
+
wrapper_type = _supported_backend()
|
|
34
|
+
directory = Path(directory).resolve(strict=True)
|
|
35
|
+
if not isinstance(model_class, type) or not issubclass(model_class, ModelMixin):
|
|
36
|
+
raise ValueError("FP8 local loading requires an explicit Diffusers ModelMixin class")
|
|
37
|
+
config = json.loads((directory / "config.json").read_text(encoding="utf-8"))
|
|
38
|
+
recipe_config = TorchAoConfig(Float8WeightOnlyConfig(set_inductor_config=False))
|
|
39
|
+
if config.get("quantization_config") != recipe_config.to_dict():
|
|
40
|
+
raise ValueError("Checkpoint does not declare the supported FP8 weight-only recipe")
|
|
41
|
+
indices = list(directory.glob("*.safetensors.index.json"))
|
|
42
|
+
if len(indices) > 1:
|
|
43
|
+
raise ValueError("Ambiguous checkpoint indices")
|
|
44
|
+
if indices:
|
|
45
|
+
weight_map = json.loads(indices[0].read_text(encoding="utf-8"))["weight_map"]
|
|
46
|
+
names = sorted(set(weight_map.values()))
|
|
47
|
+
if any(Path(name).name != name or not name.endswith(".safetensors") for name in names):
|
|
48
|
+
raise ValueError("Checkpoint index must reference local shard basenames")
|
|
49
|
+
paths = [directory / name for name in names]
|
|
50
|
+
else:
|
|
51
|
+
paths = sorted(directory.glob("*.safetensors"))
|
|
52
|
+
if len(paths) != 1:
|
|
53
|
+
raise ValueError("A single checkpoint or explicit shard index is required")
|
|
54
|
+
if any(not path.is_file() or path.resolve().parent != directory for path in paths):
|
|
55
|
+
raise ValueError("Missing shard or shard outside checkpoint directory")
|
|
56
|
+
diagnostics = {}
|
|
57
|
+
available = _safetensor_file_slices(paths, diagnostics=diagnostics)
|
|
58
|
+
if not available or any(diagnostics.values()):
|
|
59
|
+
raise ValueError("Invalid or ambiguous physical checkpoint metadata")
|
|
60
|
+
if indices and (set(weight_map) != set(available) or any(
|
|
61
|
+
available[key].path.name != shard for key, shard in weight_map.items())):
|
|
62
|
+
raise ValueError("Shard index differs from physical checkpoint keys")
|
|
63
|
+
quantizer = TorchAoHfQuantizer(recipe_config)
|
|
64
|
+
quantizer.set_metadata([str(path) for path in paths])
|
|
65
|
+
if not quantizer.metadata:
|
|
66
|
+
raise ValueError("Missing upstream TorchAO wrapper metadata")
|
|
67
|
+
model_config = {key: value for key, value in config.items() if key != "quantization_config"}
|
|
68
|
+
with init_empty_weights():
|
|
69
|
+
model = model_class.from_config(model_config)
|
|
70
|
+
expected = set(model.state_dict())
|
|
71
|
+
seen, physical_seen = set(), set()
|
|
72
|
+
wrapper_count = 0
|
|
73
|
+
for path in paths:
|
|
74
|
+
raw_state = load_file(str(path), device="cpu")
|
|
75
|
+
state = quantizer.maybe_update_state_dict(raw_state)
|
|
76
|
+
if set(state) - expected or seen & set(state):
|
|
77
|
+
raise ValueError("Unexpected or duplicate logical checkpoint keys")
|
|
78
|
+
for tensor in state.values():
|
|
79
|
+
if type(tensor) is wrapper_type:
|
|
80
|
+
describe_float8_weight_only_cpu(tensor)
|
|
81
|
+
wrapper_count += 1
|
|
82
|
+
physical, _ = TorchAoHfQuantizer.get_state_dict_and_metadata(None, state, safe_serialization=True)
|
|
83
|
+
# Upstream flatten clones wrapper payloads. These temporary owners
|
|
84
|
+
# live only through this shard; later shards may reuse their addresses.
|
|
85
|
+
# Validate geometry locally, while physical_seen enforces global keys.
|
|
86
|
+
# Only final published model owners belong in the persistent registry.
|
|
87
|
+
shard_registry = SafetensorSliceRegistry()
|
|
88
|
+
for key, tensor in physical.items():
|
|
89
|
+
descriptor = available.get(key)
|
|
90
|
+
if key in physical_seen or descriptor is None or not shard_registry.bind(tensor, descriptor):
|
|
91
|
+
raise ValueError("Physical payload has no unique matching immutable source")
|
|
92
|
+
physical_seen.update(physical)
|
|
93
|
+
model.load_state_dict(state, strict=False, assign=True)
|
|
94
|
+
seen.update(state)
|
|
95
|
+
del raw_state, state, physical
|
|
96
|
+
if quantizer._pending_flattened_state_dict or seen != expected or physical_seen != set(available):
|
|
97
|
+
raise ValueError("Incomplete logical weights or physical payload sources")
|
|
98
|
+
if not wrapper_count or any(t.device.type != "cpu" for t in model.state_dict().values()):
|
|
99
|
+
raise ValueError("Fully materialized CPU FP8 component required")
|
|
100
|
+
model.eval().requires_grad_(False)
|
|
101
|
+
# load_state_dict/Parameter publication may detach backend payloads into
|
|
102
|
+
# different CPU storage. Bind the final owners, not intermediate loader
|
|
103
|
+
# tensors. Serialized names still come exclusively from upstream flatten.
|
|
104
|
+
registry = SafetensorSliceRegistry()
|
|
105
|
+
owners = dict(model.named_parameters())
|
|
106
|
+
owners.update(dict(model.named_buffers()))
|
|
107
|
+
for name in expected:
|
|
108
|
+
tensor = owners[name]
|
|
109
|
+
serialized, _ = TorchAoHfQuantizer.get_state_dict_and_metadata(
|
|
110
|
+
None, {name: tensor.detach()}, safe_serialization=True)
|
|
111
|
+
payloads = [tensor.qdata, tensor.scale] if type(tensor) is wrapper_type else [tensor]
|
|
112
|
+
for payload in payloads:
|
|
113
|
+
matches = [(key, value) for key, value in serialized.items()
|
|
114
|
+
if value.dtype == payload.dtype and value.shape == payload.shape]
|
|
115
|
+
if len(matches) != 1:
|
|
116
|
+
raise ValueError("Ambiguous upstream physical payload mapping")
|
|
117
|
+
key, value = matches[0]
|
|
118
|
+
if not torch.equal(value.contiguous().reshape(-1).view(torch.uint8),
|
|
119
|
+
payload.contiguous().reshape(-1).view(torch.uint8)):
|
|
120
|
+
raise ValueError("Serialized physical payload differs from final owner")
|
|
121
|
+
if not registry.bind(payload, available[key]):
|
|
122
|
+
raise ValueError("Final physical owner differs from immutable source geometry")
|
|
123
|
+
model.register_to_config(quantization_config=config["quantization_config"])
|
|
124
|
+
model.hf_quantizer = quantizer
|
|
125
|
+
model._ddo_safetensor_slices = registry
|
|
126
|
+
model._ddo_safetensor_slice_summary = {"bound": registry.descriptor_count,
|
|
127
|
+
"available": len(available), "resolver": "torchao_physical_payloads",
|
|
128
|
+
"header": diagnostics}
|
|
129
|
+
model._ddo_float8_weight_only_loaded = True
|
|
130
|
+
return model
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Explicit phase-boundary cleanup of unused PyTorch pinned host allocations."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import ctypes
|
|
5
|
+
import gc
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from .metrics import DynamicOffloadMetrics
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _host_snapshot() -> dict:
|
|
15
|
+
"""Best-effort CPU observations; never query CUDA or change admission."""
|
|
16
|
+
result = {}
|
|
17
|
+
try:
|
|
18
|
+
import psutil
|
|
19
|
+
|
|
20
|
+
memory = psutil.Process().memory_info()
|
|
21
|
+
result["process_rss_bytes"] = memory.rss
|
|
22
|
+
if os.name == "nt":
|
|
23
|
+
result["process_private_bytes"] = memory.private
|
|
24
|
+
except Exception as error:
|
|
25
|
+
result["process_observation_error"] = str(error)
|
|
26
|
+
if os.name == "nt":
|
|
27
|
+
try:
|
|
28
|
+
class MemoryStatus(ctypes.Structure):
|
|
29
|
+
_fields_ = [("length", ctypes.c_uint32), ("load", ctypes.c_uint32)] + [
|
|
30
|
+
(name, ctypes.c_uint64) for name in (
|
|
31
|
+
"total_phys", "available_phys", "total_commit", "available_commit",
|
|
32
|
+
"total_virtual", "available_virtual", "extended",
|
|
33
|
+
)
|
|
34
|
+
]
|
|
35
|
+
function = ctypes.WinDLL("kernel32", use_last_error=True).GlobalMemoryStatusEx
|
|
36
|
+
function.argtypes = [ctypes.POINTER(MemoryStatus)]
|
|
37
|
+
function.restype = ctypes.c_int
|
|
38
|
+
memory = MemoryStatus(length=ctypes.sizeof(MemoryStatus))
|
|
39
|
+
if not function(ctypes.byref(memory)):
|
|
40
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
41
|
+
result.update(available_physical_bytes=memory.available_phys,
|
|
42
|
+
available_process_commit_bytes=memory.available_commit)
|
|
43
|
+
except Exception as error:
|
|
44
|
+
result["system_observation_error"] = str(error)
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _allocator_snapshot() -> dict:
|
|
49
|
+
stats_function = getattr(torch.cuda, "host_memory_stats", None)
|
|
50
|
+
if not callable(stats_function):
|
|
51
|
+
return {"status": "unavailable"}
|
|
52
|
+
try:
|
|
53
|
+
stats = stats_function()
|
|
54
|
+
allocated = stats.get("allocated_bytes.current")
|
|
55
|
+
active = stats.get("active_bytes.current")
|
|
56
|
+
valid_allocated = type(allocated) is int and allocated >= 0
|
|
57
|
+
consistent = valid_allocated and type(active) is int and 0 <= active <= allocated
|
|
58
|
+
return {"status": "available" if valid_allocated else "unavailable",
|
|
59
|
+
"allocated_bytes": allocated if valid_allocated else None,
|
|
60
|
+
"reported_active_bytes": active,
|
|
61
|
+
"active_bytes": active if consistent else None,
|
|
62
|
+
"active_counter_consistent": bool(consistent)}
|
|
63
|
+
except Exception as error:
|
|
64
|
+
return {"status": "unavailable", "error": str(error)}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def release_pytorch_host_cache(*, enabled: bool = False, phase: str = "", device=None) -> DynamicOffloadMetrics:
|
|
68
|
+
"""Release unused PyTorch host blocks at an explicitly opted-in phase boundary.
|
|
69
|
+
|
|
70
|
+
Call after previous components are detached and their caller-owned references
|
|
71
|
+
dropped. Completes device transfers once, never per denoise step. Does not
|
|
72
|
+
initialize CUDA, clear native source storage, free live tensors or set budgets.
|
|
73
|
+
Transfer completion and release errors propagate: failure is not success.
|
|
74
|
+
"""
|
|
75
|
+
started = time.perf_counter()
|
|
76
|
+
observation = {"phase": phase, "status": "disabled", "released": False}
|
|
77
|
+
if enabled:
|
|
78
|
+
if not torch.cuda.is_initialized():
|
|
79
|
+
observation["status"] = "cuda_not_initialized"
|
|
80
|
+
else:
|
|
81
|
+
empty_cache = getattr(torch._C, "_accelerator_emptyHostCache", None)
|
|
82
|
+
if not callable(empty_cache):
|
|
83
|
+
observation["status"] = "unsupported"
|
|
84
|
+
else:
|
|
85
|
+
gc.collect()
|
|
86
|
+
torch.cuda.synchronize(device)
|
|
87
|
+
observation["before"] = _allocator_snapshot()
|
|
88
|
+
observation["host_before"] = _host_snapshot()
|
|
89
|
+
empty_cache()
|
|
90
|
+
observation["after"] = _allocator_snapshot()
|
|
91
|
+
observation["host_after"] = _host_snapshot()
|
|
92
|
+
before = observation["before"].get("allocated_bytes")
|
|
93
|
+
after = observation["after"].get("allocated_bytes")
|
|
94
|
+
observation["allocator_bytes_delta"] = (
|
|
95
|
+
before - after if before is not None and after is not None else None
|
|
96
|
+
)
|
|
97
|
+
observation.update(status="released", released=True)
|
|
98
|
+
observation["elapsed_seconds"] = time.perf_counter() - started
|
|
99
|
+
return DynamicOffloadMetrics(route="pytorch_host_cache_release",
|
|
100
|
+
configuration={"enabled": bool(enabled)},
|
|
101
|
+
setup={"host_cache_release": observation})
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Read-only host observations at caller-selected, nonconcurrent phase boundaries."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from .host_cache import _host_snapshot
|
|
7
|
+
from .metrics import DynamicOffloadMetrics
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def inspect_host_memory(module=None, *, phase: str = "", max_storage_samples: int = 16) -> DynamicOffloadMetrics:
|
|
11
|
+
"""Observe host memory and registered CPU tensor storages without touching data.
|
|
12
|
+
|
|
13
|
+
Never initializes/synchronizes CUDA, collects garbage, copies weights or
|
|
14
|
+
changes placement. The census includes only the passed module's registered
|
|
15
|
+
parameters/buffers, not Python closures, native storage or other components.
|
|
16
|
+
Storage bytes are mapping extents, not RSS or proven private commitment.
|
|
17
|
+
Call only while the component is not concurrently loading/forwarding/unloading.
|
|
18
|
+
"""
|
|
19
|
+
if type(max_storage_samples) is not int or max_storage_samples < 0:
|
|
20
|
+
raise ValueError("max_storage_samples must be a non-negative integer")
|
|
21
|
+
started = time.perf_counter()
|
|
22
|
+
observation = {"phase": phase, "host": _host_snapshot(), "status": "observed"}
|
|
23
|
+
if module is not None:
|
|
24
|
+
groups = {}
|
|
25
|
+
errors = []
|
|
26
|
+
counts = {"cpu_tensor_references": 0, "cpu_tensor_reference_bytes": 0,
|
|
27
|
+
"non_cpu_tensor_references": 0, "inspection_errors": 0}
|
|
28
|
+
registry = getattr(module, "_ddo_safetensor_slices", None)
|
|
29
|
+
for kind, iterator in (("parameter", module.named_parameters(remove_duplicate=False)),
|
|
30
|
+
("buffer", module.named_buffers(remove_duplicate=False))):
|
|
31
|
+
for name, tensor in iterator:
|
|
32
|
+
if tensor.device.type != "cpu":
|
|
33
|
+
counts["non_cpu_tensor_references"] += 1
|
|
34
|
+
continue
|
|
35
|
+
counts["cpu_tensor_references"] += 1
|
|
36
|
+
counts["cpu_tensor_reference_bytes"] += tensor.numel() * tensor.element_size()
|
|
37
|
+
try:
|
|
38
|
+
storage = tensor.untyped_storage()
|
|
39
|
+
size = storage.nbytes()
|
|
40
|
+
# Storage extent and address identify aliases without
|
|
41
|
+
# retaining the tensor/storage in the returned report.
|
|
42
|
+
key = (storage.data_ptr(), size)
|
|
43
|
+
group = groups.setdefault(key, {"storage_bytes": size, "references": 0,
|
|
44
|
+
"examples": [], "shards": set()})
|
|
45
|
+
group["references"] += 1
|
|
46
|
+
if len(group["examples"]) < 3:
|
|
47
|
+
group["examples"].append({"kind": kind, "name": name})
|
|
48
|
+
if registry is not None:
|
|
49
|
+
descriptor = registry.lookup(tensor)
|
|
50
|
+
if descriptor is not None:
|
|
51
|
+
group["shards"].add(str(descriptor.path))
|
|
52
|
+
except Exception as error:
|
|
53
|
+
counts["inspection_errors"] += 1
|
|
54
|
+
if len(errors) < max_storage_samples:
|
|
55
|
+
errors.append({"kind": kind, "name": name, "error": str(error)})
|
|
56
|
+
ordered = sorted(groups.values(), key=lambda item: item["storage_bytes"], reverse=True)
|
|
57
|
+
samples = [{**group, "shards": sorted(group["shards"])}
|
|
58
|
+
for group in ordered[:max_storage_samples]]
|
|
59
|
+
observation["cpu_storages"] = {
|
|
60
|
+
**counts, "unique_storage_count": len(groups),
|
|
61
|
+
"unique_storage_bytes": sum(group["storage_bytes"] for group in ordered),
|
|
62
|
+
"storage_samples": samples, "omitted_storage_count": max(0, len(groups) - len(samples)),
|
|
63
|
+
"errors": errors, "scope": "registered_module_parameters_and_buffers_only",
|
|
64
|
+
}
|
|
65
|
+
if errors or counts["inspection_errors"]:
|
|
66
|
+
observation["status"] = "partial"
|
|
67
|
+
observation["elapsed_seconds"] = time.perf_counter() - started
|
|
68
|
+
return DynamicOffloadMetrics(route="host_memory_observation",
|
|
69
|
+
configuration={"max_storage_samples": max_storage_samples},
|
|
70
|
+
setup={"host_memory": observation})
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Explicit eager convolution offload preserving the component's native math."""
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
|
|
6
|
+
CONVOLUTIONS = (nn.Conv1d, nn.Conv2d, nn.Conv3d)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def validate_convolutions(root, config):
|
|
10
|
+
"""Refuse unsupported ownership before moving tensors or replacing forwards."""
|
|
11
|
+
if config.execution_mode != "linear_runtime" or torch.device(config.offload_device).type != "cpu":
|
|
12
|
+
raise ValueError("Convolution offload requires linear_runtime with CPU offload")
|
|
13
|
+
if config.auto_budget_policy != "off" or config.resident_module_budget_gb or config.always_resident_modules_pattern:
|
|
14
|
+
raise ValueError("Initial convolution offload requires explicit zero residency and no auto budget")
|
|
15
|
+
if config.build_profile or config.cache_pinned_weights:
|
|
16
|
+
raise ValueError("Convolution calibration and persistent pinned cache are not supported")
|
|
17
|
+
if torch.device(config.execution_device).type == "cuda" and torch.cuda.get_allocator_backend() != "native":
|
|
18
|
+
raise ValueError("Initial convolution offload requires the normal PyTorch CUDA allocator")
|
|
19
|
+
owners = {}
|
|
20
|
+
storage_owners = {}
|
|
21
|
+
for name, module in root.named_modules():
|
|
22
|
+
for key, parameter in module.named_parameters(recurse=False):
|
|
23
|
+
owners.setdefault(id(parameter), []).append((name, key))
|
|
24
|
+
if parameter.device.type == "cpu" and parameter.numel():
|
|
25
|
+
storage_owners.setdefault(parameter.untyped_storage().data_ptr(), []).append((name, key))
|
|
26
|
+
for name, module in root.named_modules():
|
|
27
|
+
if not isinstance(module, CONVOLUTIONS):
|
|
28
|
+
continue
|
|
29
|
+
if not name or module.training or list(module.children()) or list(module.buffers(recurse=False)):
|
|
30
|
+
raise ValueError("Convolution offload requires an eval child with no child modules or buffers")
|
|
31
|
+
if (
|
|
32
|
+
module._forward_hooks
|
|
33
|
+
or module._forward_pre_hooks
|
|
34
|
+
or hasattr(module, "_diffusers_hook")
|
|
35
|
+
or hasattr(module, "_hf_hook")
|
|
36
|
+
):
|
|
37
|
+
raise ValueError("Convolution already has execution hooks")
|
|
38
|
+
for parameter in module.parameters(recurse=False):
|
|
39
|
+
if type(parameter) is not nn.Parameter or parameter.device.type != "cpu" or not parameter.is_contiguous():
|
|
40
|
+
raise ValueError("Convolution offload requires plain contiguous CPU parameters")
|
|
41
|
+
if parameter.dtype not in (torch.float32, torch.float16, torch.bfloat16, torch.float64):
|
|
42
|
+
raise ValueError("Convolution offload requires dense floating-point parameters")
|
|
43
|
+
if len(owners[id(parameter)]) != 1 or (
|
|
44
|
+
parameter.numel() and len(storage_owners[parameter.untyped_storage().data_ptr()]) != 1
|
|
45
|
+
):
|
|
46
|
+
raise ValueError("Shared convolution parameter ownership is not supported")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def patch_convolution(hook, module):
|
|
50
|
+
"""Scope temporary weights to eager, current-stream native forward execution.
|
|
51
|
+
|
|
52
|
+
PyTorch owns copies and stream-ordered retirement. No stream, global sync,
|
|
53
|
+
residency cache or convolution kernel is introduced. Custom forwards must
|
|
54
|
+
not mutate parameters, escape weight views or dispatch on another stream.
|
|
55
|
+
"""
|
|
56
|
+
original = module.forward
|
|
57
|
+
active = False
|
|
58
|
+
|
|
59
|
+
def forward(_module, *args, **kwargs):
|
|
60
|
+
nonlocal active
|
|
61
|
+
if active or _module.training or torch.is_grad_enabled():
|
|
62
|
+
raise RuntimeError("Convolution offload requires non-reentrant inference")
|
|
63
|
+
if torch.compiler.is_compiling():
|
|
64
|
+
raise RuntimeError("Convolution offload does not support compiled execution")
|
|
65
|
+
value = args[0] if args else kwargs.get("input", kwargs.get("x"))
|
|
66
|
+
if not isinstance(value, torch.Tensor) or value.device != hook.execution_device:
|
|
67
|
+
raise ValueError("Convolution input must be on the configured execution device")
|
|
68
|
+
if value.device.type == "cuda" and torch.cuda.is_current_stream_capturing():
|
|
69
|
+
raise RuntimeError("Convolution offload does not support CUDA graph capture")
|
|
70
|
+
parameters = tuple(_module.parameters(recurse=False))
|
|
71
|
+
sources = tuple(parameter.data for parameter in parameters)
|
|
72
|
+
active = True
|
|
73
|
+
hook._linear_convolution_active = getattr(hook, "_linear_convolution_active", 0) + 1
|
|
74
|
+
try:
|
|
75
|
+
for parameter in parameters:
|
|
76
|
+
parameter.data = hook._to_input_device(
|
|
77
|
+
parameter, value, "convolution_parameter", cast_to_input_dtype=False
|
|
78
|
+
)
|
|
79
|
+
output = original(*args, **kwargs)
|
|
80
|
+
|
|
81
|
+
def borrowed(item):
|
|
82
|
+
if isinstance(item, torch.Tensor):
|
|
83
|
+
return any(
|
|
84
|
+
item.device == parameter.device
|
|
85
|
+
and item.untyped_storage().data_ptr() == parameter.untyped_storage().data_ptr()
|
|
86
|
+
for parameter in parameters
|
|
87
|
+
)
|
|
88
|
+
if isinstance(item, (tuple, list)):
|
|
89
|
+
return any(borrowed(child) for child in item)
|
|
90
|
+
if isinstance(item, dict):
|
|
91
|
+
return any(borrowed(child) for child in item.values())
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
if borrowed(output):
|
|
95
|
+
raise RuntimeError("Convolution output must not borrow temporary parameter storage")
|
|
96
|
+
return output
|
|
97
|
+
finally:
|
|
98
|
+
for parameter, source in zip(parameters, sources, strict=True):
|
|
99
|
+
parameter.data = source
|
|
100
|
+
hook._linear_convolution_active -= 1
|
|
101
|
+
active = False
|
|
102
|
+
|
|
103
|
+
hook._patched_modules.append((module, original))
|
|
104
|
+
hook.state.patched_module_count += 1
|
|
105
|
+
module.forward = forward.__get__(module, type(module))
|