#!/usr/bin/env python3 """Independent check of uai32's maths, in numpy (no C code involved). python3 refcheck.py MODEL DATA 1. re-implements inference from the documented file format and prints accuracy/loss to compare with `uai32 test DATA MODEL` 2. compares one C SGD step against the analytic gradient of softmax cross-entropy (needs ./uai32 in the same directory) Exit status 0 if both agree, 1 otherwise. """ import os, subprocess, sys, tempfile, re, math import numpy as np def load(path): b = open(path, "rb").read() magic, ni, nh, no = np.frombuffer(b[:8], " float32 bits w = w.view(" 0), np.append(xn, 1)) with tempfile.TemporaryDirectory() as d: one, m2 = os.path.join(d, "one.txt"), os.path.join(d, "m.model") np.savetxt(one, [np.append(xi, yi)], fmt="%.8g") open(m2, "wb").write(open(model, "rb").read()) subprocess.run(["./uai32", "train", one, m2, "0", "1", str(lr)], capture_output=True, check=True) _, _, W1b, W2b = load(m2) # The C program rounds weights to bfloat16 when saving (relative error up to 2^-8), so judge only the # weights whose update is at least 16x that noise; for them (step - gradient)/gradient must be small. for name, before, after, g in (("W1", W1, W1b, gW1), ("W2", W2, W2b, gW2)): step = (before - after) / lr; big = np.abs(g) * lr > np.abs(after) * 2 ** -4 + 1e-6 err = (np.abs(step[big] - g[big]) / np.abs(g[big])).max() if big.any() else 1.0 print(f"gradient {name}: {int(big.sum())} weights checked, max relative error {err:.3g}") same &= big.any() and err < 0.1 print("AGREE" if same else "DISAGREE"); return 0 if same else 1 if __name__ == "__main__": sys.exit(main(*sys.argv[1:3]))