File size: 7,238 Bytes
1a2bc7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | # Digit network for the Voltorb reader (reader.ts readDigit): a 24x20 grey window around a digit cell
# (2 samples per native px) in, digit 0-9 out. Trained on clean board digits plus photo digits (x4) with heavy
# augmentation. Usage: cnn.py <workdir>: reads data.json, writes net.json ({name: [scale, base64 int8]}).
import base64, json, random, sys
import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from scipy.ndimage import affine_transform, gaussian_filter, uniform_filter1d
W = sys.argv[1]
torch.manual_seed(0); random.seed(0); np.random.seed(0)
data = json.load(open(W + '/data.json'))
# hand-labelled boxes too blurred to learn from
noisy = {'2026-11-01T19:29:19.179Z.jpeg|' + str(b) for b in (5, 6, 7, 8)} | {'2026-11-09T05:58:52.261Z.jpeg|' + str(b) for b in (2, 5, 9)}
photo = [p for p in data['photo'] if p['f'] + '|' + str(p['box']) not in noisy]
def arr(x): return np.array(x['px'], np.float32).reshape(24, 20)
def norm(a): a = a - a.mean(); return a / (a.std() + 1e-3)
class Net(nn.Module):
def __init__(s):
super().__init__()
s.c1 = nn.Conv2d(1, 8, 3, padding=1); s.c2 = nn.Conv2d(8, 16, 3, padding=1); s.f1 = nn.Linear(16 * 6 * 5, 32); s.f2 = nn.Linear(32, 10)
def forward(s, x):
x = F.max_pool2d(F.relu(s.c1(x)), 2); x = F.max_pool2d(F.relu(s.c2(x)), 2)
return s.f2(F.relu(s.f1(x.flatten(1))))
def augment(a):
# misalignment: up to ~1.5 native px, plus a little slant / rotation / scale
t = random.uniform(-0.12, 0.12); sh = random.uniform(-0.15, 0.15); sc = random.uniform(0.9, 1.1)
M = np.array([[sc * np.cos(t), -np.sin(t) + sh], [np.sin(t), sc * np.cos(t)]])
c = np.array([12, 10]); off = c - M @ c + np.array([random.uniform(-3, 3), random.uniform(-3, 3)])
a = affine_transform(a, M, off, order=1, mode='nearest')
if random.random() < 0.6: a = gaussian_filter(a, random.uniform(0.3, 1.6)) # out of focus
if random.random() < 0.2: a = uniform_filter1d(a, random.randint(2, 4), axis=random.randint(0, 1)) # motion blur
a = a * random.uniform(0.35, 1.4) + random.uniform(-70, 70) # lighter / darker
if random.random() < 0.3: a = 255 * (np.clip(a, 0, 255) / 255) ** random.uniform(0.6, 1.6) # gamma
if random.random() < 0.6: # light leak / glare
yy, xx = np.mgrid[0:24, 0:20]; cy, cx, r = random.uniform(-6, 30), random.uniform(-6, 26), random.uniform(4, 20)
a = a + random.uniform(30, 160) * np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * r * r))
if random.random() < 0.3: # screen sheen: a straight-edged band
yy, xx = np.mgrid[0:24, 0:20]; t = random.uniform(0, np.pi) # washes part of the digit out
d = (xx - random.uniform(0, 20)) * np.cos(t) + (yy - random.uniform(0, 24)) * np.sin(t)
m = random.uniform(0.3, 0.75) / (1 + np.exp(-d / random.uniform(0.3, 2))) # 0 on one side, up to 0.75 on the other
a = a * (1 - m) + 255 * m
a = a + np.random.normal(0, random.uniform(0, 20), a.shape) # sensor noise
if random.random() < 0.3: a = np.round(a / 16) * 16 # compression banding
return a
# ponytail: clean digits are one pixel font, so a few thousand cover it; caps training time as uploads grow
C = random.sample([(arr(x), int(x['d'])) for x in data['clean']], min(len(data['clean']), 5000))
m = Net(); hard = []
try: # start from the live network (retrain.mjs writes it): more data refines it instead of starting over
live = json.load(open(W + '/net-live.json'))
m.load_state_dict({k: torch.tensor(np.frombuffer(base64.b64decode(live[k][1]), np.int8).astype(np.float32) * live[k][0]).view_as(v) for k, v in m.state_dict().items()})
print('starting from the live digit network', flush=True)
# hard examples: the live network on the harvested photo digits (30 per board, in order: tens, units, Voltorbs per
# hint), read the way reader.ts does. 6 extra copies of each digit it gets wrong, 3 of each it gets right with under
# 0.9 confidence (held-out boards: 99 of 20,130 digits wrong, against 106 for a plain fine-tune and 115 for live)
harvest = [p for p in photo if p['box'] == -1]; seen = {}; wrong = unsure = 0
if harvest:
with torch.no_grad(): P = F.softmax(m(torch.tensor(np.stack([norm(arr(p)) for p in harvest])[:, None])), 1).numpy()
for p, pr in zip(harvest, P):
k = seen.get(p['f'], 0) % 3; seen[p['f']] = seen.get(p['f'], 0) + 1; y = int(p['d'])
if k == 0: pr = np.array([pr[0], pr[1] + pr[7]]) # tens: 0 or 1, the network's 7 counts as 1
elif k == 2: pr = pr[:6] # Voltorbs: 0-5
ok = int(pr.argmax()) == y; sure = y < len(pr) and pr[y] >= 0.9
wrong += not ok; unsure += ok and not sure
hard += [(arr(p), y)] * (6 if not ok else 0 if sure else 3)
print(f'live gets {wrong} of {len(harvest)} harvested digits wrong, {unsure} right but unsure: {len(hard)} extra copies', flush=True)
except FileNotFoundError: pass
# photo digits repeated until they weigh about 20k per epoch (×4 back when there were few; once when there are many)
P = [(arr(x), int(x['d'])) for x in photo] + hard
items = C + P * max(1, round(20000 / max(1, len(P))))
opt = torch.optim.Adam(m.parameters(), 2e-3)
for e in range(60):
random.shuffle(items)
for i in range(0, len(items), 64):
b = items[i:i + 64]
x = torch.tensor(np.stack([norm(augment(a)) for a, _ in b])[:, None], dtype=torch.float32)
opt.zero_grad(); F.cross_entropy(m(x), torch.tensor([y for _, y in b])).backward(); opt.step()
if e % 10 == 0: print('epoch', e, flush=True)
out = {}
for k, v in m.state_dict().items():
a = v.numpy().astype(np.float32); sc = float(f'{float(np.abs(a).max()) / 127 or 1.0:.6g}')
out[k] = [sc, base64.b64encode(np.clip(np.round(a / sc), -127, 127).astype(np.int8).tobytes()).decode()]
json.dump(out, open(W + '/net.json', 'w'))
# the shipped (int8) weights on the hand-checked digits, read the way reader.ts does: each box is tens, units,
# Voltorb count; a tens digit is 0 or 1 (with the network's 7 counted as 1), a count is 0-5
m.load_state_dict({k: torch.tensor(np.frombuffer(base64.b64decode(b), np.int8).astype(np.float32) * sc).view_as(v) for (k, v), (sc, b) in zip(m.state_dict().items(), out.values())})
m.eval(); hand = [p for p in photo if p['box'] != -1]; right = 0
with torch.no_grad():
for i, p in enumerate(hand):
pr = F.softmax(m(torch.tensor(norm(arr(p)))[None, None]), 1)[0].numpy()
if i % 3 == 0: pr[1] += pr[7]; pr = pr[:2]
elif i % 3 == 2: pr = pr[:6]
right += int(pr.argmax()) == int(p['d'])
json.dump({'clean': len(C), 'photo': len(photo), 'handRight': right, 'hand': len(hand)}, open(W + '/trained.json', 'w')) # for the post's "Model updates"
print(f'hand-checked digits read right: {right}/{len(hand)}')
print('trained on', len(C), 'clean +', len(photo), 'photo digits')
|