#!/usr/bin/env python3 """Export Engine.export_embedded JSON to immutable quantized ESP-IDF headers. Usage: python3 tools/quantize.py snapshot.json main/model.h Per-row symmetric INT8/INT16 weights, wide accumulation, float calibration. No third party Python packages required. Re-evaluate calibration after export. """ import argparse import hashlib import json import math from pathlib import Path import struct MAX_DIMS, MAX_CLASSES = 768, 16 HEADS = {"nearest-prototype": "RD_PROTOTYPE", "linear-probe": "RD_PROBE", "logistic": "RD_LOGISTIC", "similarity-uncalibrated": "RD_SIMILARITY"} def f32(x): if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or abs(x) > 1e6: raise ValueError("model values must be finite numbers with magnitude <=1e6") return struct.unpack(" 1024 or "\0" in s: raise ValueError("identifiers must be nonempty UTF-8 strings <=1024 bytes without NUL") return '"' + ''.join(f"\\{b:03o}" for b in s.encode()) + '"' def validate(m): if m["version"] != 1: raise ValueError("unsupported snapshot version") d, k = m["dims"], len(m["labels"]) if type(d) is not int or not 1 <= d <= MAX_DIMS or not 1 <= k <= MAX_CLASSES: raise ValueError("snapshot exceeds MCU envelope") kind, head = m["kind"], m["head"] if kind not in ("choice", "score", "noul") or head not in HEADS: raise ValueError("unsupported decision head") if (kind == "noul" and (k != 1 or head not in ("logistic", "similarity-uncalibrated"))) or ( kind != "noul" and head not in ("nearest-prototype", "linear-probe")): raise ValueError("head/kind mismatch") if len(set(m["labels"])) != k: raise ValueError("duplicate labels") for s in [m["model_id"], m["question_id"], *m["labels"]]: cstring(s) if type(m["source_calibrated"]) is not bool: raise ValueError("invalid calibration flag") trained = head in ("linear-probe", "logistic") for name, expected in (("prototypes", k), ("negatives", k), ("weights", k if trained else 0)): if len(m[name]) != expected: raise ValueError(f"{name} row count mismatch") for row in m[name]: if row is None and name == "negatives": continue if not isinstance(row, list) or len(row) != d: raise ValueError(f"{name} width mismatch") for x in row: f32(x) if name != "weights" and abs(sum(f32(x)**2 for x in row)-1) > .02: raise ValueError("prototype and negative rows must be unit vectors") if len(m["bias"]) != (k if trained else 0): raise ValueError("bias count mismatch") for x in m["bias"]: f32(x) for key in ("temperature", "platt_a", "platt_b", "not_for_lambda", "abstain_tau", "abstain_scale", "logit_scale"): f32(m[key]) if m["temperature"] < .1 or m["logit_scale"] <= 0 or abs(m["abstain_scale"]) < 1.1920929e-7: raise ValueError("invalid calibration/abstention scale") if 'preprocessing' in m: pre=m['preprocessing'] if pre['kind']!='standardize-f32-v1' or len(pre['mean'])!=d or len(pre['std'])!=d: raise ValueError('preprocessing schema mismatch') if len(pre['features'])!=d or any(not isinstance(x,str) for x in pre['features']): raise ValueError('feature schema mismatch') for mean,std in zip(pre['mean'],pre['std']): f32(mean) if f32(std)<=0: raise ValueError('invalid feature scale') def quantize_row(row, bits=16): row = [f32(x) for x in row] qmax = (1 << (bits-1))-1 scale = f32(max(map(abs, row))/qmax) if any(row) else 1.0 if scale <= 0: raise ValueError("row scale underflow") # Explicit half-away-from-zero rounding matches C roundf. q = [max(-qmax, min(qmax, int(math.copysign(math.floor(abs(x/scale)+.5), x)))) for x in row] return q, scale def export(m, path, vectors=None, bits=16): validate(m) if bits not in (8, 16): raise ValueError('quantization bits must be 8 or 16') digest = hashlib.sha256(json.dumps({'snapshot':m, 'quant_bits':bits}, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() out = ['/* Generated by tools/quantize.py; do not edit. */', '#ifndef RD_MODEL_H', '#define RD_MODEL_H', '#include "rvdecision.h"'] weight_bytes, float_bytes = 0, 0 if 'preprocessing' in m: pre=m['preprocessing'] out.append('#define RD_PREPROCESSING 1') out.append('static const float rd_feature_mean[] = {'+','.join(map(number,pre['mean']))+'};') out.append('static const float rd_feature_std[] = {'+','.join(map(number,pre['std']))+'};') arrays = {} for name in ("prototypes", "negatives", "weights"): if not m[name]: continue descriptors = [] for i, row in enumerate(m[name]): if row is None: descriptors.append("{NULL, 0, 1.0f}"); continue q, scale = quantize_row(row, bits) key = tuple(q) weight_bytes += 4; float_bytes += len(q)*4 if key not in arrays: arrays[key] = f'rd_{name}_{i}' weight_bytes += len(q)*(bits//8) out.append(f'static const int{bits}_t {arrays[key]}[] = {{' + ','.join(map(str, q)) + '};') descriptors.append(f'{{{arrays[key]}, {len(q)}, {number(scale)}}}') out.append(f'static const rd_row rd_{name}[] = {{' + ','.join(descriptors) + '};') if m["bias"]: out.append('static const float rd_bias[] = {' + ','.join(map(number, m["bias"])) + '};') out.append('static const char *const rd_labels[] = {' + ','.join(map(cstring, m["labels"])) + '};') out += [f'#define RD_MODEL_DIMS {m["dims"]}', f'#define RD_MODEL_CLASSES {len(m["labels"])}', f'#define RD_MODEL_HASH "{digest}"', f'#define RD_MODEL_ID {cstring(m["model_id"])}', f'#define RD_QUESTION_ID {cstring(m["question_id"])}', f'#define RD_PARAMETER_BYTES {weight_bytes + len(m["bias"])*4}', f'#define RD_FLOAT_PARAMETER_BYTES {float_bytes + len(m["bias"])*4}'] out.append('static const rd_model rd_firmware_model = {') fields = {"version": "1", "quant_bits": str(bits), "dims": str(m["dims"]), "classes": str(len(m["labels"])), "kind": 'RD_'+m["kind"].upper(), "head": HEADS[m["head"]], "source_calibrated": str(m["source_calibrated"]).lower()} for name in ("prototypes", "negatives", "weights", "bias"): fields[name] = 'rd_'+name if m[name] else 'NULL' for key, name in (("prototype_count", "prototypes"), ("negative_count", "negatives"), ("weight_count", "weights"), ("bias_count", "bias")): fields[key] = str(len(m[name])) for name in ("not_for_lambda", "abstain_tau", "abstain_scale", "temperature", "logit_scale", "platt_a", "platt_b"): fields[name] = number(m[name]) out.extend(f' .{key} = {value},' for key, value in fields.items()) out.append('};') golden = (vectors or [])[:8] out.append(f'#define RD_GOLDEN_COUNT {len(golden)}') if golden: out.append('static const float rd_golden_inputs[][RD_MODEL_DIMS] = {') for row in golden: if len(row['features']) != m['dims']: raise ValueError('golden width mismatch') out.append('{' + ','.join(map(number, row['features'])) + '},') out.append('};') out.append('static const rd_result rd_golden_expected[] = {') for row in golden: a = row['answer'] index = m['labels'].index(a['choice']) if 'choice' in a else a.get('score', int(a.get('noul', 0) >= .5)) probs = a.get('probabilities', [a.get('noul', 0)]) if isinstance(probs, dict): probs = [probs[label] for label in m['labels']] out.append('{.index=' + str(index) + ',.probabilities={' + ','.join(map(number, probs)) + '},.confidence=' + number(a['confidence']) + ',.abstain=' + number(a['abstain']) + ',.noul=' + number(a.get('noul', 0)) + '},') out.append('};') out.extend(['#endif', '']) Path(path).parent.mkdir(parents=True, exist_ok=True) Path(path).write_text('\n'.join(out)) return {"sha256": digest, "quant_bits": bits, "quantized_parameter_bytes": weight_bytes+len(m["bias"])*4, "float_parameter_bytes": float_bytes+len(m["bias"])*4, "dims": m["dims"], "classes": len(m["labels"]), "source_calibrated": m["source_calibrated"], "quantized_calibration_validated": False} if __name__ == '__main__': p = argparse.ArgumentParser(description=__doc__) p.add_argument('snapshot', type=Path); p.add_argument('header', type=Path) p.add_argument('--vectors', type=Path, help='Rust reference vectors; embed first 8 boot self-tests') p.add_argument('--bits', type=int, choices=(8,16), default=16, help='16 is the accuracy profile; gate 8 on your validation data') a = p.parse_args() if a.snapshot.stat().st_size > 2_000_000: p.error('snapshot exceeds 2 MB') vectors = json.loads(a.vectors.read_text()) if a.vectors else None print(json.dumps(export(json.loads(a.snapshot.read_text()), a.header, vectors, a.bits), indent=2))