File size: 12,670 Bytes
c1dc9b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""SplitZip support for the ``vmm_fast`` route (native DLL allocator).

Target: ``dynamic_offload.py::_prepare_vmm_fast_runtime`` where
``attach_model_linear_modules(...)`` (ddo-vmm-allocator, ``model_arena_adapter.py``)
returns a ``ModelArenaWeightStore`` whose native shard transport reads EXACTLY
``binding.nbytes`` raw bytes from the safetensors shard straight into the VMM
arena. Python never stages per-weight bytes on that path, so the staging-pool
interception (``splitzip_staging.py``) never sees it.

The seams that make a Python-only integration possible (verified against
ddo-vmm-allocator @ 70802e1, ``model_arena_adapter.py``):

1. All uploads are enqueued on a Python-owned stream:
   ``self._upload_stream = torch.cuda.Stream(device=device_ordinal)``.
2. ``native.copy_from_host_async(arena_offset, source, stream=...)`` is the
   Python-visible DMA used for CPU-source uploads — it copies exactly
   ``source.nbytes``, so a compressed payload can be DMA'd if it arrives as a
   pinned tensor of that size.
3. ``wait_for_compute(ready_event)`` accepts polymorphic tokens, including a
   plain ``torch.cuda.Event`` — a decode enqueued after the DMA on the upload
   stream is fenced correctly by returning an event recorded after it.

Strategy: replace ``store._native_shard_transport`` with
``SplitZipNativeShardTransport`` AFTER ``attach_model_linear_modules`` returns.
Per compressed binding we read the blob into a persistent pinned buffer, DMA it
into the arena range, decode the full BF16 weight in place on the upload
stream, and return a torch Event. Raw (uncached) bindings are delegated to the
inner transport unchanged. The native DLL is NOT modified.

Because native-shard bindings may carry no retained CPU tensor, cache entries
are additionally aliased to their safetensor slice identity at attach time
(``bind_slice_aliases``) and resolved at fault time via ``binding.file_slice``.

Hardware-verification points are listed in docs/developer/splitzip.md.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Callable

import torch

from .splitzip_codec import GpuSplitZipDecoder, PayloadMeta, triton_available
from .splitzip_shard_cache import SplitZipShardCache

# A resolved cache entry: (blob_path, meta, codebook)
_CacheHit = tuple[Any, PayloadMeta, Any]


def _resolve_arena_view(store: Any) -> Callable[[Any, int, int], torch.Tensor]:
    """Find a callable that yields a torch view over arena device memory.

    Tries the store, then the native handle. If your build names it
    differently, pass ``arena_view_fn`` to :func:`enable_splitzip_fast_transport`.
    """
    candidates = []
    for owner in (store, getattr(store, "native", None)):
        for name in ("arena_view", "arena_view_bytes", "view_arena", "arena_tensor_view"):
            fn = getattr(owner, name, None)
            if callable(fn):
                candidates.append(fn)
    if not candidates:
        raise RuntimeError(
            "SplitZip fast transport could not resolve an arena-view helper on the "
            "ModelArenaWeightStore or its native handle. Pass arena_view_fn=... to "
            "enable_splitzip_fast_transport (signature: (native, arena_offset, nbytes) "
            "-> contiguous torch.uint8 CUDA tensor)."
        )
    first = candidates[0]

    def arena_view_fn(native: Any, arena_offset: int, nbytes: int) -> torch.Tensor:
        view = first(native, arena_offset, nbytes)
        if not (torch.is_tensor(view) and view.is_cuda and view.is_contiguous()):
            raise RuntimeError("arena_view helper returned a non-CUDA or non-contiguous tensor")
        return view.reshape(-1) if view.dtype is torch.uint8 else view.reshape(-1).view(torch.uint8)

    return arena_view_fn


class SplitZipNativeShardTransport:
    """Wraps the store's ``_NativeShardTransport``; overrides ``upload_batch``.

    Contract with ``ModelArenaWeightStore.fault_and_copy_if_needed`` (the only
    consumer): called as ``upload_batch([binding], native, upload_stream)`` and
    its return value is handed to ``wait_for_compute``. We keep that contract —
    including the observed single-binding call pattern. For a mixed multi-
    binding batch we raise, because one return token cannot fence both the
    inner ring path and our decode; split the batch instead.
    """

    def __init__(
        self,
        inner: Any,
        shard_cache: SplitZipShardCache,
        store: Any,
        *,
        arena_view_fn: Callable[[Any, int, int], torch.Tensor] | None = None,
    ) -> None:
        if not triton_available():
            raise RuntimeError(
                "SplitZip fast transport requires the vendored Triton codec "
                "(_splitzip_vendor.codec_gpu); on Windows use the staging-pool route."
            )
        self._inner = inner
        self._shard_cache = shard_cache
        self._store = store
        self._device_id = getattr(store, "_device_ordinal", 0)
        self._decoder = GpuSplitZipDecoder(device_id=self._device_id)
        self._arena_view_fn = arena_view_fn or _resolve_arena_view(store)
        self._pinned: torch.Tensor | None = None  # persistent pinned staging, uint8
        self._dec_lut: dict[int, torch.Tensor] = {}  # id(codebook) -> GPU dec_lut
        self.stats = {"compressed_uploads": 0, "delegated_uploads": 0, "comp_bytes": 0, "raw_bytes": 0}

    # Everything except upload_batch delegates to the inner transport (ring
    # prefetch, slot management, ...). Prefetched raw reads for compressed
    # bindings are wasted work until the adapter learns to skip them; they are
    # harmless (the prefetch target is simply not consumed for those bindings).
    def __getattr__(self, name: str) -> Any:
        return getattr(self._inner, name)

    # -- cache lookup -------------------------------------------------------

    def _hit_for(self, binding: Any) -> _CacheHit | None:
        source = getattr(binding, "source", None)
        if source is not None:
            hit = self._shard_cache.lookup(source)
            if hit is not None:
                return hit
        # Preferred on the native-shard path: bindings may carry no retained
        # CPU tensor, so resolve via the safetensor slice identity aliased at
        # attach time (aliasing uses DDO's own offset convention).
        file_slice = getattr(binding, "file_slice", None)
        if file_slice is not None:
            return self._shard_cache.lookup_by_slice(
                Path(file_slice.path).name, file_slice.offset_bytes, file_slice.size_bytes
            )
        return None

    def _dec_lut_for(self, codebook: Any, device: torch.device) -> torch.Tensor:
        key = id(codebook)
        lut = self._dec_lut.get(key)
        if lut is None or lut.device != device:
            lut = codebook.dec_lut.to(device)
            self._dec_lut[key] = lut
        return lut

    def _pinned_for(self, nbytes: int) -> torch.Tensor:
        if self._pinned is None or self._pinned.numel() < nbytes:
            self._pinned = torch.empty(nbytes, dtype=torch.uint8, pin_memory=True)
        return self._pinned

    # -- the seam -----------------------------------------------------------

    def upload_batch(self, bindings: list[Any], native: Any, stream: Any) -> Any:
        hits = [(b, self._hit_for(b)) for b in bindings]
        if not any(hit is not None for _b, hit in hits):
            self.stats["delegated_uploads"] += len(bindings)
            return self._inner.upload_batch(bindings, native, stream)
        if len(bindings) > 1:
            raise NotImplementedError(
                "SplitZipNativeShardTransport observed a multi-binding upload_batch with "
                "compressed content. The adapter's known call pattern is one binding per "
                "call; either split the batch or extend this wrapper."
            )
        binding, hit = hits[0]
        return self._upload_compressed(binding, hit, native, stream)

    def _upload_compressed(self, binding: Any, hit: _CacheHit, native: Any, stream: Any) -> torch.cuda.Event:
        blob_path, meta, codebook = hit
        comp = meta.comp_bytes
        raw_bytes = meta.n * 2
        if comp > raw_bytes:
            raise RuntimeError(
                f"SplitZip payload exceeds the binding's arena range "
                f"({comp} > {raw_bytes}); the coverage gate should have skipped this tensor"
            )
        pinned = self._pinned_for(comp)
        with open(blob_path, "rb", buffering=0) as handle:
            read = handle.readinto(memoryview(pinned.numpy()).cast("B")[:comp])
        if read != comp:
            raise OSError(f"Short SplitZip blob read from {blob_path}: expected {comp}, got {read}")
        arena_offset = binding.offset  # verified: passed to native.copy_from_host_async
        with torch.cuda.stream(stream):
            # 1) DMA the compressed payload into the arena range (comp bytes).
            native.copy_from_host_async(arena_offset, pinned[:comp], stream=stream)
            # 2) Expand bitwise over the same range on the upload stream: the
            #    decoder first stashes arena[offset:offset+comp] to GPU scratch,
            #    then writes the full BF16 weight over the arena range.
            arena_u8 = self._arena_view_fn(native, arena_offset, raw_bytes)
            slot_bf16 = arena_u8.view(torch.bfloat16)
            self._decoder.decode_slot_into(
                slot_bf16, meta, self._dec_lut_for(codebook, arena_u8.device), stream=stream
            )
            # 3) Fence: wait_for_compute accepts a plain torch event; it must be
            #    recorded AFTER the decode so compute never sees compressed bytes.
            ready = torch.cuda.Event()
            ready.record(stream)
        self.stats["compressed_uploads"] += 1
        self.stats["comp_bytes"] += comp
        self.stats["raw_bytes"] += raw_bytes
        return ready


def bind_slice_aliases(root: Any, shard_cache: SplitZipShardCache) -> int:
    """Alias cached content keys to safetensor slice identities, attach time only.

    Walks ``root``'s parameters while the loader CPU tensors are alive, reads
    each one's ``SafetensorFileSlice`` from the registry DDO bound as
    ``module._ddo_safetensor_slices``, and records the
    (shard name, offset_bytes, size_bytes) triple next to the content key.
    After this, ``SplitZipNativeShardTransport`` can resolve compressed
    bindings that carry no retained CPU tensor.

    Call BEFORE loader tensors are released (i.e. during/just after attach);
    returns the number of aliases created.
    """
    registry = getattr(root, "_ddo_safetensor_slices", None)
    if registry is None:
        return 0
    lookup = getattr(registry, "lookup", None)
    if not callable(lookup):
        return 0
    aliases = 0
    for _name, parameter in root.named_parameters(remove_duplicate=False):
        tensor = parameter.data
        if tensor is None or tensor.device.type != "cpu":
            continue
        file_slice = lookup(tensor)
        if file_slice is None:
            continue
        if shard_cache.alias_slice(
            tensor, Path(file_slice.path).name, file_slice.offset_bytes, file_slice.size_bytes
        ):
            aliases += 1
    return aliases


def enable_splitzip_fast_transport(
    store: Any,
    shard_cache: SplitZipShardCache,
    *,
    arena_view_fn: Callable[[Any, int, int], torch.Tensor] | None = None,
) -> SplitZipNativeShardTransport:
    """Swap SplitZip into a ``ModelArenaWeightStore``'s native shard transport.

    Call right after ``report, store = attach_model_linear_modules(...)`` in
    ``_prepare_vmm_fast_runtime`` when ``native_transport_kwargs`` is non-empty
    (i.e. the native DLL transport is active), and after
    :func:`bind_slice_aliases` while the loader tensors are still alive.
    Requires the vendored Triton codec; raises otherwise (the CPU fallback
    cannot run on this path because Python never stages per-weight bytes here).

    The native DLL is unchanged; this only re-routes file reads for compressed
    bindings through the Python-visible DMA seam and adds an in-place GPU
    decode on the upload stream.
    """
    inner = getattr(store, "_native_shard_transport", None)
    if inner is None:
        raise RuntimeError(
            "store has no _native_shard_transport: native transport is not active. "
            "Enable vmm_native_transport, or use the SplitZipStagingPool route instead."
        )
    wrapper = SplitZipNativeShardTransport(inner, shard_cache, store, arena_view_fn=arena_view_fn)
    store._native_shard_transport = wrapper
    return wrapper