""" Ternary (3-level, ~1.58-bit) KV-cache quantization-aware training for Hugging Face transformers attention, in the style of BananaMind KV1. * Quantizes post-RoPE K and V per token, per KV head, over head_dim (same as KV1). * mode="affine": levels {min, min+s, min+2s}; fp16 min + fp16 scale per vector (KV1 with qmax=2). * mode="symmetric": levels {-s, 0, +s}; fp16 absmean scale per vector. * hadamard=True: orthonormal Hadamard rotation of head_dim before quantizing. Q and K are rotated together (dot products unchanged); V is quantized in the rotated basis and rotated back. In full precision this is mathematically identical to the unrotated model. * Straight-through estimator: forward sees dequantized K/V, backward is identity. * Codes pack 5 trits per byte (3^5 = 243 <= 256) -> 1.6 bits/value before metadata. Usage: import kv_ternary as kvt kvt.configure(levels=4, mode="affine", hadamard=True, sink=4) name = kvt.register() # registers a "kv_ternary" attention implementation wrapping sdpa model = AutoModelForCausalLM.from_pretrained(repo, attn_implementation=name) Because quantization is per token and independent of history, a forward pass with this attention gives exactly the outputs of decoding from a packed ternary cache (see pack_kv/unpack_kv). """ import math import torch import torch.nn.functional as F STATE = {"enabled": True, "alpha": 1.0, "levels": 4, "mode": "affine", "hadamard": False, "eps": 1e-6, "sink": 0, "calls": 0} def configure(**kw): for k, v in kw.items(): if k not in STATE: raise KeyError(f"unknown kv_ternary option {k!r}") STATE[k] = v if STATE["mode"] not in ("affine", "symmetric"): raise ValueError("mode must be 'affine' or 'symmetric'") if STATE["levels"] not in (3, 4): raise ValueError("levels must be 4 (2-bit, KV1-8M style) or 3 (ternary)") if STATE["mode"] == "symmetric" and STATE["levels"] != 3: raise ValueError("symmetric mode is only defined for levels=3 ({-s, 0, +s})") # ---------------------------------------------------------------- Hadamard _H_CACHE = {} def hadamard_matrix(n, device, dtype): if n <= 0 or n & (n - 1): raise ValueError(f"Hadamard rotation needs a power-of-two head_dim, got {n}") key = (n, str(device), dtype) H = _H_CACHE.get(key) if H is None: H = torch.ones(1, 1, dtype=torch.float64) while H.size(0) < n: H = torch.cat([torch.cat([H, H], 1), torch.cat([H, -H], 1)], 0) H = (H / math.sqrt(n)).to(device=device, dtype=dtype) # symmetric, H @ H = I _H_CACHE[key] = H return H # ---------------------------------------------------------------- quantizer def quantize_ternary(x, mode="affine", eps=1e-6, levels=None): """Returns (codes uint8 in {0..levels-1}, min fp16 or None, scale fp16), reducing over the last dim. levels=4: KV1-8M 2-bit affine (scale = (max-min)/3). levels=3: ternary.""" levels = STATE["levels"] if levels is None else levels qmax = levels - 1 xf = x.float() if mode == "affine": mn = xf.amin(-1, keepdim=True) mx = xf.amax(-1, keepdim=True) scale16 = ((mx - mn) / qmax).clamp_min(eps).to(torch.float16) mn16 = mn.to(torch.float16) codes = ((xf - mn16.float()) / scale16.float()).round().clamp_(0, qmax) return codes.to(torch.uint8), mn16, scale16 scale16 = xf.abs().mean(-1, keepdim=True).clamp_min(eps).to(torch.float16) codes = (xf / scale16.float()).round().clamp_(-1, 1) + 1 return codes.to(torch.uint8), None, scale16 def dequantize_ternary(codes, mn16, scale16, mode, dtype): c = codes.to(dtype) if mode == "affine": return c * scale16.to(dtype) + mn16.to(dtype) return (c - 1) * scale16.to(dtype) def fake_quant_ternary_ste(x, mode="affine", eps=1e-6, alpha=1.0, levels=None): with torch.no_grad(): codes, mn, sc = quantize_ternary(x, mode, eps, levels) delta = dequantize_ternary(codes, mn, sc, mode, x.dtype) - x if alpha < 1.0: delta = delta * alpha return x + delta # ---------------------------------------------------------------- packing # levels=4: 4 x 2-bit codes per byte, byte = c0 + (c1 << 2) + (c2 << 4) + (c3 << 6) (identical to KV1-8M) # levels=3: 5 trits per byte (3^5 = 243 <= 256) def packed_dim(d, levels=None): levels = STATE["levels"] if levels is None else levels return (d + 3) // 4 if levels == 4 else (d + 4) // 5 def pack_codes(codes, levels=None): levels = STATE["levels"] if levels is None else levels n, base = (4, 4) if levels == 4 else (5, 3) d = codes.size(-1) pad = (-d) % n if pad: codes = F.pad(codes, (0, pad)) ch = codes.reshape(*codes.shape[:-1], -1, n).to(torch.int16) w = torch.tensor([base ** i for i in range(n)], dtype=torch.int16, device=codes.device) return (ch * w).sum(-1).to(torch.uint8) def unpack_codes(packed, d, levels=None): levels = STATE["levels"] if levels is None else levels n, base = (4, 4) if levels == 4 else (5, 3) p = packed.to(torch.int16) parts = [(p // (base ** i)) % base for i in range(n)] return torch.stack(parts, -1).flatten(-2)[..., :d].to(torch.uint8) pack_trits, unpack_trits = pack_codes, unpack_codes # backwards-compatible names def bits_per_value(head_dim, mode="affine", levels=None): meta_bytes = 4 if mode == "affine" else 2 return 8 * (packed_dim(head_dim, levels) + meta_bytes) / head_dim def pack_kv(x, mode=None, eps=None, hadamard=None): """Packed cache entry for post-RoPE K or V of shape (..., head_dim). Rotated basis if hadamard.""" mode = STATE["mode"] if mode is None else mode eps = STATE["eps"] if eps is None else eps hadamard = STATE["hadamard"] if hadamard is None else hadamard if hadamard: x = x @ hadamard_matrix(x.size(-1), x.device, x.dtype) codes, mn, sc = quantize_ternary(x, mode, eps) return pack_codes(codes), mn, sc def unpack_kv(packed, mn, sc, head_dim, dtype, mode=None): """Dequantized values, still in the rotated basis (rotate Q for K; rotate attn output back for V).""" mode = STATE["mode"] if mode is None else mode return dequantize_ternary(unpack_codes(packed, head_dim), mn, sc, mode, dtype) # ---------------------------------------------------------------- attention hook def _keep_sinks(xq, x, n): """Positions [0, n) along the sequence dim keep their unquantized values (attention sinks).""" if n <= 0: return xq n = min(n, x.size(-2)) return torch.cat([x[..., :n, :], xq[..., n:, :]], dim=-2) def apply_kv_quant(query, key, value): s = STATE if not s["enabled"]: return query, key, value s["calls"] += 1 kw = dict(mode=s["mode"], eps=s["eps"], alpha=s["alpha"]) if s["hadamard"]: H = hadamard_matrix(query.size(-1), query.device, query.dtype) query = query @ H kr, vr = key @ H, value @ H key = _keep_sinks(fake_quant_ternary_ste(kr, **kw), kr, s["sink"]) value = _keep_sinks(fake_quant_ternary_ste(vr, **kw), vr, s["sink"]) @ H else: key = _keep_sinks(fake_quant_ternary_ste(key, **kw), key, s["sink"]) value = _keep_sinks(fake_quant_ternary_ste(value, **kw), value, s["sink"]) return query, key, value def register(name="kv_ternary", base="sdpa"): from transformers import AttentionInterface from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS base_fn = ALL_ATTENTION_FUNCTIONS[base] def kv_ternary_attention(module, query, key, value, attention_mask, **kwargs): query, key, value = apply_kv_quant(query, key, value) return base_fn(module, query, key, value, attention_mask, **kwargs) AttentionInterface.register(name, kv_ternary_attention) try: # newer transformers build masks per attention implementation from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS, AttentionMaskInterface AttentionMaskInterface.register(name, ALL_MASK_ATTENTION_FUNCTIONS[base]) except Exception: pass return name