Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
tools: int4-rans256-g0 repack + verify tools, optional librans_c bridge
monotophice0ef3106443f
diff --git a/c/.gitignore b/c/.gitignoreindex 504cc602..3299f514 100644--- a/c/.gitignore+++ b/c/.gitignore@@ -8,3 +8,6 @@ tests/test_st_preadtools/libiq3.sotools/libiq3.dylibtools/iq3.dll+tools/librans_c.so+tools/librans_c.dylib+tools/rans_c.dlldiff --git a/c/Makefile b/c/Makefileindex 5a9c07d7..52e16c99 100644--- a/c/Makefile+++ b/c/Makefile@@ -337,6 +337,22 @@ iq3: $(IQ3LIB)$(IQ3LIB): tools/iq3_encode.c$(CC) $(CFLAGS) -fPIC -shared $< -o $@ $(LDFLAGS)+# int4-rans256-g0 codec bridge for tools/repack_rans.py + tools/rans_verify.py.+# OPTIONAL: both tools fall back to a pure-Python codec producing the same+# bytes far more slowly when the library is absent (fine for tests, not for a+# real repack). Same ARCH story as the engine: an AVX-512/NEON host gets the+# batched vector decoder, anything else the scalar paths.+ifneq (,$(DARWIN))+RANSLIB = tools/librans_c.dylib+else ifneq ($(IS_WIN),)+RANSLIB = tools/rans_c.dll+else+RANSLIB = tools/librans_c.so+endif+rans: $(RANSLIB)+$(RANSLIB): tools/rans_ctypes.c rans.h+ $(CC) $(CFLAGS) -fPIC -shared $< -o $@ $(LDFLAGS)+cuda-test: backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/test_backend_cuda.cu@command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }"$(GPUCC)" $(GPUFLAGS) backend_cuda.cu tests/test_backend_cuda.cu -o backend_cuda_test$(EXE)@@ -441,6 +457,7 @@ tests/test_kv_alloc$(EXE): tests/test_kv_alloc.c colibri.c st.h json.h tok.h toktests/test_e8_kernel$(EXE): tests/test_e8_kernel.c quant.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_int3$(EXE): tests/test_int3.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)@@ -548,4 +565,4 @@ clean:bench: iobench$(EXE)@if [ -n "$(ARGS)" ]; then ./iobench$(EXE) $(ARGS); else echo "built iobench$(EXE) β run: ./iobench$(EXE) <file> <MB> <iters> <threads> <direct 0|1>"; fi-.PHONY: all colibri glm iq3 cuda-test hip-test gpu-compile cuda-bench cuda-dll portable test-c test-python test check clean install uninstall bench+.PHONY: all colibri glm iq3 rans cuda-test hip-test gpu-compile cuda-bench cuda-dll portable test-c test-python test check clean install uninstall benchdiff --git a/c/tools/rans_ctypes.c b/c/tools/rans_ctypes.cnew file mode 100644index 00000000..e316ad45--- /dev/null+++ b/c/tools/rans_ctypes.c@@ -0,0 +1,95 @@+/* rans_ctypes.c β thin exported-symbol bridge over rans.h for the Python+ * offline tools (repack_rans.py, rans_verify.py), built as a shared library+ * by `make rans` (same optional-accelerator shape as tools/iq3_encode.c:+ * the Python side falls back to a slow pure-Python codec producing the SAME+ * bytes when this library is absent, and the Python e2e test pins the two+ * implementations byte-identical).+ *+ * Everything in rans.h is static; these wrappers are the only symbols the+ * library exports. No engine code is included or touched. */+#include "../rans.h"++#ifdef _WIN32+#define RC_EXPORT __declspec(dllexport)+#else+#define RC_EXPORT+#endif++/* Encode n nibbles into one chunk record. Returns the record length, or the+ * negated rans_err on failure. out_cap should come from rc_record_bound. */+RC_EXPORT int64_t rc_record_encode(const uint8_t *nibbles, uint64_t n,+ const uint32_t *freq, const uint32_t *start,+ const uint16_t *slot_to_symbol,+ uint32_t scale_bits, uint32_t n_streams,+ uint8_t *out, uint64_t out_cap) {+ rans_table t;+ rans_err e = rans_table_init(&t, scale_bits, freq, start, slot_to_symbol);+ if (e != RANS_OK) return -(int64_t)e;+ uint64_t len = 0;+ e = rans_record_encode(nibbles, n, &t, n_streams, out, out_cap, &len);+ rans_table_free(&t);+ if (e != RANS_OK) return -(int64_t)e;+ return (int64_t)len;+}++RC_EXPORT uint64_t rc_record_bound(uint64_t n_symbols, uint32_t n_streams) {+ return rans_record_bound(n_symbols, n_streams);+}++/* Parse + fully validate a record blob; fills n_symbols/packed_bytes on+ * success. Returns a rans_err. */+RC_EXPORT int32_t rc_record_parse(const uint8_t *blob, uint64_t blob_len,+ uint32_t n_streams,+ uint64_t *n_symbols, uint64_t *packed_bytes) {+ rans_record rec;+ rans_err e = rans_record_parse(blob, blob_len, n_streams, &rec);+ if (e == RANS_OK) {+ if (n_symbols) *n_symbols = rec.n_symbols;+ if (packed_bytes) *packed_bytes = rec.packed_bytes;+ }+ return (int32_t)e;+}++/* Parse + decode a record blob to packed bytes with the requested path+ * (path < 0 => rans_path_select(): env-honouring best arm). out_packed must+ * hold the record's packed_bytes; the CALLER must satisfy the RANS_SLACK+ * contract (blob allocated with >= RANS_SLACK readable bytes past blob_len β+ * the Python side copies each record into a padded buffer). */+RC_EXPORT int32_t rc_record_decode(const uint8_t *blob, uint64_t blob_len,+ uint32_t n_streams,+ const uint32_t *freq, const uint32_t *start,+ const uint16_t *slot_to_symbol,+ uint32_t scale_bits, int32_t path,+ uint8_t *out_packed) {+ rans_record rec;+ rans_err e = rans_record_parse(blob, blob_len, n_streams, &rec);+ if (e != RANS_OK) return (int32_t)e;+ rans_table t;+ e = rans_table_init(&t, scale_bits, freq, start, slot_to_symbol);+ if (e != RANS_OK) return (int32_t)e;+ rans_path p = (path < 0) ? rans_path_select() : (rans_path)path;+ e = rans_record_decode_packed(&rec, &t, n_streams, p, out_packed);+ rans_table_free(&t);+ return (int32_t)e;+}++/* Checked per-stream decode (verification invariants: state range, exact+ * consumption, final state). Returns a rans_err. */+RC_EXPORT int32_t rc_stream_decode_checked(const uint8_t *in_buf, uint64_t in_size,+ uint64_t n,+ const uint32_t *freq, const uint32_t *start,+ const uint16_t *slot_to_symbol,+ uint32_t scale_bits,+ uint8_t *out_nibbles) {+ return (int32_t)rans_decode_stream_checked(in_buf, (size_t)in_size, (size_t)n,+ freq, start, slot_to_symbol,+ scale_bits, out_nibbles);+}++RC_EXPORT const char *rc_err_name(int32_t e) {+ return rans_err_name((rans_err)(e < 0 ? -e : e));+}++RC_EXPORT const char *rc_path_name(void) {+ return rans_path_name(rans_path_select());+}diff --git a/c/tools/rans_format.py b/c/tools/rans_format.pynew file mode 100644index 00000000..a90314f5--- /dev/null+++ b/c/tools/rans_format.py@@ -0,0 +1,476 @@+"""int4-rans256-g0 format reference module, shared by repack_rans.py (writer)+and rans_verify.py (validator).++This is the Python twin of c/rans.h β the same codec, the same chunk-record+framing, the same named refusal classes. When the optional C bridge library+(`make rans` -> tools/librans_c.*) is present it does the heavy per-stream+work; when absent, the pure-Python fallback here produces byte-identical+output far more slowly (the e2e test pins the two implementations equal, the+same relationship iq3_pack.py has with tools/libiq3).++FORMAT SUMMARY (docs/int4-rans256-g0.md is the full specification):+ - a weight tensor's bytes are ONE chunk record: n_symbols u64,+ packed_bytes u64, stream_offsets[N+1] u32, zero-pad to 16, payload+ (N=256 independent rANS streams, round-robin symbol assignment j -> j%N),+ zero-pad to 16;+ - the shared static table ships once per shard in+ __metadata__["colibri.int4-rans256-g0.table"] (JSON: table_id, n_streams,+ scale_bits, M, freq[16], start[16], slot_to_symbol_b64, table_crc32);+ - __metadata__["colibri.fmt"] maps each entropy-coded WEIGHT tensor name to+ the format NAME "int4-rans256-g0". THE STAMP IS MANDATORY: entropy-coded+ sizes are data-dependent, so no byte-arithmetic inference exists for this+ format β the stamp is the ONLY signal a U8 tensor is entropy-coded, not a+ cross-check on an inference (unlike fmt=7's optional stamp).++Table construction is the standard largest-remainder frequency quantization+(FSE/rANS convention): scale an empirical histogram to sum exactly to+M = 2**scale_bits, keep every present symbol encodable (freq >= 1), hand out+the remainder by largest fractional part.+"""+import base64+import ctypes+import json+import os+import struct+import zlib++import numpy as np++FORMAT_NAME = "int4-rans256-g0"+N_STREAMS = 256+SCALE_BITS = 14 # M = 16384; generous for a 16-symbol alphabet+M = 1 << SCALE_BITS+TABLE_ID = "g0" # shared-global-table generation 0+METADATA_KEY = "colibri.fmt" # same key/shape as the fmt=7 stamp convention+TABLE_KEY = "colibri.int4-rans256-g0.table"+RANS_L = 1 << 23+SLACK = 64 # readable bytes past a record buffer (SIMD contract)+++class RansRefusal(Exception):+ """A named TRUST-VERIFY-REFUSE failure. `code` matches c/rans.h's+ rans_err_name strings (E_TRUNCATED, E_TABLE_CRC, ...) plus the+ container-level classes only the Python tools can see (stamps, metadata)."""++ def __init__(self, code, detail):+ self.code = code+ self.detail = detail+ super().__init__(f"{code}: {detail}")+++# ---------------------------------------------------------------------------+# table construction (ported unchanged from the proven prototype)+# ---------------------------------------------------------------------------+def quantize_freq(hist, m=M):+ """hist: length-16 array of raw counts. Returns freq[16] uint32 summing to+ m; largest-remainder quantization; min 1 count for any nonzero-count+ symbol (so it stays encodable); absent symbols get exactly 0."""+ hist = np.asarray(hist, dtype=np.float64)+ total = hist.sum()+ assert total > 0+ raw = hist / total * m+ freq = np.floor(raw).astype(np.int64)+ nonzero = hist > 0+ freq[nonzero & (freq == 0)] = 1+ deficit = m - freq.sum()+ if deficit > 0:+ remainder = raw - np.floor(raw)+ remainder[~nonzero] = -1 # never give slots to symbols absent from data+ order = np.argsort(-remainder)+ i = 0+ while deficit > 0 and i < len(order):+ idx = order[i]+ if nonzero[idx]:+ freq[idx] += 1+ deficit -= 1+ i += 1+ elif deficit < 0:+ order = np.argsort(-freq)+ i = 0+ while deficit < 0:+ idx = order[i % len(order)]+ if freq[idx] > 1:+ freq[idx] -= 1+ deficit += 1+ i += 1+ assert freq.sum() == m, (freq.sum(), m)+ return freq.astype(np.uint32)+++def build_table(freq, m=M):+ start = np.zeros(len(freq), dtype=np.uint32)+ start[1:] = np.cumsum(freq)[:-1].astype(np.uint32)+ slot_to_symbol = np.zeros(m, dtype=np.uint16)+ for s, (f, st) in enumerate(zip(freq, start)):+ if f:+ slot_to_symbol[st:st + f] = s+ return start, slot_to_symbol+++def table_blob(freq, start, slot_to_symbol):+ """The per-shard __metadata__ table value (as a dict; the writer+ json.dumps(..., sort_keys=True) it β deterministic, diffable)."""+ slot_bytes = np.ascontiguousarray(slot_to_symbol, dtype="<u2").tobytes()+ return {+ "table_id": TABLE_ID,+ "n_streams": N_STREAMS,+ "scale_bits": SCALE_BITS,+ "M": M,+ "freq": [int(x) for x in freq],+ "start": [int(x) for x in start],+ "slot_to_symbol_b64": base64.b64encode(slot_bytes).decode("ascii"),+ "table_crc32": f"{zlib.crc32(slot_bytes):08x}",+ }+++def parse_table_blob(raw):+ """Validate + decode the metadata table value. Raises RansRefusal with a+ named class for every malformation the break-it battery covers."""+ try:+ blob = json.loads(raw)+ except ValueError as exc:+ raise RansRefusal("E_TABLE_MALFORMED", f"table metadata is not JSON: {exc}")+ for key in ("table_id", "n_streams", "scale_bits", "M", "freq", "start",+ "slot_to_symbol_b64", "table_crc32"):+ if key not in blob:+ raise RansRefusal("E_TABLE_MALFORMED", f"table metadata lacks '{key}'")+ sb = blob["scale_bits"]+ if not isinstance(sb, int) or not (1 <= sb <= 15):+ raise RansRefusal("E_TABLE_SCALE", f"scale_bits={sb!r} out of range 1..15")+ m = blob["M"]+ if m != (1 << sb):+ raise RansRefusal("E_TABLE_SCALE", f"M={m!r} != 1<<scale_bits={1 << sb}")+ if blob["n_streams"] != N_STREAMS:+ raise RansRefusal("E_TABLE_MALFORMED",+ f"n_streams={blob['n_streams']!r} (this format fixes 256)")+ freq = blob["freq"]+ start = blob["start"]+ if len(freq) != 16 or len(start) != 16 or \+ not all(isinstance(x, int) and 0 <= x <= m for x in freq + start):+ raise RansRefusal("E_TABLE_MALFORMED", "freq/start must be 16 ints each")+ if sum(freq) != m:+ raise RansRefusal("E_TABLE_FREQ_SUM", f"freq sums to {sum(freq)}, not M={m}")+ acc = 0+ for s in range(16):+ if start[s] != acc:+ raise RansRefusal("E_TABLE_START", f"start[{s}]={start[s]} != prefix {acc}")+ acc += freq[s]+ try:+ slot_bytes = base64.b64decode(blob["slot_to_symbol_b64"], validate=True)+ except Exception as exc:+ raise RansRefusal("E_TABLE_MALFORMED", f"slot_to_symbol_b64: {exc}")+ if len(slot_bytes) != 2 * m:+ raise RansRefusal("E_TABLE_MALFORMED",+ f"slot_to_symbol is {len(slot_bytes)} bytes, want {2 * m}")+ crc = f"{zlib.crc32(slot_bytes):08x}"+ if crc != blob["table_crc32"]:+ raise RansRefusal("E_TABLE_CRC",+ f"slot table crc {crc} != stamped {blob['table_crc32']}")+ slot = np.frombuffer(slot_bytes, dtype="<u2")+ freq_a = np.asarray(freq, dtype=np.uint32)+ start_a = np.asarray(start, dtype=np.uint32)+ counts = np.bincount(slot, minlength=17)+ if slot.max(initial=0) > 15 or counts[:16].tolist() != freq or \+ not np.array_equal(np.sort(slot), slot):+ # sortedness + per-symbol counts == freq pins the slot table to be+ # exactly the canonical start/freq banding+ raise RansRefusal("E_TABLE_SLOT", "slot_to_symbol inconsistent with freq[]")+ return {"scale_bits": sb, "M": m, "freq": freq_a, "start": start_a,+ "slot_to_symbol": np.ascontiguousarray(slot, dtype=np.uint16),+ "table_id": blob["table_id"]}+++# ---------------------------------------------------------------------------+# nibble packing (low-nibble-first, the container convention)+# ---------------------------------------------------------------------------+def unpack_nibbles(raw_bytes):+ b = np.frombuffer(raw_bytes, dtype=np.uint8)+ out = np.empty(b.size * 2, dtype=np.uint8)+ out[0::2] = b & 0x0F+ out[1::2] = b >> 4+ return out+++def pack_nibbles(nibbles):+ n = nibbles.reshape(-1, 2)+ return ((n[:, 0] | (n[:, 1] << 4)).astype(np.uint8)).tobytes()+++# ---------------------------------------------------------------------------+# optional C bridge (make rans)+# ---------------------------------------------------------------------------+def _load_lib():+ here = os.path.dirname(os.path.abspath(__file__))+ for name in ("librans_c.dylib", "librans_c.so", "rans_c.dll"):+ path = os.path.join(here, name)+ if not os.path.exists(path):+ continue+ lib = ctypes.CDLL(path)+ u8p = ctypes.POINTER(ctypes.c_uint8)+ u16p = ctypes.POINTER(ctypes.c_uint16)+ u32p = ctypes.POINTER(ctypes.c_uint32)+ u64p = ctypes.POINTER(ctypes.c_uint64)+ lib.rc_record_encode.argtypes = [u8p, ctypes.c_uint64, u32p, u32p, u16p,+ ctypes.c_uint32, ctypes.c_uint32,+ u8p, ctypes.c_uint64]+ lib.rc_record_encode.restype = ctypes.c_int64+ lib.rc_record_bound.argtypes = [ctypes.c_uint64, ctypes.c_uint32]+ lib.rc_record_bound.restype = ctypes.c_uint64+ lib.rc_record_parse.argtypes = [u8p, ctypes.c_uint64, ctypes.c_uint32,+ u64p, u64p]+ lib.rc_record_parse.restype = ctypes.c_int32+ lib.rc_record_decode.argtypes = [u8p, ctypes.c_uint64, ctypes.c_uint32,+ u32p, u32p, u16p, ctypes.c_uint32,+ ctypes.c_int32, u8p]+ lib.rc_record_decode.restype = ctypes.c_int32+ lib.rc_stream_decode_checked.argtypes = [u8p, ctypes.c_uint64,+ ctypes.c_uint64, u32p, u32p,+ u16p, ctypes.c_uint32, u8p]+ lib.rc_stream_decode_checked.restype = ctypes.c_int32+ lib.rc_err_name.argtypes = [ctypes.c_int32]+ lib.rc_err_name.restype = ctypes.c_char_p+ return lib+ return None+++LIB = None if os.environ.get("RANS_FORCE_PYTHON") else _load_lib()+++def _p8(a):+ return a.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))+++def _p16(a):+ return a.ctypes.data_as(ctypes.POINTER(ctypes.c_uint16))+++def _p32(a):+ return a.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))+++def _err_name(code):+ return LIB.rc_err_name(code).decode("ascii")+++# ---------------------------------------------------------------------------+# pure-Python codec fallback (bit-exact twin of c/rans.h's scalar paths)+# ---------------------------------------------------------------------------+def _py_encode_stream(nibbles, freq, start, scale_bits):+ out = bytearray() # collected backwards, reversed at the end+ x = RANS_L+ for s in nibbles[::-1]:+ s = int(s)+ f = int(freq[s])+ x_max = ((RANS_L >> scale_bits) << 8) * f+ while x >= x_max:+ out.append(x & 0xFF)+ x >>= 8+ x = ((x // f) << scale_bits) + (x % f) + int(start[s])+ for _ in range(4):+ out.append(x & 0xFF)+ x >>= 8+ return bytes(out[::-1])+++def _py_decode_stream_checked(buf, n, freq, start, slot_to_symbol, scale_bits):+ """Returns (nibbles ndarray, refusal-name-or-None); mirrors+ rans_decode_stream_checked in c/rans.h refusal for refusal."""+ if len(buf) < 4:+ return None, "E_STREAM_UNDERRUN"+ mask = (1 << scale_bits) - 1+ pos = 4+ x = int.from_bytes(buf[:4], "big")+ if x < RANS_L:+ return None, "E_STREAM_STATE_RANGE"+ end = len(buf)+ out = np.empty(n, dtype=np.uint8)+ for i in range(n):+ slot = x & mask+ s = int(slot_to_symbol[slot])+ x = int(freq[s]) * (x >> scale_bits) + slot - int(start[s])+ while x < RANS_L:+ if pos >= end:+ break+ x = (x << 8) | buf[pos]+ pos += 1+ out[i] = s+ if pos != end:+ return None, "E_STREAM_LEFTOVER"+ if x != RANS_L:+ return None, "E_STREAM_FINAL_STATE"+ return out, None+++# ---------------------------------------------------------------------------+# chunk record: build / parse / decode+# ---------------------------------------------------------------------------+def _round16(v):+ return (v + 15) & ~15+++def record_header_bytes(n_streams=N_STREAMS):+ return _round16(16 + (n_streams + 1) * 4)+++def build_record(nibbles, freq, start, slot_to_symbol, scale_bits=SCALE_BITS,+ n_streams=N_STREAMS):+ """nibbles -> one chunk-record bytes object. Deterministic."""+ nib = np.ascontiguousarray(nibbles, dtype=np.uint8)+ n = nib.size+ if n == 0:+ raise RansRefusal("E_EMPTY", "refusing to encode an empty tensor")+ if LIB is not None:+ cap = int(LIB.rc_record_bound(n, n_streams)) + SLACK+ out = np.zeros(cap, dtype=np.uint8)+ freq_a = np.ascontiguousarray(freq, dtype=np.uint32)+ start_a = np.ascontiguousarray(start, dtype=np.uint32)+ slot_a = np.ascontiguousarray(slot_to_symbol, dtype=np.uint16)+ rc = LIB.rc_record_encode(_p8(nib), n, _p32(freq_a), _p32(start_a),+ _p16(slot_a), scale_bits, n_streams,+ _p8(out), cap)+ if rc < 0:+ raise RansRefusal(_err_name(int(rc)), "rc_record_encode failed")+ return out[:rc].tobytes()+ # pure-Python fallback: identical construction+ streams = [_py_encode_stream(nib[i::n_streams], freq, start, scale_bits)+ for i in range(n_streams)]+ offsets = np.zeros(n_streams + 1, dtype=np.uint32)+ offsets[1:] = np.cumsum([len(s) for s in streams]).astype(np.uint32)+ payload = b"".join(streams)+ head = struct.pack("<QQ", n, (n + 1) // 2) + offsets.astype("<u4").tobytes()+ head += b"\x00" * (_round16(len(head)) - len(head))+ payload += b"\x00" * (_round16(len(payload)) - len(payload))+ return head + payload+++def parse_record(blob, n_streams=N_STREAMS):+ """Validate framing; returns dict(n_symbols, packed_bytes, offsets,+ payload). Raises RansRefusal with the same named classes as c/rans.h."""+ head = record_header_bytes(n_streams)+ if len(blob) < head:+ raise RansRefusal("E_TRUNCATED", f"{len(blob)} bytes < {head}-byte header")+ n_symbols, packed_bytes = struct.unpack_from("<QQ", blob, 0)+ if n_symbols == 0:+ raise RansRefusal("E_EMPTY", "n_symbols == 0")+ if packed_bytes != (n_symbols + 1) // 2:+ raise RansRefusal("E_COUNT_MISMATCH",+ f"packed_bytes={packed_bytes} != ceil({n_symbols}/2)")+ offsets = np.frombuffer(blob, dtype="<u4", count=n_streams + 1, offset=16)+ if offsets[0] != 0:+ raise RansRefusal("E_OFFSET_FIRST", f"stream_offsets[0]={offsets[0]}")+ d = np.diff(offsets.astype(np.int64))+ if (d < 0).any():+ raise RansRefusal("E_OFFSETS_MONOTONIC", "stream_offsets not non-decreasing")+ if (d < 4).any():+ raise RansRefusal("E_STREAM_SHORT",+ f"stream {int(np.argmax(d < 4))} shorter than its 4-byte state")+ payload_len = int(offsets[n_streams])+ if head + payload_len > len(blob):+ raise RansRefusal("E_TRUNCATED",+ f"payload claims {payload_len} bytes past the blob end")+ if len(blob) != head + _round16(payload_len):+ raise RansRefusal("E_LENGTH_MISMATCH",+ f"blob is {len(blob)} bytes, framing derives "+ f"{head + _round16(payload_len)}")+ raw_head_end = 16 + (n_streams + 1) * 4+ if any(blob[raw_head_end:head]) or any(blob[head + payload_len:]):+ raise RansRefusal("E_PAD_NONZERO", "derived padding bytes are not zero")+ return {"n_symbols": n_symbols, "packed_bytes": packed_bytes,+ "offsets": offsets, "payload": blob[head:head + payload_len]}+++def decode_record(blob, table, n_streams=N_STREAMS, checked=True):+ """Record bytes -> original packed bytes. `table` is parse_table_blob's+ result (or an equivalent dict). Raises RansRefusal on any malformation,+ including the stream-level invariants a genuine encoder output always+ satisfies (state range / exact consumption / final state)."""+ rec = parse_record(blob, n_streams)+ freq = np.ascontiguousarray(table["freq"], dtype=np.uint32)+ start = np.ascontiguousarray(table["start"], dtype=np.uint32)+ slot = np.ascontiguousarray(table["slot_to_symbol"], dtype=np.uint16)+ sb = table["scale_bits"]+ n = rec["n_symbols"]+ if LIB is not None and not checked:+ buf = np.zeros(len(blob) + SLACK, dtype=np.uint8) # SLACK contract+ buf[:len(blob)] = np.frombuffer(blob, dtype=np.uint8)+ out = np.empty(rec["packed_bytes"], dtype=np.uint8)+ rc = LIB.rc_record_decode(_p8(buf), len(blob), n_streams, _p32(freq),+ _p32(start), _p16(slot), sb, -1, _p8(out))+ if rc != 0:+ raise RansRefusal(_err_name(rc), "rc_record_decode failed")+ return out.tobytes()+ # checked per-stream decode (verification path), C-accelerated per stream+ payload = rec["payload"]+ offsets = rec["offsets"]+ nib = np.empty(n, dtype=np.uint8)+ for i in range(n_streams):+ sub = payload[int(offsets[i]):int(offsets[i + 1])]+ n_i = len(range(i, n, n_streams))+ if LIB is not None:+ sbuf = np.frombuffer(sub, dtype=np.uint8)+ sout = np.empty(max(n_i, 1), dtype=np.uint8)+ rc = LIB.rc_stream_decode_checked(_p8(np.ascontiguousarray(sbuf)),+ len(sub), n_i, _p32(freq),+ _p32(start), _p16(slot), sb,+ _p8(sout))+ if rc != 0:+ raise RansRefusal(_err_name(rc), f"stream {i} failed checked decode")+ dec = sout[:n_i]+ else:+ dec, err = _py_decode_stream_checked(sub, n_i, freq, start, slot, sb)+ if err:+ raise RansRefusal(err, f"stream {i} failed checked decode")+ nib[i::n_streams] = dec+ if n % 2:+ nib = np.concatenate([nib, np.zeros(1, dtype=np.uint8)])+ return pack_nibbles(nib)+++# ---------------------------------------------------------------------------+# minimal safetensors i/o (header-only reads; deterministic writes) β no+# external safetensors dependency, same spirit as doctor.py's own parser+# ---------------------------------------------------------------------------+def read_header(path):+ with open(path, "rb") as f:+ raw = f.read(8)+ if len(raw) != 8:+ raise RansRefusal("E_SHARD_MALFORMED", f"{path}: no header length")+ hlen = struct.unpack("<Q", raw)[0]+ if hlen > 512 * 1024 * 1024:+ raise RansRefusal("E_SHARD_MALFORMED", f"{path}: absurd header ({hlen} B)")+ try:+ header = json.loads(f.read(hlen))+ except ValueError as exc:+ raise RansRefusal("E_SHARD_MALFORMED", f"{path}: header not JSON: {exc}")+ return header, 8 + hlen+++def read_tensor_bytes(path, header, data_start, name):+ info = header[name]+ b, e = info["data_offsets"]+ with open(path, "rb") as f:+ f.seek(data_start + b)+ raw = f.read(e - b)+ if len(raw) != e - b:+ raise RansRefusal("E_SHARD_MALFORMED", f"{path}:{name}: short read")+ return raw, info+++def write_shard(path, tensors, metadata):+ """tensors: list of (name, dtype, shape, bytes) β written in the given+ order; metadata: {str: str}. Fully deterministic byte layout (sorted+ metadata keys, insertion-ordered tensors, no timestamps)."""+ header = {"__metadata__": {k: metadata[k] for k in sorted(metadata)}}+ offset = 0+ for name, dtype, shape, raw in tensors:+ header[name] = {"dtype": dtype, "shape": list(shape),+ "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ hjson = json.dumps(header, separators=(",", ":"), sort_keys=False).encode()+ tmp = path + ".tmp"+ with open(tmp, "wb") as f:+ f.write(struct.pack("<Q", len(hjson)))+ f.write(hjson)+ for _, _, _, raw in tensors:+ f.write(raw)+ os.replace(tmp, path)diff --git a/c/tools/rans_verify.py b/c/tools/rans_verify.pynew file mode 100644index 00000000..234f8f92--- /dev/null+++ b/c/tools/rans_verify.py@@ -0,0 +1,173 @@+#!/usr/bin/env python3+"""int4-rans256-g0 container validator: TRUST-VERIFY-REFUSE at the format+boundary. Accepts a spec-conformant shard; produces a NAMED refusal for every+corruption class; never crashes, never silently accepts.++WHAT IS CHECKED, per shard:+ stamp layer (the stamp is MANDATORY for this format β entropy-coded sizes+ are data-dependent, so the stamp is the ONLY signal a U8 tensor is+ entropy-coded at all):+ E_STAMP_MISSING __metadata__ or its colibri.fmt key absent while+ the shard was named on the command line as an+ entropy container+ E_STAMP_MALFORMED colibri.fmt not a JSON {name: format} object+ E_STAMP_DANGLING a stamped name with no tensor in the shard+ E_STAMP_DTYPE a stamped tensor whose dtype is not U8+ table layer:+ E_TABLE_MISSING colibri.int4-rans256-g0.table absent while stamps+ claim this format+ E_TABLE_MALFORMED table JSON/fields/b64 malformed+ E_TABLE_SCALE scale_bits/M out of range or inconsistent+ E_TABLE_FREQ_SUM freq[] does not sum to M+ E_TABLE_START start[] not the prefix sum of freq[]+ E_TABLE_SLOT slot_to_symbol inconsistent with freq[]/start[]+ E_TABLE_CRC slot-table bytes do not match the stamped crc32+ record layer (per stamped tensor; same names as c/rans.h's rans_err):+ E_TRUNCATED E_EMPTY E_COUNT_MISMATCH E_OFFSET_FIRST E_OFFSETS_MONOTONIC+ E_STREAM_SHORT E_LENGTH_MISMATCH E_PAD_NONZERO+ payload layer (per stream; a genuine encoder output ALWAYS satisfies+ these, so corruption is refused without any ground-truth bytes):+ E_STREAM_STATE_RANGE initial state outside the encoder's invariant+ E_STREAM_UNDERRUN stream shorter than its flushed state+ E_STREAM_LEFTOVER decode finished with bytes unconsumed+ E_STREAM_FINAL_STATE final state != the encoder's initial state+ plus a re-encode cross-check: re-encoding the decoded nibbles with the+ shard's own table must reproduce the record byte-for-byte+ (E_REENCODE_MISMATCH) β the writer is deterministic, so any surviving+ divergence is corruption the invariants above happened to miss.++Exit status: 0 = every named shard TRUSTED; 1 = at least one refusal+(each printed as `REFUSE <shard> <tensor|-> <CLASS>: detail`); 2 = usage.++Build `make rans` first for the C codec; the pure-Python fallback verifies+the same things far more slowly.++Usage:+ python3 tools/rans_verify.py <shard.safetensors> [more shards...]+ python3 tools/rans_verify.py --max-tensors 8 <shard> # sampled quick look+"""+import argparse+import json+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rans_format as rf # noqa: E402+++def refuse(failures, shard, tensor, code, detail):+ print(f"REFUSE {os.path.basename(shard)} {tensor or '-'} {code}: {detail}")+ failures.append((shard, tensor, code))+++def verify_shard(path, failures, max_tensors=None):+ try:+ header, data_start = rf.read_header(path)+ except rf.RansRefusal as exc:+ refuse(failures, path, None, exc.code, exc.detail)+ return+ meta = header.get("__metadata__")+ if not isinstance(meta, dict) or rf.METADATA_KEY not in meta:+ refuse(failures, path, None, "E_STAMP_MISSING",+ f"no __metadata__[{rf.METADATA_KEY!r}] β for this format the "+ f"stamp is load-bearing, not optional")+ return+ try:+ fmt_map = json.loads(meta[rf.METADATA_KEY])+ if not isinstance(fmt_map, dict) or \+ not all(isinstance(k, str) and isinstance(v, str)+ for k, v in fmt_map.items()):+ raise ValueError("not a {name: format} object")+ except ValueError as exc:+ refuse(failures, path, None, "E_STAMP_MALFORMED", str(exc))+ return++ ours = sorted(n for n, v in fmt_map.items() if v == rf.FORMAT_NAME)+ others = {n: v for n, v in fmt_map.items() if v != rf.FORMAT_NAME}+ if others:+ print(f"[note] {os.path.basename(path)}: {len(others)} stamp(s) for "+ f"other formats β out of this validator's scope, skipped")+ if not ours:+ refuse(failures, path, None, "E_STAMP_MISSING",+ f"colibri.fmt carries no {rf.FORMAT_NAME!r} stamps")+ return++ if rf.TABLE_KEY not in meta:+ refuse(failures, path, None, "E_TABLE_MISSING",+ f"stamps claim {rf.FORMAT_NAME} but __metadata__"+ f"[{rf.TABLE_KEY!r}] is absent")+ return+ try:+ table = rf.parse_table_blob(meta[rf.TABLE_KEY])+ except rf.RansRefusal as exc:+ refuse(failures, path, None, exc.code, exc.detail)+ return++ checked = 0+ trusted = 0+ for name in ours:+ if max_tensors is not None and checked >= max_tensors:+ print(f"[note] {os.path.basename(path)}: stopped after "+ f"--max-tensors {max_tensors} of {len(ours)} stamped tensors")+ break+ checked += 1+ if name not in header:+ refuse(failures, path, name, "E_STAMP_DANGLING",+ "stamped but not present in this shard")+ continue+ info = header[name]+ if info["dtype"] != "U8":+ refuse(failures, path, name, "E_STAMP_DTYPE",+ f"dtype {info['dtype']} != U8")+ continue+ try:+ blob, _ = rf.read_tensor_bytes(path, header, data_start, name)+ except rf.RansRefusal as exc:+ refuse(failures, path, name, exc.code, exc.detail)+ continue+ try:+ packed = rf.decode_record(blob, table)+ except rf.RansRefusal as exc:+ refuse(failures, path, name, exc.code, exc.detail)+ continue+ # deterministic re-encode cross-check+ try:+ re_rec = rf.build_record(rf.unpack_nibbles(packed), table["freq"],+ table["start"], table["slot_to_symbol"],+ table["scale_bits"])+ except rf.RansRefusal as exc:+ refuse(failures, path, name, exc.code, exc.detail)+ continue+ if re_rec != blob:+ refuse(failures, path, name, "E_REENCODE_MISMATCH",+ "re-encoding the decoded stream does not reproduce the "+ "record β content corruption")+ continue+ trusted += 1+ print(f"[trust] {os.path.basename(path)}: {trusted}/{checked} verified "+ f"tensor(s) byte-exact (table_id={table['table_id']}, "+ f"codec={'C' if rf.LIB else 'python'})")+++def main():+ ap = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("shards", nargs="+", help="entropy-container shard(s) to verify")+ ap.add_argument("--max-tensors", type=int, default=None,+ help="verify at most N stamped tensors per shard (sampling; "+ "default: all β full verification is the deliverable)")+ a = ap.parse_args()+ failures = []+ for p in a.shards:+ if not os.path.exists(p):+ refuse(failures, p, None, "E_SHARD_MALFORMED", "no such file")+ continue+ verify_shard(p, failures, a.max_tensors)+ if failures:+ print(f"RESULT: REFUSE ({len(failures)} refusal(s))")+ sys.exit(1)+ print("RESULT: TRUST")+++if __name__ == "__main__":+ main()diff --git a/c/tools/repack_rans.py b/c/tools/repack_rans.pynew file mode 100644index 00000000..92eb304c--- /dev/null+++ b/c/tools/repack_rans.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""int4-rans256-g0 repack tool: per-row-int4 expert shards -> an+entropy-coded container (lossless, byte-exact round trip guaranteed and+verified before anything is written).++WHAT IT DOES+ 1. Scans every input shard's header (header-only reads, cheap) and builds a+ corpus-wide {tensor -> shard} index β routed-expert tensors and their+ `.qs` sidecars can live in different shards.+ 2. Selects routed-expert projection weights+ (model.layers.{L}.mlp.experts.{E}.{gate,up,down}_proj.weight, dtype U8)+ whose `.qs` sidecar is per-row F32 β the per-row ("gs=0") int4 geometry+ this format's v1 targets. GEOMETRY GUARD (enforced, not assumed): for a+ per-row container weight_bytes/scale_rows == I/2, a per-group (g64)+ container measures exactly 32 β any tensor at ratio 32, at a+ non-integral ratio, or below MIN_ROW_RATIO is REFUSED by name rather+ than silently entropy-coded under the wrong format identity.+ 3. Builds ONE global static rANS table from the pooled nibble histogram of+ every selected tensor (pass 1), then encodes each tensor as a 256-stream+ round-robin-interleaved chunk record (pass 2). The byte-identical table+ is stamped into EVERY output shard (the encoder invariant: readers are+ shard-local, so each shard must carry the same copy).+ 4. Verifies EVERY record byte-exact (decode -> repack -> compare against+ the original weight bytes) before its shard is written. Not sampled.+ 5. Writes ordinary safetensors shards: each weight tensor keeps its+ ORIGINAL logical name (its bytes are the chunk record), `.qs` sidecars+ pass through raw and untouched, and __metadata__ carries:+ colibri.fmt = JSON {weight_name: "int4-rans256-g0"}+ colibri.int4-rans256-g0.table = JSON shared-table blob+ The colibri.fmt stamp is MANDATORY for this format: entropy-coded sizes+ are data-dependent, so no byte-arithmetic inference exists β the stamp+ is the only signal a U8 tensor is entropy-coded at all (see+ docs/int4-rans256-g0.md, "the stamp is load-bearing").++DETERMINISM: two runs over the same input produce byte-identical output β+sorted tensor order, sorted JSON keys, no timestamps, a codec whose output+is a pure function of (bytes, table). The e2e test diffs two runs.++Build `make rans` first for the C codec (tools/librans_c.*); without it this+tool falls back to a pure-Python codec that emits the same bytes orders of+magnitude slower (fine for the test fixtures, not for a real container).++Usage:+ python3 tools/repack_rans.py --indir <int4_dir> --outdir <out> --dry-run+ python3 tools/repack_rans.py --indir <int4_dir> --outdir <out> [--layers 20,55]+"""+import argparse+import glob+import json+import os+import re+import sys++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rans_format as rf # noqa: E402++EXPERT_RE = re.compile(+ r"^model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.(gate|up|down)_proj\.weight$")++# Per-row geometry guard (see module docstring). MIN_ROW_RATIO = I/2 for the+# smallest hidden dim this tool accepts; the load-bearing exclusion is 32,+# the exact ratio EVERY per-group-64 container measures regardless of shape.+G64_RATIO = 32+MIN_ROW_RATIO = 64+++def build_index(indir):+ paths = sorted(glob.glob(os.path.join(indir, "*.safetensors")))+ index = {}+ for p in paths:+ header, data_start = rf.read_header(p)+ for name in header:+ if name == "__metadata__":+ continue+ index[name] = (p, header, data_start)+ return index, paths+++def select_targets(index, layers):+ """Returns sorted list of selected weight names; refuses (loud, named)+ any expert tensor whose geometry is not per-row int4."""+ selected = []+ for name in sorted(index):+ m = EXPERT_RE.match(name)+ if not m:+ continue+ if layers is not None and int(m.group(1)) not in layers:+ continue+ _, header, _ = index[name]+ info = header[name]+ if info["dtype"] != "U8":+ continue # not a packed-int4 weight (e.g. int8 MTP)+ qs = name + ".qs"+ if qs not in index:+ raise rf.RansRefusal(+ "E_GEOMETRY_NO_SCALES",+ f"{name}: no {qs} sidecar anywhere in the corpus β refusing to "+ f"entropy-code a tensor whose format cannot be confirmed")+ qpath, qheader, _ = index[qs]+ qinfo = qheader[qs]+ if qinfo["dtype"] != "F32":+ raise rf.RansRefusal(+ "E_GEOMETRY_NOT_PER_ROW",+ f"{name}: {qs} dtype {qinfo['dtype']} != F32")+ wb = info["data_offsets"][1] - info["data_offsets"][0]+ sb = qinfo["data_offsets"][1] - qinfo["data_offsets"][0]+ if sb % 4 or sb == 0:+ raise rf.RansRefusal("E_GEOMETRY_NOT_PER_ROW",+ f"{name}: {qs} is {sb} bytes (not F32-shaped)")+ rows = sb // 4+ if wb % rows:+ raise rf.RansRefusal(+ "E_GEOMETRY_NOT_PER_ROW",+ f"{name}: weight bytes {wb} not divisible by scale rows {rows}")+ ratio = wb // rows+ if ratio == G64_RATIO:+ raise rf.RansRefusal(+ "E_GEOMETRY_G64",+ f"{name}: weight/scale ratio {ratio} is the per-group-64 "+ f"signature β g64 containers are out of this format's v1 scope "+ f"(materially weaker entropy payoff; needs its own round)")+ if ratio < MIN_ROW_RATIO:+ raise rf.RansRefusal(+ "E_GEOMETRY_NOT_PER_ROW",+ f"{name}: weight/scale ratio {ratio} < {MIN_ROW_RATIO} β not a "+ f"per-row int4 shape this tool recognizes")+ selected.append(name)+ return selected+++def main():+ ap = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--indir", required=True,+ help="directory of per-row-int4 *.safetensors shards")+ ap.add_argument("--outdir", required=True,+ help="destination for the entropy-coded container shards")+ ap.add_argument("--layers",+ help="comma-separated layer subset (default: every layer)")+ ap.add_argument("--dry-run", action="store_true",+ help="inventory only: scan headers, print selection, write nothing")+ a = ap.parse_args()++ layers = None+ if a.layers:+ layers = {int(x) for x in a.layers.split(",")}++ index, shard_paths = build_index(a.indir)+ if not shard_paths:+ print(f"ERROR: no *.safetensors files in {a.indir}", file=sys.stderr)+ sys.exit(1)+ try:+ selected = select_targets(index, layers)+ except rf.RansRefusal as exc:+ print(f"REFUSED {exc}", file=sys.stderr)+ sys.exit(1)+ if not selected:+ print(f"ERROR: no per-row int4 routed-expert tensors selected under "+ f"{a.indir} β nothing to repack; refusing to emit an empty "+ f"container", file=sys.stderr)+ sys.exit(1)++ by_shard = {}+ total_w = 0+ for name in selected:+ p, header, _ = index[name]+ by_shard.setdefault(p, []).append(name)+ total_w += header[name]["data_offsets"][1] - header[name]["data_offsets"][0]+ print(f"[select] {len(selected)} weight tensor(s), {total_w / 1e9:.3f} GB "+ f"packed bytes, across {len(by_shard)} input shard(s)"+ + (f", layers={sorted(layers)}" if layers else ""))+ if a.dry_run:+ for p in sorted(by_shard):+ print(f"[dry-run] {os.path.basename(p)}: {len(by_shard[p])} tensor(s)")+ print(f"[dry-run] codec: {'C (librans_c)' if rf.LIB else 'pure Python'}")+ return++ if rf.LIB is None:+ print("[warn] tools/librans_c.* not built (make rans): using the "+ "pure-Python codec β identical bytes, orders of magnitude slower",+ file=sys.stderr)++ # pass 1: pooled histogram -> the ONE global table+ hist = np.zeros(16, dtype=np.int64)+ for name in selected:+ p, header, data_start = index[name]+ raw, _ = rf.read_tensor_bytes(p, header, data_start, name)+ hist += np.bincount(rf.unpack_nibbles(raw), minlength=16)+ freq = rf.quantize_freq(hist)+ start, slot = rf.build_table(freq)+ table_json = json.dumps(rf.table_blob(freq, start, slot), sort_keys=True)+ table = rf.parse_table_blob(table_json) # writer trusts nothing, not even itself+ print(f"[table] pooled histogram {hist.tolist()}")+ print(f"[table] freq {freq.tolist()} (M={rf.M}, scale_bits={rf.SCALE_BITS})")++ # pass 2: encode + verify + write, one output shard per input shard+ os.makedirs(a.outdir, exist_ok=True)+ out_n = 0+ total_record = 0+ for p in sorted(by_shard):+ tensors = []+ fmt_map = {}+ for name in by_shard[p]:+ _, header, data_start = index[name]+ raw, info = rf.read_tensor_bytes(p, header, data_start, name)+ nib = rf.unpack_nibbles(raw)+ record = rf.build_record(nib, freq, start, slot)+ # verify BEFORE writing: full checked decode, byte-exact repack+ back = rf.decode_record(record, table)+ if back != raw:+ print(f"FATAL: {name}: decode(encode(x)) != x β refusing to "+ f"write a container that does not round-trip", file=sys.stderr)+ sys.exit(1)+ tensors.append((name, "U8", [len(record)], record))+ fmt_map[name] = rf.FORMAT_NAME+ total_record += len(record)+ qs = name + ".qs"+ qp, qheader, qdata_start = index[qs]+ qraw, qinfo = rf.read_tensor_bytes(qp, qheader, qdata_start, qs)+ tensors.append((qs, qinfo["dtype"], qinfo["shape"], qraw))+ metadata = {+ rf.METADATA_KEY: json.dumps(fmt_map, sort_keys=True),+ rf.TABLE_KEY: table_json,+ }+ out_path = os.path.join(a.outdir, f"out-rans-{out_n:05d}.safetensors")+ rf.write_shard(out_path, tensors, metadata)+ print(f"[write] {out_path}: {len(tensors)} tensor(s) "+ f"({os.path.getsize(out_path) / 1e9:.4f} GB) "+ f"from {os.path.basename(p)}")+ out_n += 1++ ratio = total_record / total_w+ print(f"[ratio] record/original: {ratio:.4f} ({(1 - ratio) * 100:.2f}% "+ f"reduction incl. framing), {total_w / 1e6:.1f} MB -> "+ f"{total_record / 1e6:.1f} MB")+ print(f"[done] {out_n} shard(s), every record round-trip-verified byte-exact")+++if __name__ == "__main__":+ main()