SONAPSE-PICO-1 / runtime.py
Kai9987kai's picture
Release SONAPSE-PICO-1 (GRU-256 INT4 QAT, 131,557 B package)
6f08b33 verified
Raw History Blame Contribute Delete
5.75 kB
"""Standalone PICO inference runtime. Dependencies: Python stdlib + NumPy only (no torch, no teacher).
.pico v1 layout (little-endian):
0 4s magic b"PICO"
4 u16 version (1)
6 u16 flags (0)
8 u32 header_len (<= 65536)
12 ... UTF-8 JSON header {"model": cfg, "tensors": [...], "meta": {...}}
... zero padding to 8-byte alignment, then payload
end-32 SHA-256 of all preceding bytes
Tensor entry: name, dtype in {i8,i4,f16,f32}, shape [rows, cols], offset/nbytes relative to payload start,
optional "scale": {offset, nbytes} (f16 per-row symmetric scale, for i8/i4).
i4: signed nibbles in [-8,7], row-major flattened, low nibble first, padded to whole byte.
Storage precision != compute precision: weights are dequantized to float32 at load."""
import hashlib, json, struct
import numpy as np
MAGIC, VERSION, MAX_HEADER, MAX_DIM = b"PICO", 1, 65536, 1 << 16
DTYPE_BYTES = {"i8": 1.0, "i4": 0.5, "f16": 2.0, "f32": 4.0}
class PicoFormatError(ValueError):
pass
def unpack_i4(buf, n):
b = np.frombuffer(buf, np.uint8)
lo = (b & 0x0F).astype(np.int8); hi = (b >> 4).astype(np.int8)
v = np.empty(b.size * 2, np.int8); v[0::2] = lo; v[1::2] = hi
v[v > 7] -= 16
return v[:n]
def load(path, verify=True):
with open(path, "rb") as f:
data = f.read()
return parse(data, verify)
def parse(data, verify=True):
if len(data) < 12 + 32:
raise PicoFormatError("file too small")
magic, ver, flags, hlen = struct.unpack_from("<4sHHI", data, 0)
if magic != MAGIC:
raise PicoFormatError("bad magic")
if ver != VERSION:
raise PicoFormatError(f"unsupported version {ver}")
if hlen > MAX_HEADER or 12 + hlen > len(data) - 32:
raise PicoFormatError("bad header length")
if verify and hashlib.sha256(data[:-32]).digest() != data[-32:]:
raise PicoFormatError("checksum mismatch")
try:
hdr = json.loads(data[12:12 + hlen].decode("utf-8"))
except Exception as e:
raise PicoFormatError(f"bad header json: {e}")
p0 = (12 + hlen + 7) // 8 * 8
plen = len(data) - 32 - p0
tensors = {}
for t in hdr.get("tensors", []):
shape = t["shape"]
if t["dtype"] not in DTYPE_BYTES or len(shape) != 2 or not all(isinstance(d, int) and 0 < d <= MAX_DIM for d in shape):
raise PicoFormatError(f"bad tensor spec {t.get('name')}")
n = shape[0] * shape[1]
need = int(np.ceil(n * DTYPE_BYTES[t["dtype"]]))
o, nb = t["offset"], t["nbytes"]
if nb != need or o < 0 or o + nb > plen:
raise PicoFormatError(f"bad offset/size for {t['name']}")
raw = data[p0 + o:p0 + o + nb]
if t["dtype"] == "f32":
w = np.frombuffer(raw, "<f4").astype(np.float32)
elif t["dtype"] == "f16":
w = np.frombuffer(raw, "<f2").astype(np.float32)
else:
q = np.frombuffer(raw, np.int8) if t["dtype"] == "i8" else unpack_i4(raw, n)
s = t.get("scale")
if s is None or s["nbytes"] != 2 * shape[0] or s["offset"] < 0 or s["offset"] + s["nbytes"] > plen:
raise PicoFormatError(f"bad scale for {t['name']}")
sc = np.frombuffer(data[p0 + s["offset"]:p0 + s["offset"] + s["nbytes"]], "<f2").astype(np.float32)
w = (q.astype(np.float32).reshape(shape) * sc[:, None]).ravel()
tensors[t["name"]] = w.reshape(shape)
return hdr, tensors
def _sig(x):
return 1.0 / (1.0 + np.exp(-x))
class PicoAgent:
"""Streaming step API: reset(batch) then step(obs[B,D]) -> actions[B]."""
def __init__(self, path):
self.hdr, self.t = load(path)
self.cfg = self.hdr["model"]
self.kind = self.cfg["kind"]
if self.kind == "connectome":
c = self.cfg
self.R, self.Hr = c["regions"], c["region_size"]
self.edges = [tuple(e) for e in c["edges"]]
for d, s in self.edges:
if not (0 <= d < self.R and 0 <= s < self.R):
raise PicoFormatError("bad edge index")
self.h = None
def reset(self, batch=1):
n = self.cfg["hidden"] if self.kind == "gru" else self.R * self.Hr
self.h = np.zeros((batch, n), np.float32)
def step(self, obs):
x = np.asarray(obs, np.float32)
if x.ndim == 1:
x = x[None]
T = self.t
if self.kind == "gru":
H = self.cfg["hidden"]
gi = x @ T["w_ih"].T + T["b_ih"][0]
gh = self.h @ T["w_hh"].T + T["b_hh"][0]
r = _sig(gi[:, :H] + gh[:, :H]); z = _sig(gi[:, H:2 * H] + gh[:, H:2 * H])
n = np.tanh(gi[:, 2 * H:] + r * gh[:, 2 * H:])
self.h = (1 - z) * n + z * self.h
out = self.h
else:
R, H = self.R, self.Hr
N = R * H
xi = x @ T["w_in"].T + T["b_in"][0]
hr = self.h.reshape(-1, R, H)
zc = np.zeros((x.shape[0], R, H), np.float32); zg = np.zeros_like(zc)
for k, (d, s) in enumerate(self.edges):
W = T[f"blk{k}"]
zc[:, d] += hr[:, s] @ W[:H].T
zg[:, d] += hr[:, s] @ W[H:].T
g = _sig(xi[:, N:] + zg.reshape(-1, N))
self.h = ((1 - g) * self.h + g * np.tanh(xi[:, :N] + zc.reshape(-1, N))).astype(np.float32)
out = self.h[:, -H:]
self.logits = out @ T["head_w"].T + T["head_b"][0]
return self.logits.argmax(-1)
if __name__ == "__main__":
import sys
hdr, ts = load(sys.argv[1])
print(json.dumps(hdr["model"]))
for t in hdr["tensors"]:
print(f"{t['name']:10s} {t['dtype']:4s} {str(t['shape']):14s} {t['nbytes']:8d} B scale {t.get('scale', {}).get('nbytes', 0)} B")