Files
leleka/scripts/memory/kv_block_compress_sim.py

96 lines
3.9 KiB
Python

# Synthetic model of a parked prefix-cache block:
# the real layout (INT8 K/V codes with one fp16 scale per 64 values, run-major, plus f32 pooled index rows), filled with
# SYNTHETIC activations (Gaussian, per-channel outliers, Student-t tails). It measures order-0 entropy per plane and
# writes the planes as files so that `zstd -1/-3/-19` can be timed on the target CPU. It is NOT a measurement of the model:
# real parked blocks need the dump hook described in the document. Offline experiment, pure standard library.
#
# kv_block_compress_sim.py OUT_DIR [CELLS] (CELLS per layer, default 2048 = one block; keep OUT_DIR small)
import collections
import math
import os
import random
import struct
import sys
HEADS, HEAD_DIM, GROUP = 2, 256, 64
MODELS = { # name: (std of log channel scale, Student-t degrees of freedom or 0 for Gaussian)
"gauss": (0.0, 0),
"outlier-channels": (0.7, 0),
"outlier-channels+t4": (0.7, 4),
}
def entropy_bits(data):
counts, n = collections.Counter(data), len(data)
return -sum(c / n * math.log2(c / n) for c in counts.values())
def draw(rng, sigma, dof):
if dof == 0:
return rng.gauss(0.0, 1.0)
return rng.gauss(0.0, 1.0) / math.sqrt(rng.gammavariate(dof / 2.0, 2.0) / dof)
def quantize(values):
"""absmax/127 per 64-group, scale rounded through fp16, codes round-half-even (kv_q8.rs)."""
codes, scales = bytearray(), []
for at in range(0, len(values), GROUP):
group = values[at:at + GROUP]
s = struct.unpack("<e", struct.pack("<e", max(abs(v) for v in group) / 127.0))[0]
scales.append(struct.pack("<e", s))
codes += bytes((round(v / s) if s > 0 else 0) & 0xFF for v in group)
return bytes(codes), b"".join(scales)
def plane(rng, cells, sigma, dof):
"""K or V codes and scales of `cells` cells of one layer, cell-major (2 heads x 256 dims per cell)."""
channel = [math.exp(rng.gauss(0.0, sigma)) for _ in range(HEADS * HEAD_DIM)]
codes, scales = bytearray(), bytearray()
for _ in range(cells):
c, s = quantize([draw(rng, sigma, dof) * channel[i] for i in range(HEADS * HEAD_DIM)])
codes += c
scales += s
return bytes(codes), bytes(scales)
def pooled_rows(rng, rows, dim=128):
"""f32 pooled index rows: four keys rounded through fp16, summed, RMS-normalised, scaled by gamma."""
gamma = [math.exp(rng.gauss(0.0, 0.3)) for _ in range(dim)]
out = bytearray()
for _ in range(rows):
keys = [sum(struct.unpack("<e", struct.pack("<e", rng.gauss(0, 1)))[0] for _ in range(4)) for _ in range(dim)]
inv = 1.0 / math.sqrt(sum(k * k for k in keys) / dim + 1e-6)
out += struct.pack("<%df" % dim, *[k * inv * g for k, g in zip(keys, gamma)])
return bytes(out)
def byte_planes(raw, width):
return [raw[i::width] for i in range(width)]
def report(name, codes, scales, index):
hc, hs = entropy_bits(codes), entropy_bits(scales)
hi = sum(entropy_bits(p) for p in byte_planes(index, 4)) / 4
total = (1024 * hc / 8 + 32 * hs / 8 + 128 * hi / 8)
print("%-22s codes %.2f b/B (x%.2f) scales %.2f b/B (x%.2f) index f32 byte-planes %.2f b/B (x%.2f)"
" block ideal x%.2f" % (name, hc, 8 / hc, hs, 8 / hs, hi, 8 / hi, 1184 / total))
def main(out_dir, cells):
rng = random.Random(1)
os.makedirs(out_dir, exist_ok=True)
index = pooled_rows(rng, max(cells // 4, 1))
for name, (sigma, dof) in MODELS.items():
k_codes, k_scales = plane(rng, cells, sigma, dof)
v_codes, v_scales = plane(rng, cells, sigma, dof)
report(name, k_codes + v_codes, k_scales + v_scales, index)
for part, data in (("codes", k_codes + v_codes), ("scales", k_scales + v_scales)):
with open(os.path.join(out_dir, "%s.%s.bin" % (name, part)), "wb") as f:
f.write(data)
with open(os.path.join(out_dir, "index.f32.bin"), "wb") as f:
f.write(index)
if __name__ == "__main__":
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 2048)