Files

36 lines
1.7 KiB
Python

# Synthetic entropy bound of int8 absmax-quantized K/V-like vectors and of fp32 state.
# Offline experiment (Python is allowed offline): NOT a measurement of the model; real parked blocks are measured by task T8. Pure standard library.
import random, math, zlib, struct, collections
random.seed(1)
def H(bs):
c = collections.Counter(bs); n = len(bs)
return -sum(v/n*math.log2(v/n) for v in c.values())
def quant(vecs):
out = bytearray()
for v in vecs:
m = max(abs(x) for x in v) or 1.0
s = 127.0/m
out += bytes((max(-127,min(127,round(x*s)))&0xff) for x in v)
return bytes(out)
def gen(kind, n, d=128):
vs=[]
for _ in range(n):
if kind=='gauss': v=[random.gauss(0,1) for _ in range(d)]
elif kind=='laplace': v=[random.expovariate(1)*random.choice((-1,1)) for _ in range(d)]
elif kind=='t3':
v=[random.gauss(0,1)/math.sqrt(random.gammavariate(1.5,2)/3) for _ in range(d)]
vs.append(v)
return vs
print("synthetic int8 absmax-quantized vectors (d=128), 0-order entropy bits/byte, ideal entropy-coder ratio, zlib-1 ratio")
for k in ('gauss','laplace','t3'):
b = quant(gen(k, 4000))
h = H(b)
print(f"{k:8s} H={h:5.2f} bits ideal x{8/h:4.2f} zlib1 x{len(b)/len(zlib.compress(b,1)):4.2f}")
# fp32 state: gaussian values, byte-plane entropy
vals=[random.gauss(0,0.05) for _ in range(300000)]
raw=struct.pack('<%df'%len(vals),*vals)
planes=[raw[i::4] for i in range(4)]
hp=[H(p) for p in planes]
print("fp32 gaussian byte-plane entropies (b0 low mantissa .. b3 sign/exp):", [round(x,2) for x in hp], " ideal x%.2f"%(32/sum(hp)))
print("zlib1 on raw x%.2f ; zlib1 on byte-shuffled x%.2f"%(len(raw)/len(zlib.compress(raw,1)), len(raw)/len(zlib.compress(b''.join(planes),1))))