ddo-vmm-allocator 0.1.0rc2__py3-none-win_amd64.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_vmm_allocator/__init__.py +45 -0
- ddo_vmm_allocator/_library.py +25 -0
- ddo_vmm_allocator/component_arena_adapter.py +247 -0
- ddo_vmm_allocator/diffusers_adapter.py +38 -0
- ddo_vmm_allocator/execution_auxiliary.py +106 -0
- ddo_vmm_allocator/model_arena_adapter.py +2430 -0
- ddo_vmm_allocator/native/win32/artifact.json +26 -0
- ddo_vmm_allocator/native/win32/ddo_vmm.dll +0 -0
- ddo_vmm_allocator/native.py +1146 -0
- ddo_vmm_allocator/platform.py +42 -0
- ddo_vmm_allocator/quantized_arena_adapter.py +240 -0
- ddo_vmm_allocator/quantized_owners.py +116 -0
- ddo_vmm_allocator/quantized_payload.py +153 -0
- ddo_vmm_allocator/source.py +143 -0
- ddo_vmm_allocator/source_cache.py +435 -0
- ddo_vmm_allocator/tensor_owners.py +163 -0
- ddo_vmm_allocator/tensor_view.py +80 -0
- ddo_vmm_allocator/timeline.py +158 -0
- ddo_vmm_allocator/torch_allocator.py +67 -0
- ddo_vmm_allocator/torch_module_adapter.py +334 -0
- ddo_vmm_allocator/triton_execution.py +180 -0
- ddo_vmm_allocator/triton_execution_compile.py +63 -0
- ddo_vmm_allocator/triton_qk_rope.py +148 -0
- ddo_vmm_allocator/weight_arena.py +756 -0
- ddo_vmm_allocator-0.1.0rc2.dist-info/METADATA +48 -0
- ddo_vmm_allocator-0.1.0rc2.dist-info/RECORD +28 -0
- ddo_vmm_allocator-0.1.0rc2.dist-info/WHEEL +4 -0
- ddo_vmm_allocator-0.1.0rc2.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Portable foundations for the DDO CUDA VMM allocator."""
|
|
2
|
+
|
|
3
|
+
from .platform import CudaVmmCapabilities, detect_cuda_vmm_capabilities
|
|
4
|
+
from .tensor_owners import TensorOwnerGroup, capture_model_tensor_owners
|
|
5
|
+
|
|
6
|
+
# Bootstrap imports torch_allocator through this package before allocator
|
|
7
|
+
# installation. Adapter imports may transitively query CUDA via optional
|
|
8
|
+
# quantization backends; retain the public API without eagerly importing them.
|
|
9
|
+
_ADAPTER_EXPORTS = {
|
|
10
|
+
"TransformerAttachReport": "diffusers_adapter",
|
|
11
|
+
"attach_transformer_blocks": "diffusers_adapter",
|
|
12
|
+
"ModelArenaAttachReport": "model_arena_adapter",
|
|
13
|
+
"ModelArenaModuleAdapter": "model_arena_adapter",
|
|
14
|
+
"ModelArenaWeightStore": "model_arena_adapter",
|
|
15
|
+
"attach_model_linear_modules": "model_arena_adapter",
|
|
16
|
+
"inspect_model_linear_layout": "model_arena_adapter",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def __getattr__(name):
|
|
21
|
+
if name not in _ADAPTER_EXPORTS:
|
|
22
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
23
|
+
from importlib import import_module
|
|
24
|
+
|
|
25
|
+
value = getattr(import_module(f".{_ADAPTER_EXPORTS[name]}", __name__), name)
|
|
26
|
+
globals()[name] = value
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def __dir__():
|
|
31
|
+
return sorted(set(globals()) | set(_ADAPTER_EXPORTS))
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"CudaVmmCapabilities",
|
|
35
|
+
"TensorOwnerGroup",
|
|
36
|
+
"capture_model_tensor_owners",
|
|
37
|
+
"detect_cuda_vmm_capabilities",
|
|
38
|
+
"TransformerAttachReport",
|
|
39
|
+
"attach_transformer_blocks",
|
|
40
|
+
"ModelArenaAttachReport",
|
|
41
|
+
"ModelArenaModuleAdapter",
|
|
42
|
+
"ModelArenaWeightStore",
|
|
43
|
+
"attach_model_linear_modules",
|
|
44
|
+
"inspect_model_linear_layout",
|
|
45
|
+
]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""DLL loading diagnostics without importing Torch or calling CUDA exports."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import platform
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def load_library(path, error_type):
|
|
8
|
+
loader = ctypes.WinDLL if platform.system() == "Windows" else ctypes.CDLL
|
|
9
|
+
try:
|
|
10
|
+
return loader(str(path))
|
|
11
|
+
except OSError as error:
|
|
12
|
+
raise error_type(
|
|
13
|
+
f"Cannot load native VMM library '{path}': {error}. "
|
|
14
|
+
"Check library architecture and required DLL dependencies."
|
|
15
|
+
) from error
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def require_exports(library, path, names, error_type):
|
|
19
|
+
missing = [name for name in names if getattr(library, name, None) is None]
|
|
20
|
+
if missing:
|
|
21
|
+
raise error_type(
|
|
22
|
+
f"Incompatible native VMM library '{path}'; missing exports: "
|
|
23
|
+
f"{', '.join(missing)}. Use a DLL built for this allocator package. "
|
|
24
|
+
"The selected library will not be replaced automatically."
|
|
25
|
+
)
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Opt-in component ownership using the existing native fault/unit machinery.
|
|
2
|
+
|
|
3
|
+
No architecture names, parameter CPU cache or Python residency policy. Initial
|
|
4
|
+
scope: disjoint execution units, immutable file-backed parameters, bounded
|
|
5
|
+
device buffers and one compute stream. Legacy Linear attachment is unchanged.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
from .model_arena_adapter import (
|
|
11
|
+
ModelArenaError, ModelArenaAttachReport, ModelArenaModuleAdapter,
|
|
12
|
+
ModelArenaWeightStore, NativeExecutionBuffers, _ModuleBinding,
|
|
13
|
+
_TensorBinding, _FileTensorDescriptor, _align_up,
|
|
14
|
+
)
|
|
15
|
+
from .tensor_owners import capture_model_tensor_owners
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ComponentLayout:
|
|
20
|
+
groups: tuple
|
|
21
|
+
parameters: tuple # group, offset, descriptor
|
|
22
|
+
units: tuple # name, module, parameter group indexes
|
|
23
|
+
payload_bytes: int
|
|
24
|
+
buffer_bytes: int
|
|
25
|
+
component_lifetime_parameters: tuple = () # group, immutable descriptor
|
|
26
|
+
|
|
27
|
+
def snapshot(self):
|
|
28
|
+
result = {"schema_version": 1, "parameter_groups": len(self.parameters),
|
|
29
|
+
"buffer_groups": sum(group.kind == "buffer" for group in self.groups),
|
|
30
|
+
"payload_bytes": self.payload_bytes, "buffer_bytes": self.buffer_bytes,
|
|
31
|
+
"execution_units": len(self.units), "lookahead": False}
|
|
32
|
+
if self.component_lifetime_parameters:
|
|
33
|
+
result.update(component_lifetime_parameter_groups=len(self.component_lifetime_parameters),
|
|
34
|
+
component_lifetime_parameter_bytes=sum(g.nbytes for g, _ in self.component_lifetime_parameters))
|
|
35
|
+
return result
|
|
36
|
+
|
|
37
|
+
def capacity_snapshot(self):
|
|
38
|
+
"""Detached loaded-source geometry; no native allocation/admission."""
|
|
39
|
+
units = []
|
|
40
|
+
for name, _, indices in self.units:
|
|
41
|
+
payload = 0
|
|
42
|
+
for index in indices:
|
|
43
|
+
payload = _align_up(payload, 512) + self.parameters[index][0].nbytes
|
|
44
|
+
units.append({"name": name, "parameter_groups": len(indices),
|
|
45
|
+
"execution_slot_payload_bytes": payload})
|
|
46
|
+
largest = max(unit["execution_slot_payload_bytes"] for unit in units)
|
|
47
|
+
return {**self.snapshot(), "observation": "loaded_source_preflight",
|
|
48
|
+
"native_admission_validated": False,
|
|
49
|
+
"unique_parameter_bytes": (sum(group.nbytes for group, _, _ in self.parameters)
|
|
50
|
+
+ sum(g.nbytes for g, _ in self.component_lifetime_parameters)),
|
|
51
|
+
"execution_slot_count": 2, "execution_slot_payload_bytes": largest,
|
|
52
|
+
"execution_slot_total_payload_bytes": 2 * largest,
|
|
53
|
+
"units": units}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def discover_component_layout(root, file_slices, *, buffer_limit_bytes, _prepared_groups=None,
|
|
57
|
+
_component_lifetime_root_limit_bytes=None):
|
|
58
|
+
"""Preflight before any allocator operation or module mutation."""
|
|
59
|
+
if type(buffer_limit_bytes) is not int or buffer_limit_bytes < 0:
|
|
60
|
+
raise ValueError("component buffer limit must be a non-negative byte integer")
|
|
61
|
+
if (_component_lifetime_root_limit_bytes is not None
|
|
62
|
+
and (type(_component_lifetime_root_limit_bytes) is not int
|
|
63
|
+
or _component_lifetime_root_limit_bytes < 0)):
|
|
64
|
+
raise ValueError("component-lifetime root limit must be a non-negative byte integer")
|
|
65
|
+
groups = capture_model_tensor_owners(root) if _prepared_groups is None else _prepared_groups
|
|
66
|
+
modules = dict(root.named_modules())
|
|
67
|
+
list_items = {}
|
|
68
|
+
import torch
|
|
69
|
+
|
|
70
|
+
if any(module.training for module in modules.values()):
|
|
71
|
+
raise ValueError("component ownership requires eval mode for immutable inference")
|
|
72
|
+
for path, module in modules.items():
|
|
73
|
+
if isinstance(module, (torch.nn.Embedding, torch.nn.EmbeddingBag)) and module.max_norm is not None:
|
|
74
|
+
raise ValueError("in-place embedding renormalization is incompatible with immutable native sources")
|
|
75
|
+
if isinstance(module, torch.nn.ModuleList):
|
|
76
|
+
for index, child in enumerate(module):
|
|
77
|
+
list_items[f"{path}.{index}" if path else str(index)] = child
|
|
78
|
+
parameters, units, offset = [], {}, 0
|
|
79
|
+
buffers = 0
|
|
80
|
+
lifetime, lifetime_bytes = [], 0
|
|
81
|
+
for group in groups:
|
|
82
|
+
source = group.loader_tensor
|
|
83
|
+
if source.device.type != "cpu" or not source.is_contiguous() or not source.numel():
|
|
84
|
+
raise ValueError("component ownership requires materialized contiguous nonempty CPU tensors")
|
|
85
|
+
if group.kind == "buffer":
|
|
86
|
+
buffers += group.nbytes
|
|
87
|
+
continue
|
|
88
|
+
descriptor = file_slices.lookup(source) if file_slices is not None else None
|
|
89
|
+
if descriptor is None:
|
|
90
|
+
raise ValueError(f"component parameter has no immutable file source: {group.snapshot()['names']}")
|
|
91
|
+
if _component_lifetime_root_limit_bytes is not None and any(owner is root for owner, _, _ in group.owners):
|
|
92
|
+
if not all(owner is root for owner, _, _ in group.owners) or type(source) is not torch.nn.Parameter:
|
|
93
|
+
raise ValueError("component-lifetime root state requires plain parameters with root-only owners")
|
|
94
|
+
lifetime.append((group, descriptor))
|
|
95
|
+
lifetime_bytes += group.nbytes
|
|
96
|
+
continue
|
|
97
|
+
offset = _align_up(offset, max(source.element_size(), 256))
|
|
98
|
+
position = len(parameters)
|
|
99
|
+
parameters.append((group, offset, descriptor))
|
|
100
|
+
offset += group.nbytes
|
|
101
|
+
for owner, key, names in group.owners:
|
|
102
|
+
path = names[0].rsplit(".", 1)[0] if "." in names[0] else ""
|
|
103
|
+
ancestors = [".".join(path.split(".")[:index]) for index in range(1, len(path.split(".")) + 1)]
|
|
104
|
+
unit = next((parent for parent in ancestors if parent in list_items), path)
|
|
105
|
+
execution_owner = getattr(owner, "_ddo_execution_module", owner)
|
|
106
|
+
entry = units.setdefault(unit, [list_items.get(unit, execution_owner), []])
|
|
107
|
+
if position not in entry[1]:
|
|
108
|
+
entry[1].append(position)
|
|
109
|
+
if not parameters:
|
|
110
|
+
raise ValueError("component has no file-backed parameters")
|
|
111
|
+
if buffers > buffer_limit_bytes:
|
|
112
|
+
raise ValueError("component buffers exceed the explicit device-buffer limit")
|
|
113
|
+
if (_component_lifetime_root_limit_bytes is not None
|
|
114
|
+
and buffers + lifetime_bytes > _component_lifetime_root_limit_bytes):
|
|
115
|
+
raise ValueError("component-lifetime root state and buffers exceed the explicit component limit")
|
|
116
|
+
names = list(units)
|
|
117
|
+
if "" in units and len(units) > 1:
|
|
118
|
+
raise ValueError("overlapping direct-parameter execution units are not supported")
|
|
119
|
+
# A parameter-owning parent consumes its parameter across child calls.
|
|
120
|
+
# Enclose descendant units in that parent rather than swapping native
|
|
121
|
+
# storage underneath an active invocation. This is execution geometry,
|
|
122
|
+
# not an architecture-specific residency or cache policy.
|
|
123
|
+
merged = {}
|
|
124
|
+
for name, (unit_module, indices) in units.items():
|
|
125
|
+
ancestors = [parent for parent in names if parent and name.startswith(parent + ".")]
|
|
126
|
+
enclosing = min(ancestors, key=lambda path: len(path.split("."))) if ancestors else name
|
|
127
|
+
entry = merged.setdefault(enclosing, [units[enclosing][0], []])
|
|
128
|
+
for index in indices:
|
|
129
|
+
if index not in entry[1]:
|
|
130
|
+
entry[1].append(index)
|
|
131
|
+
units = merged
|
|
132
|
+
return ComponentLayout(groups, tuple(parameters),
|
|
133
|
+
tuple((name, module, tuple(indices)) for name, (module, indices) in units.items()),
|
|
134
|
+
offset, buffers, tuple(lifetime))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class ComponentArenaAdapter(ModelArenaModuleAdapter):
|
|
138
|
+
def __init__(self, store):
|
|
139
|
+
super().__init__(store)
|
|
140
|
+
self._ownership_groups = ()
|
|
141
|
+
self._retirement_event = None
|
|
142
|
+
self.component_report = {}
|
|
143
|
+
|
|
144
|
+
def _move_buffer(self, source):
|
|
145
|
+
return source.to(f"cuda:{self.store._device_ordinal}")
|
|
146
|
+
|
|
147
|
+
def _native_view(self, group, source, offset):
|
|
148
|
+
stable, signature = self.store.stable_tensor(offset=offset, source=source)
|
|
149
|
+
if stable.device.type != "cuda":
|
|
150
|
+
raise ModelArenaError("component publication requires a CUDA native view, not a retained CPU source")
|
|
151
|
+
return stable, signature
|
|
152
|
+
|
|
153
|
+
def _completion_event(self):
|
|
154
|
+
import torch
|
|
155
|
+
|
|
156
|
+
event = torch.cuda.Event(enable_timing=False)
|
|
157
|
+
event.record(torch.cuda.current_stream(self.store._device_ordinal))
|
|
158
|
+
return event
|
|
159
|
+
|
|
160
|
+
def _publish_component_lifetime_parameters(self, parameters):
|
|
161
|
+
if parameters:
|
|
162
|
+
raise ModelArenaError("component-lifetime root state requires an explicit dedicated adapter")
|
|
163
|
+
|
|
164
|
+
def attach_component(self, layout):
|
|
165
|
+
self._ownership_groups = layout.groups
|
|
166
|
+
self.component_report = layout.snapshot()
|
|
167
|
+
bindings = []
|
|
168
|
+
spans = tuple((offset, group.nbytes) for group, offset, _ in layout.parameters)
|
|
169
|
+
with self.store.view_setup(spans):
|
|
170
|
+
for group, offset, descriptor in layout.parameters:
|
|
171
|
+
source = group.loader_tensor
|
|
172
|
+
stable, signature = self._native_view(group, source, offset)
|
|
173
|
+
metadata = _FileTensorDescriptor(group.shape, group.dtype, group.nbytes, source.element_size())
|
|
174
|
+
group.publish(stable)
|
|
175
|
+
owner, key, names = group.owners[0]
|
|
176
|
+
binding = _TensorBinding(owner, key, metadata, descriptor, stable, offset,
|
|
177
|
+
group.nbytes, signature=signature, label=names[0])
|
|
178
|
+
bindings.append(binding)
|
|
179
|
+
self._address_bindings[stable.data_ptr()] = binding
|
|
180
|
+
self.store._source_stats["file_backed_bindings"] += 1
|
|
181
|
+
self.store._source_stats["file_backed_bytes"] += group.nbytes
|
|
182
|
+
del source
|
|
183
|
+
for group in layout.groups:
|
|
184
|
+
if group.kind == "buffer":
|
|
185
|
+
group.publish(self._move_buffer(group.loader_tensor))
|
|
186
|
+
self._publish_component_lifetime_parameters(layout.component_lifetime_parameters)
|
|
187
|
+
for name, module, indices in layout.units:
|
|
188
|
+
state = _ModuleBinding(name, module, [bindings[index] for index in indices], {},
|
|
189
|
+
guard_reentry=True)
|
|
190
|
+
self._bindings.append(state)
|
|
191
|
+
self._execution_units.append(state)
|
|
192
|
+
# Geometry only: native slots/admission retain the existing GPU ceiling.
|
|
193
|
+
# No speculative lookahead in the initial component ownership contract.
|
|
194
|
+
if self.store._streaming_enabled and self.store._native_shard_transport is not None:
|
|
195
|
+
maximum = 0
|
|
196
|
+
for unit in self._execution_units:
|
|
197
|
+
size = 0
|
|
198
|
+
for binding in unit.tensors:
|
|
199
|
+
size = _align_up(size, 512) + binding.nbytes
|
|
200
|
+
maximum = max(maximum, size)
|
|
201
|
+
self.store.execution_buffer = NativeExecutionBuffers(self.store, maximum)
|
|
202
|
+
for unit in self._execution_units:
|
|
203
|
+
self._register_execution_unit(unit)
|
|
204
|
+
self.store._native_shard_transport.prepare_sources(self._execution_units)
|
|
205
|
+
return ModelArenaAttachReport("component_parameters", len(layout.units), len(bindings),
|
|
206
|
+
len(layout.units), layout.payload_bytes,
|
|
207
|
+
self.store.virtual_bytes, self.store.page_bytes, self)
|
|
208
|
+
|
|
209
|
+
def close(self):
|
|
210
|
+
if any(unit.active for unit in self._execution_units):
|
|
211
|
+
raise ModelArenaError("cannot close a component with an active execution unit")
|
|
212
|
+
super().close() # Last upload/compute users and pins must retire first.
|
|
213
|
+
published = [group for group in self._ownership_groups if group.state in ("published", "retiring")]
|
|
214
|
+
if published:
|
|
215
|
+
if self._retirement_event is None:
|
|
216
|
+
self._retirement_event = self._completion_event()
|
|
217
|
+
self._retirement_event.synchronize()
|
|
218
|
+
for group in published:
|
|
219
|
+
if not group.retire(self._retirement_event):
|
|
220
|
+
raise ModelArenaError("component final-consumer completion is unproven")
|
|
221
|
+
for group in self._ownership_groups:
|
|
222
|
+
if group.state == "publication_failed":
|
|
223
|
+
group.rollback_failed_publication()
|
|
224
|
+
self._ownership_groups = ()
|
|
225
|
+
self._retirement_event = None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def attach_component_parameters(root, library, *, component_buffer_limit_bytes, **store_kwargs):
|
|
229
|
+
if not store_kwargs.get("native_transport_slot_size_bytes"):
|
|
230
|
+
raise ValueError("component ownership requires native immutable file transport")
|
|
231
|
+
layout = discover_component_layout(root, store_kwargs.get("file_slices"),
|
|
232
|
+
buffer_limit_bytes=component_buffer_limit_bytes)
|
|
233
|
+
store = ModelArenaWeightStore(library, payload_bytes=layout.payload_bytes, **store_kwargs)
|
|
234
|
+
adapter = ComponentArenaAdapter(store)
|
|
235
|
+
try:
|
|
236
|
+
return adapter.attach_component(layout), store
|
|
237
|
+
except BaseException as error:
|
|
238
|
+
# Never close backing if alias/event cleanup cannot prove release.
|
|
239
|
+
from .source_cache import _run_cleanup_preserving_error
|
|
240
|
+
|
|
241
|
+
def cleanup():
|
|
242
|
+
adapter.close()
|
|
243
|
+
store.close()
|
|
244
|
+
_run_cleanup_preserving_error(cleanup, "component attachment cleanup", error)
|
|
245
|
+
# Retain the owning adapter for diagnostics/retry after cleanup failure.
|
|
246
|
+
error.component_adapter = adapter
|
|
247
|
+
raise
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Optional integration helpers for Diffusers-style transformer modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .torch_module_adapter import VmmModuleAdapter
|
|
9
|
+
from .weight_arena import VmmWeightArena
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class TransformerAttachReport:
|
|
14
|
+
pattern: str
|
|
15
|
+
attached_groups: int
|
|
16
|
+
adapter: VmmModuleAdapter
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def attach_transformer_blocks(
|
|
20
|
+
transformer: Any,
|
|
21
|
+
arena: VmmWeightArena,
|
|
22
|
+
*,
|
|
23
|
+
module_pattern: str = r"transformer_blocks\.\d+$",
|
|
24
|
+
recursive: bool = True,
|
|
25
|
+
) -> TransformerAttachReport:
|
|
26
|
+
"""Attach matching transformer blocks to an explicit VMM arena.
|
|
27
|
+
|
|
28
|
+
The function only relies on the standard ``torch.nn.Module`` traversal API,
|
|
29
|
+
so Diffusers remains an optional caller dependency. It deliberately does
|
|
30
|
+
not install a global PyTorch allocator or remove existing Diffusers hooks.
|
|
31
|
+
"""
|
|
32
|
+
adapter = VmmModuleAdapter(arena)
|
|
33
|
+
names = adapter.attach_module_tree(transformer, module_pattern, recursive=recursive)
|
|
34
|
+
return TransformerAttachReport(
|
|
35
|
+
pattern=module_pattern,
|
|
36
|
+
attached_groups=len(names),
|
|
37
|
+
adapter=adapter,
|
|
38
|
+
)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Opt-in auxiliary ownership within existing dense execution units.
|
|
2
|
+
|
|
3
|
+
Discovery is CPU-only. Bytes join the existing arena, immutable source batches
|
|
4
|
+
and event-fenced execution slots; no separate residency cache is introduced.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .tensor_owners import capture_model_tensor_owners
|
|
8
|
+
from .component_arena_adapter import ComponentArenaAdapter
|
|
9
|
+
from .model_arena_adapter import ModelArenaError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ExecutionAuxiliaryAdapter(ComponentArenaAdapter):
|
|
13
|
+
"""Dense scheduling with existing alias retirement and native event fences."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, store, groups, small_tensor_threshold_bytes=16 * 1024):
|
|
16
|
+
super().__init__(store)
|
|
17
|
+
self._ownership_groups = groups
|
|
18
|
+
self.auxiliary_report = {
|
|
19
|
+
"schema_version": 1, "parameter_groups": len(groups),
|
|
20
|
+
"parameter_bytes": sum(group.nbytes for group in groups),
|
|
21
|
+
"budget_policy": "existing_native_ceiling", "residency_cache": False,
|
|
22
|
+
"preserved_small_tensor_threshold_bytes": small_tensor_threshold_bytes,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
def _register_execution_unit(self, state):
|
|
26
|
+
# Reuse the proven component boundary for cooperative BaseException
|
|
27
|
+
# cleanup and output-view/reentry guards, without changing scheduling.
|
|
28
|
+
state.guard_reentry = True
|
|
29
|
+
return super()._register_execution_unit(state)
|
|
30
|
+
|
|
31
|
+
def _publish_auxiliary_view(self, group, stable, file_slice):
|
|
32
|
+
if stable.device.type != "cuda" or file_slice is None:
|
|
33
|
+
raise ModelArenaError("auxiliary ownership requires a file-backed CUDA native view")
|
|
34
|
+
group.publish(stable)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def discover_execution_auxiliary_layout(root, pattern, file_slices, *, small_tensor_threshold_bytes=16 * 1024):
|
|
38
|
+
"""Include residual direct parameters in selected units, once per alias.
|
|
39
|
+
|
|
40
|
+
Aliases crossing unit boundaries, selected Linear owners or distinct overlapping
|
|
41
|
+
storage objects are refused before mutation. Parameters within the existing
|
|
42
|
+
small-tensor contract, buffers and out-of-unit parameters retain their route.
|
|
43
|
+
This deliberately does not infer arbitrary graphs.
|
|
44
|
+
"""
|
|
45
|
+
import torch
|
|
46
|
+
from .model_arena_adapter import _discover_linear_layout, _align_up
|
|
47
|
+
|
|
48
|
+
if type(small_tensor_threshold_bytes) is not int or small_tensor_threshold_bytes < 0:
|
|
49
|
+
raise ValueError("small tensor threshold must be a non-negative integer byte count")
|
|
50
|
+
|
|
51
|
+
selected, units, payload = _discover_linear_layout(root, pattern)
|
|
52
|
+
unit_modules = {name: module for name, module in units.values()}
|
|
53
|
+
groups = capture_model_tensor_owners(root)
|
|
54
|
+
auxiliary = {}
|
|
55
|
+
added = []
|
|
56
|
+
seen_modules = {id(module) for _, module in selected}
|
|
57
|
+
for group in groups:
|
|
58
|
+
if group.kind != "parameter" or group.nbytes <= small_tensor_threshold_bytes:
|
|
59
|
+
continue
|
|
60
|
+
locations = []
|
|
61
|
+
for owner, key, names in group.owners:
|
|
62
|
+
for name in names:
|
|
63
|
+
path = name.rsplit(".", 1)[0] if "." in name else ""
|
|
64
|
+
unit = next((name for name in unit_modules
|
|
65
|
+
if path == name or path.startswith(name + ".")), None)
|
|
66
|
+
locations.append((owner, key, path, unit))
|
|
67
|
+
candidates = [item for item in locations
|
|
68
|
+
if item[3] is not None and not isinstance(item[0], torch.nn.Linear)]
|
|
69
|
+
if not candidates:
|
|
70
|
+
continue
|
|
71
|
+
if any(item[3] != candidates[0][3] or isinstance(item[0], torch.nn.Linear)
|
|
72
|
+
for item in locations):
|
|
73
|
+
raise ValueError("auxiliary aliases must stay within one non-Linear execution unit")
|
|
74
|
+
source = group.loader_tensor
|
|
75
|
+
if any(owner.training for owner, _, _, _ in locations):
|
|
76
|
+
raise ValueError("auxiliary ownership requires eval mode")
|
|
77
|
+
if source.device.type != "cpu" or not source.numel() or not source.is_contiguous():
|
|
78
|
+
raise ValueError("auxiliary sources must be nonempty contiguous CPU parameters")
|
|
79
|
+
if file_slices is None or file_slices.lookup(source) is None:
|
|
80
|
+
raise ValueError("auxiliary parameter requires an immutable file source")
|
|
81
|
+
start, end = source.data_ptr(), source.data_ptr() + group.nbytes
|
|
82
|
+
for other in groups:
|
|
83
|
+
if other is group:
|
|
84
|
+
continue
|
|
85
|
+
value = other.loader_tensor
|
|
86
|
+
if value.device.type == "cpu" and value.numel():
|
|
87
|
+
storage = value.untyped_storage()
|
|
88
|
+
low = storage.data_ptr()
|
|
89
|
+
high = low + storage.nbytes()
|
|
90
|
+
if start < high and low < end:
|
|
91
|
+
raise ValueError("distinct auxiliary storage aliases are unsupported")
|
|
92
|
+
owner, key, path, unit = candidates[0]
|
|
93
|
+
auxiliary[(id(owner), key)] = group
|
|
94
|
+
if id(owner) not in seen_modules:
|
|
95
|
+
added.append((path, owner))
|
|
96
|
+
seen_modules.add(id(owner))
|
|
97
|
+
units[path] = (unit, unit_modules[unit])
|
|
98
|
+
expanded = tuple(selected) + tuple(added)
|
|
99
|
+
# Match attachment order and alignment exactly, including unique aliases.
|
|
100
|
+
payload = 0
|
|
101
|
+
from .model_arena_adapter import _layout_parameter_items
|
|
102
|
+
for _, module in expanded:
|
|
103
|
+
for _, parameter in _layout_parameter_items(module, auxiliary):
|
|
104
|
+
payload = _align_up(payload, max(parameter.element_size(), 256))
|
|
105
|
+
payload += parameter.numel() * parameter.element_size()
|
|
106
|
+
return expanded, units, payload, auxiliary
|