"""SplitZip compressed shard cache for the DDO VMM routes. One-time build: calibrate a per-tensor Top-16 exponent codebook on the real weight tensors (paper protocol: offline calibration, per-tensor granularity, coverage-gated at >=0.99), encode each BF16 weight to the aligned SplitZip payload, and write one blob per tensor plus a manifest. Runtime: two lookup modes. - Content key (SHA-1 of the weight bytes): used wherever the live CPU tensor is available (staging-pool route, builder verification). - Slice key (shard file name, offset_bytes, size_bytes): used by the vmm_fast native-shard route, where bindings carry no retained CPU tensor. Slice keys are aliased at attach time via ``alias_slice`` while the loader tensors are still alive, and persisted in the manifest. Cache dir layout: /manifest.json /blobs/.bin """ from __future__ import annotations import hashlib import json import os import tempfile import threading from pathlib import Path import torch from .splitzip_codec import ( GpuSplitZipEncoder, PayloadMeta, SplitZipCodebook, calibrate_codebook, encode_torch, triton_available, ) COVERAGE_MIN = 0.99 CHUNK_SIZE = 1024 def _tensor_key(tensor: torch.Tensor) -> str: digest = hashlib.sha1() digest.update(str(tuple(tensor.shape)).encode()) digest.update(str(tensor.dtype).encode()) digest.update(str(tensor.numel() * tensor.element_size()).encode()) data = tensor.contiguous().view(torch.uint8).reshape(-1) digest.update(data.numpy().tobytes()) return digest.hexdigest() class SplitZipShardCacheBuilder: """Builds the compressed shard cache from the model's CPU weight tensors.""" def __init__(self, root: Path, *, coverage_min: float = COVERAGE_MIN) -> None: self.root = Path(root) self.coverage_min = float(coverage_min) def build(self, tensors: list[tuple[str, torch.Tensor]]) -> dict: """Encode every BF16 tensor; skip tensors that fail the coverage gate. ``tensors`` are (module_qualname, cpu_weight) pairs, e.g. from a named_modules() walk over the transformer. Returns a report; entries not in the manifest are served uncompressed by the transport. """ blobs = self.root / "blobs" blobs.mkdir(parents=True, exist_ok=True) encoder = GpuSplitZipEncoder() if triton_available() else None manifest: dict = {"format": 1, "chunk_size": CHUNK_SIZE, "coverage_min": self.coverage_min, "entries": {}} report = {"encoded": 0, "skipped_coverage": 0, "skipped_dtype": 0, "comp_bytes": 0, "raw_bytes": 0} for qualname, tensor in tensors: if tensor.dtype is not torch.bfloat16: report["skipped_dtype"] += 1 continue if not tensor.is_contiguous(): raise ValueError(f"{qualname}: SplitZip build requires contiguous weights") codebook, coverage = calibrate_codebook(tensor) if coverage < self.coverage_min: report["skipped_coverage"] += 1 continue if encoder is not None: payload, meta = encoder.encode(tensor, codebook) else: payload, meta = encode_torch(tensor, codebook, CHUNK_SIZE) key = _tensor_key(tensor) blob_path = blobs / f"{key}.bin" fd, tmp = tempfile.mkstemp(dir=blobs) try: with os.fdopen(fd, "wb") as handle: handle.write(payload) os.replace(tmp, blob_path) except BaseException: with contextlib_suppress(): os.unlink(tmp) raise manifest["entries"][key] = { "qualname": qualname, "blob": f"blobs/{key}.bin", "codebook": codebook.to_json(), "meta": meta.to_json(), "raw_bytes": tensor.numel() * tensor.element_size(), "slice_keys": [], } report["encoded"] += 1 report["comp_bytes"] += meta.comp_bytes report["raw_bytes"] += tensor.numel() * tensor.element_size() report["ratio"] = (report["comp_bytes"] / report["raw_bytes"]) if report["raw_bytes"] else None _write_manifest(self.root, manifest) return report def contextlib_suppress(): import contextlib return contextlib.suppress(OSError) def _write_manifest(root: Path, manifest: dict) -> None: fd, tmp = tempfile.mkstemp(dir=root) try: with os.fdopen(fd, "w") as handle: json.dump(manifest, handle) os.replace(tmp, root / "manifest.json") except BaseException: with contextlib_suppress(): os.unlink(tmp) raise class SplitZipShardCache: """Runtime lookup over a built cache; safe to share across staging calls. ``alias_slice`` is the only mutation and is persisting to the manifest, so concurrent readers either see an entry or not — never a partial one. """ def __init__(self, root: Path) -> None: self.root = Path(root) manifest_path = self.root / "manifest.json" if not manifest_path.is_file(): raise FileNotFoundError(f"SplitZip shard cache missing {manifest_path}") with open(manifest_path) as handle: self._manifest = json.load(handle) self.chunk_size = int(self._manifest.get("chunk_size", CHUNK_SIZE)) self._entries: dict[str, dict] = self._manifest["entries"] self._slice_index: dict[tuple[str, int, int], str] = {} for key, entry in self._entries.items(): for slice_key in entry.get("slice_keys", []): self._slice_index[(slice_key[0], int(slice_key[1]), int(slice_key[2]))] = key self._lock = threading.RLock() # -- lookup ------------------------------------------------------------- def _hit(self, key: str) -> tuple[Path, PayloadMeta, SplitZipCodebook] | None: entry = self._entries.get(key) if entry is None: return None meta = PayloadMeta.from_json(entry["meta"]) codebook = SplitZipCodebook.from_json(entry["codebook"]) return self.root / entry["blob"], meta, codebook def lookup(self, tensor: torch.Tensor) -> tuple[Path, PayloadMeta, SplitZipCodebook] | None: if tensor.dtype is not torch.bfloat16: return None with self._lock: return self._hit(_tensor_key(tensor)) def lookup_by_slice(self, shard_name: str, offset_bytes: int, size_bytes: int) -> tuple[Path, PayloadMeta, SplitZipCodebook] | None: """Slice-key lookup for the vmm_fast native-shard route (no CPU tensor).""" with self._lock: key = self._slice_index.get((shard_name, int(offset_bytes), int(size_bytes))) return self._hit(key) if key is not None else None # -- aliasing ----------------------------------------------------------- def alias_slice( self, tensor: torch.Tensor | str, shard_name: str, offset_bytes: int, size_bytes: int, ) -> bool: """Bind a shard slice identity to a cached entry; returns False if absent. Call while the loader CPU tensors are alive (attach time), passing the weight tensor (or its content key). ``offset_bytes``/``size_bytes`` must come from DDO's own ``SafetensorFileSlice`` so the convention matches whatever the adapter stores — never computed independently. """ key = tensor if isinstance(tensor, str) else _tensor_key(tensor) slice_key = (shard_name, int(offset_bytes), int(size_bytes)) with self._lock: entry = self._entries.get(key) if entry is None: return False existing = entry.setdefault("slice_keys", []) if list(slice_key) not in existing: existing.append(list(slice_key)) self._slice_index[slice_key] = key _write_manifest(self.root, self._manifest) return True # -- blob access ---------------------------------------------------------- def read_blob(self, tensor: torch.Tensor, size_bytes: int) -> bytes | None: """Read one compressed payload, or None when the tensor is not cached.""" hit = self.lookup(tensor) if hit is None: return None blob_path, meta, _codebook = hit if size_bytes < meta.comp_bytes: raise RuntimeError( f"staging slot too small for SplitZip payload: need {meta.comp_bytes}, have {size_bytes}" ) with self._lock: with open(blob_path, "rb") as handle: return handle.read(meta.comp_bytes)