"""SplitZip codec adapter for diffusers-dynamic-offloader. Lossless BF16 codec from: "SplitZip: Ultra Fast Lossless KV Compression for Disaggregated LLM Serving" (arXiv:2605.01708, NeurIPS 2026), official MIT implementation at https://github.com/Intelligent-Microsystems-Lab/SplitZip. Method: view each BF16 value as a 16-bit int. The exponent byte (bits 7..14) is coded with an offline-calibrated Top-16 -> 4-bit codebook (two codes per byte); the sign + low-7-mantissa byte is stored verbatim; exponents outside the Top-16 go to a sparse escape stream with chunk-local positions (chunk_size=1024). Reconstruction is bitwise exact: x_hat = ((sm & 0x80) << 8) | (exp << 7) | (sm & 0x7F) ONE-TIME VENDOR STEP: copy the upstream MIT file into the package: src/diffusers_dynamic_offloader/_splitzip_vendor/codec_gpu.py src/diffusers_dynamic_offloader/_splitzip_vendor/LICENSE Without it this module still works in pure-PyTorch mode (slower, but the only option on Windows, where Triton is unavailable). Payload layout (all offsets 4-byte aligned where a wider view is taken): [uint8 pk[n_pairs] @ off_pk ] packed 4-bit exponent codes [uint8 sm[n] @ off_sm ] sign + low-7-mantissa bytes [int32 chunk_id[n_esc] @ off_cid] escape chunk ids [uint16 local_pos[n_esc] @ off_lpos] chunk-local escape positions [uint8 esc_val[n_esc] @ off_ev ] raw exponent bytes Validated (CPU, pure-PyTorch path): bitwise round-trip on 10 synthetic cases including odd sizes, escape-heavy and subnormal-heavy distributions; measured ratio 0.750 on gaussian/weight-like data; shard-cache build/lookup/miss. """ from __future__ import annotations import base64 import contextlib from dataclasses import dataclass import torch try: # vendored upstream Triton codec (optional, Linux/CUDA only) from ._splitzip_vendor import codec_gpu as _gpu_codec except Exception: # pragma: no cover - depends on vendoring _gpu_codec = None def triton_available() -> bool: return _gpu_codec is not None def _align4(value: int) -> int: return (value + 3) & ~3 # --------------------------------------------------------------------------- # Codebook # --------------------------------------------------------------------------- @dataclass(frozen=True) class SplitZipCodebook: """Top-16 exponent codebook for one tensor (paper: per-tensor granularity).""" enc_lut: torch.Tensor # (256,) uint8, value -> 4-bit code enc_lut_marked: torch.Tensor # (256,) uint8, value -> code or 16 (escape) dec_lut: torch.Tensor # (16,) uint8, code -> value common_lut: torch.Tensor # (256,) uint8, 1 if value in Top-16 coverage: float def to_json(self) -> dict: return { "coverage": self.coverage, "enc_lut": base64.b64encode(self.enc_lut.cpu().numpy().tobytes()).decode(), "enc_lut_marked": base64.b64encode(self.enc_lut_marked.cpu().numpy().tobytes()).decode(), "dec_lut": base64.b64encode(self.dec_lut.cpu().numpy().tobytes()).decode(), "common_lut": base64.b64encode(self.common_lut.cpu().numpy().tobytes()).decode(), } @staticmethod def from_json(data: dict) -> "SplitZipCodebook": return SplitZipCodebook( enc_lut=torch.frombuffer(bytearray(base64.b64decode(data["enc_lut"])), dtype=torch.uint8), enc_lut_marked=torch.frombuffer( bytearray(base64.b64decode(data["enc_lut_marked"])), dtype=torch.uint8 ), dec_lut=torch.frombuffer(bytearray(base64.b64decode(data["dec_lut"])), dtype=torch.uint8), common_lut=torch.frombuffer( bytearray(base64.b64decode(data["common_lut"])), dtype=torch.uint8 ), coverage=float(data["coverage"]), ) def calibrate_codebook(x: torch.Tensor) -> tuple[SplitZipCodebook, float]: """Calibrate the Top-16 exponent codebook on one tensor (any device).""" if x.dtype is not torch.bfloat16: raise ValueError(f"SplitZip calibrate expects bfloat16, got {x.dtype}") flat = x.contiguous().reshape(-1).view(torch.int16).to(torch.int32) & 0xFFFF exp = ((flat >> 7) & 0xFF).to(torch.uint8) vals, counts = torch.unique(exp, return_counts=True) order = torch.argsort(counts, descending=True) top = min(16, int(vals.numel())) enc_lut = torch.zeros(256, dtype=torch.uint8) enc_lut_marked = torch.full((256,), 16, dtype=torch.uint8) dec_lut = torch.zeros(16, dtype=torch.uint8) common_lut = torch.zeros(256, dtype=torch.uint8) for code in range(top): value = int(vals[order[code]]) enc_lut[value] = code enc_lut_marked[value] = code dec_lut[code] = value common_lut[value] = 1 coverage = float(counts[order[:top]].sum().item() / counts.sum().item()) return SplitZipCodebook(enc_lut, enc_lut_marked, dec_lut, common_lut, coverage), coverage # --------------------------------------------------------------------------- # Payload metadata # --------------------------------------------------------------------------- @dataclass(frozen=True) class PayloadMeta: n: int n_pairs: int chunk_size: int n_esc: int comp_bytes: int offsets: tuple[int, int, int, int, int] # pk, sm, chunk_id, local_pos, esc_val coverage: float @property def off_pk(self) -> int: return self.offsets[0] @property def off_sm(self) -> int: return self.offsets[1] @property def off_cid(self) -> int: return self.offsets[2] @property def off_lpos(self) -> int: return self.offsets[3] @property def off_ev(self) -> int: return self.offsets[4] def to_json(self) -> dict: return { "n": self.n, "n_pairs": self.n_pairs, "chunk_size": self.chunk_size, "n_esc": self.n_esc, "comp_bytes": self.comp_bytes, "offsets": list(self.offsets), "coverage": self.coverage, } @staticmethod def from_json(data: dict) -> "PayloadMeta": return PayloadMeta( n=int(data["n"]), n_pairs=int(data["n_pairs"]), chunk_size=int(data["chunk_size"]), n_esc=int(data["n_esc"]), comp_bytes=int(data["comp_bytes"]), offsets=tuple(int(v) for v in data["offsets"]), coverage=float(data["coverage"]), ) def assemble_payload( pk: bytes, sm: bytes, chunk_id: bytes, local_pos: bytes, esc_val: bytes, *, n: int, n_esc: int, chunk_size: int, coverage: float, ) -> tuple[bytes, PayloadMeta]: """Pack the five payload streams into the aligned wire layout.""" n_pairs = (n + 1) // 2 if len(pk) != n_pairs or len(sm) != n: raise ValueError("pk/sm stream length mismatch") n_lpos_bytes = 2 * n_esc # plain uint16, little-endian, 2 bytes per escape if len(chunk_id) != 4 * n_esc or len(local_pos) != n_lpos_bytes or len(esc_val) != n_esc: raise ValueError("escape stream length mismatch") off_pk = 0 off_sm = _align4(off_pk + n_pairs) off_cid = _align4(off_sm + n) off_lpos = off_cid + 4 * n_esc off_ev = _align4(off_lpos + n_lpos_bytes) total = off_ev + n_esc buf = bytearray(total) buf[off_pk : off_pk + n_pairs] = pk buf[off_sm : off_sm + n] = sm buf[off_cid : off_cid + 4 * n_esc] = chunk_id buf[off_lpos : off_lpos + len(local_pos)] = local_pos buf[off_ev : off_ev + n_esc] = esc_val meta = PayloadMeta( n=n, n_pairs=n_pairs, chunk_size=chunk_size, n_esc=n_esc, comp_bytes=total, offsets=(off_pk, off_sm, off_cid, off_lpos, off_ev), coverage=coverage, ) return bytes(buf), meta # --------------------------------------------------------------------------- # Pure-PyTorch codec (device-agnostic reference + Windows/CPU fallback) # --------------------------------------------------------------------------- def encode_torch( x: torch.Tensor, codebook: SplitZipCodebook, chunk_size: int = 1024 ) -> tuple[bytes, PayloadMeta]: if x.dtype is not torch.bfloat16: raise ValueError(f"SplitZip encode expects bfloat16, got {x.dtype}") flat = x.contiguous().reshape(-1).view(torch.int16).to(torch.int32) & 0xFFFF exp = ((flat >> 7) & 0xFF).to(torch.uint8) marked = codebook.enc_lut_marked.to(exp.device)[exp.long()] n = int(flat.numel()) evens = (marked[0::2] & 0xF).to(torch.uint8) odds = (marked[1::2] & 0xF).to(torch.uint8) if odds.numel() < evens.numel(): pad = torch.zeros(evens.numel() - odds.numel(), dtype=torch.uint8, device=odds.device) odds = torch.cat([odds, pad]) pk = ((evens << 4) | odds).to(torch.uint8).cpu().numpy().tobytes() sm = (((flat >> 8) & 0x80) | (flat & 0x7F)).to(torch.uint8).cpu().numpy().tobytes() esc_idx = (marked > 15).nonzero(as_tuple=True)[0] n_esc = int(esc_idx.numel()) chunk_id = torch.div(esc_idx, chunk_size, rounding_mode="floor").to(torch.int32).cpu().numpy().tobytes() # chunk-local positions as plain uint16 little-endian (upstream wire layout): # byte 2k = pos[k] & 0xFF # byte 2k + 1 = pos[k] >> 8 lp = (esc_idx % chunk_size).to(torch.int32) lp_bytes = torch.stack( [(lp & 0xFF).to(torch.uint8), ((lp >> 8) & 0xFF).to(torch.uint8)], dim=1 ).reshape(-1).cpu().numpy().tobytes() esc_val = exp[esc_idx].cpu().numpy().tobytes() return assemble_payload( pk, sm, chunk_id, lp_bytes, esc_val, n=n, n_esc=n_esc, chunk_size=chunk_size, coverage=codebook.coverage, ) def decode_torch( payload: torch.Tensor, meta: PayloadMeta, dec_lut: torch.Tensor, out_bf16: torch.Tensor | None = None ) -> torch.Tensor: """Decode an aligned payload (uint8 tensor, any device) back to BF16. With ``out_bf16`` (a full-size, contiguous BF16 tensor), decodes in place into it; used for the Windows CPU path and the builder's verification. """ o, n = meta.offsets, meta.n pk = payload[o[0] : o[0] + meta.n_pairs].to(torch.int32) sm = payload[o[1] : o[1] + n].to(torch.int32) codes = torch.empty(n, dtype=torch.int32, device=payload.device) # n_pairs == ceil(n/2): with odd n the last byte's low nibble is padding, # so only the first n // 2 low-nibble slots are valid. codes[0::2] = (pk >> 4) & 0xF codes[1::2] = pk[: n // 2] & 0xF exp = dec_lut.to(payload.device)[codes.long()].to(torch.int32) recon = ((sm & 0x80) << 8) | (exp << 7) | (sm & 0x7F) if meta.n_esc: cid = payload[o[2] : o[2] + 4 * meta.n_esc].view(torch.int32).long() # plain uint16 little-endian positions (matches the upstream Triton layout) lpos_b = payload[o[3] : o[3] + 2 * meta.n_esc].to(torch.int32) pos = (lpos_b[0::2] | (lpos_b[1::2] << 8)).long() ev = payload[o[4] : o[4] + meta.n_esc].to(torch.int32) idx = cid * meta.chunk_size + pos sm_at = sm[idx] recon[idx] = ((sm_at & 0x80) << 8) | (ev << 7) | (sm_at & 0x7F) out16 = recon.to(torch.int16) if out_bf16 is None: return out16.view(torch.bfloat16) out_bf16.reshape(-1).view(torch.int16).copy_(out16) return out_bf16 # --------------------------------------------------------------------------- # Upstream Triton encoder (cache building) and GPU slot decoder (fast path) # --------------------------------------------------------------------------- class GpuSplitZipEncoder: """Encodes BF16 tensors on GPU with the vendored upstream Triton kernels.""" def __init__(self, device: str = "cuda", chunk_size: int = 1024) -> None: if _gpu_codec is None: raise RuntimeError("Vendored SplitZip Triton codec is unavailable") self._codec = _gpu_codec.ChunkLocalSplitZipGPU(device=device, chunk_size=chunk_size) self._chunk_size = chunk_size def encode(self, x: torch.Tensor, codebook: SplitZipCodebook) -> tuple[bytes, PayloadMeta]: codec = self._codec codec.enc_lut = codebook.enc_lut.to(x.device) codec.enc_lut_marked = codebook.enc_lut_marked.to(x.device) codec.dec_lut = codebook.dec_lut.to(x.device) codec.common_lut = codebook.common_lut.to(x.device) encoded = codec.encode(x) pk = encoded.pk.detach().cpu().numpy().tobytes() sm = encoded.sm.detach().cpu().numpy().tobytes() cid = encoded.chunk_id.detach().cpu().numpy().tobytes() lpos = encoded.local_pos.detach().cpu().numpy().tobytes() ev = encoded.esc_val.detach().cpu().numpy().tobytes() return assemble_payload( pk, sm, cid, lpos, ev, n=int(encoded.n), n_esc=int(encoded.n_esc), chunk_size=self._chunk_size, coverage=codebook.coverage, ) class GpuSplitZipDecoder: """Decodes a compressed payload out of a VMM slot into the same slot. The native allocator DMA'd the compressed payload into slot[0:comp_bytes]. We copy those bytes to a persistent GPU scratch (an on-device copy at HBM speed is negligible), then launch the upstream decode kernels writing the full BF16 weight back over the slot. Everything is enqueued on the caller's upload stream, so ordering against the DMA and the mark_upload event holds. """ def __init__(self, device_id: int = 0) -> None: if _gpu_codec is None: raise RuntimeError("Vendored SplitZip Triton codec is unavailable") self._device = torch.device(f"cuda:{device_id}") self._scratch: torch.Tensor | None = None def _ensure_scratch(self, nbytes: int) -> torch.Tensor: if self._scratch is None or self._scratch.numel() < nbytes: self._scratch = torch.empty(max(nbytes, 1 << 20), dtype=torch.uint8, device=self._device) return self._scratch def decode_slot_into( self, slot_typed: torch.Tensor, meta: PayloadMeta, dec_lut_gpu: torch.Tensor, stream=None ) -> None: """Expand a compressed payload occupying slot_typed[:comp_bytes].""" if not slot_typed.is_contiguous(): raise ValueError("VMM slot tensor must be contiguous for SplitZip decode") n, comp, o = meta.n, meta.comp_bytes, meta.offsets scratch = self._ensure_scratch(comp) slot_bytes = slot_typed.reshape(-1).view(torch.uint8) ctx = torch.cuda.stream(stream) if stream is not None else contextlib.nullcontext() with ctx: # 1) stash the compressed payload (the slot region is overwritten) scratch[:comp].copy_(slot_bytes[:comp], non_blocking=True) if n % 4 == 0: out16 = slot_typed.reshape(-1).view(torch.int16) # 2) dense decode: exponent LUT + sign/mantissa merge, 4 values per uint64 quad _gpu_codec._dec_4bit_quad64[((n // 4 + 511) // 512,)]( scratch[o[0] : o[0] + meta.n_pairs].view(torch.int16), scratch[o[1] : o[1] + n].view(torch.int32), dec_lut_gpu, out16.view(torch.int64), n // 4, BLOCK=512, num_warps=4, ) # 3) sparse escape correction with chunk-local positions if meta.n_esc: _gpu_codec._fix_escapes_local_linear[((meta.n_esc + 127) // 128,)]( scratch[o[2] : o[2] + 4 * meta.n_esc].view(torch.int32), scratch[o[3] : o[3] + 2 * meta.n_esc].view(torch.uint16), scratch[o[4] : o[4] + meta.n_esc], scratch[o[1] : o[1] + n], out16, meta.n_esc, CHUNK=meta.chunk_size, BLOCK_ESC=128, ) else: # rare non-quad-aligned tensor: pure-torch decode on GPU result = decode_torch(scratch[:comp], meta, dec_lut_gpu) slot_typed.reshape(-1).copy_(result)