Cotton code
522 lines · 23.0 KB · PythonRaw
#!/usr/bin/env python3"""The ink classifier: a small 1-D conv net over one group of strokes (a letter or a digit), trained on the ink corpus.    train.py features <corpus.jsonl>            # each line's input, as JSON (no ML stack needed)    train.py train <corpus dir> <out dir> [--rotation DEG]                                                # train, measure, export Core ML + TFLite, prove parity    train.py evaluate <corpus dir> <model.pt>   # a trained net on the held-out writers, upright and turned`--rotation DEG` (the alphabet's `train_rotation`, owner, 3 Nov 2026: "if Iwrite C at an angle it classifies as other things") also turns eachtraining group by a random angle within ±DEG about its centre BEFORE thecontract's normalisation, every batch afresh — as a hand writing at aslant does — before the usual slant, turn and stretch (`augment`). Withoutit the run is the shipped one, bit for bit: no random number is drawn for it.The held-out writers are measured three ways: upright, turned ±20° andturned ±35° (each group both ways, each as its own class admits it), so aslant's cost and its cure are seen.The input is the harness's contract, `ink_input.encode` (the ink-mlkitlane's reference encoder, copied verbatim): `points` [1, 64, 3] of[x, y, pen_up] over the strokes joined in order (the jumps between them arepath, pen_up 1) in the unit box, and `stroke_count` [1, 1]. The output is`probabilities` [1, 62], a softmax over a–z, A–Z, then 0–9; the case-foldedreading (search is case-free) is each letter's lower and upper summed and thedigits as they are, 36 symbols.What a surface admits decides a reading (owner, 3 Nov 2026: "I also wantto include having numbers"): a deck of names takes letters only, a numericcolumn digits only, so a letter's number never pays for 0/O, 1/l, 5/S. Theheld-out writers are measured that way — `admitted`: a letter read among the26 letters, a digit among the 10 digits — and as a mixed column reads them,`any`: among all 36 — and exact, `letter_case`: among all 62.The split is BY WRITER: UJIpenchars2's `trn_` writers and 80% of HWRT's train;its `tst_` writers and the other 20% of HWRT's (by a hash of the writer id)are never seen until the numbers are taken; the HWRT ids held out arewritten to `<corpus dir>/heldout-writers.json` so the harness scores the samesplit. No early stopping and no choicemade on the held-out writers: the recipe is fixed (`EPOCHS`, `SEED`).Training needs `scripts/ink/requirements-train.txt` (Python 3.11). The netis trained in torch; Core ML is converted from the traced torch net(`coremltools`, float32), and TFLite from a Keras twin built layer for layerand handed the torch weights — the same numbers, two files — then both arerun on 100 held-out groups and must give the same answers. Out:`ink-classifier.mlpackage`, `ink-classifier.tflite`, `ink-classifier.pt`,`results.json` and `results.md` in the out dir."""import hashlibimport jsonimport osimport sysimport timesys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import ink_input  # noqa: E402LETTERS = "abcdefghijklmnopqrstuvwxyz"CLASSES = ink_input.CLASSES# The case-folded symbols: the 26 letters, then the 10 digits.SYMBOLS = list(LETTERS) + CLASSES[52:]EPOCHS = int(os.environ.get("INK_EPOCHS", "80"))  # the recipe; INK_EPOCHS only for a smoke runSEED = 7MOST_STROKES = 6# The hidden layer before the classes: 192 wide since the digits came (62# classes through the 128 sized for 52 read the held-out letters 0.1 to 0.7# points worse across three seeds; 192 reads them as the 52-class net did,# 3 Nov 2026).WIDTH = 192def class_of(row):    return ink_input.label_index(row["label"], row["case"])def folded(probabilities):    """[b, 62] → [b, 36]: each letter's two cases summed, the digits as they are."""    import torch    return torch.cat([probabilities[:, :26] + probabilities[:, 26:52], probabilities[:, 52:]], 1)def symbol_of(truth):    """A class (0–61) as its folded symbol (0–35)."""    import torch    return torch.where(truth >= 52, truth - 26, truth % 26)def admitted(fold, truth):    """The folded symbol read where only the truth's own class is admitted:    a letter among the 26 letters, a digit among the 10 digits."""    import torch    letter = fold[:, :26].argmax(1)    digit = fold[:, 26:].argmax(1) + 26    return torch.where(truth >= 52, digit, letter)def held_out(row):    """The writers never trained on."""    if row["source"] == "ujipenchars2":        return row["writer"].startswith("tst_")    return int(hashlib.md5(f"{row['source']}:{row['writer']}".encode()).hexdigest(), 16) % 5 == 0def rotation_flag(argv):    """`--rotation DEG` among `argv`, in degrees (0 without it), and the rest."""    if "--rotation" not in argv:        return 0.0, argv    at = argv.index("--rotation")    return float(argv[at + 1]), argv[:at] + argv[at + 2:]def raw_tensors(rows, feats):    """Each group's 64 samples back in its own pt (the contract's    normalisation undone over its input box) and its input points, padded,    with their mask: what a turn before the normalisation needs."""    import torch    most = max(sum(len(s) for s in r["strokes"]) for r in rows)    samples = torch.zeros(len(rows), 64, 3, dtype=torch.float64)    points = torch.zeros(len(rows), most, 2, dtype=torch.float64)    mask = torch.zeros(len(rows), most, dtype=torch.bool)    for i, (r, (encoded, _)) in enumerate(zip(rows, feats)):        xy = [(float(p[0]), float(p[1])) for s in r["strokes"] for p in s]        xs, ys = [p[0] for p in xy], [p[1] for p in xy]        mx, my, w, h = min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys)        size = max(w, h) if max(w, h) >= 1e-6 else 1.0        ox, oy = (1 - w / size) / 2, (1 - h / size) / 2        e = torch.tensor(encoded, dtype=torch.float64)        samples[i, :, 0] = (e[:, 0] - ox) * size + mx        samples[i, :, 1] = (e[:, 1] - oy) * size + my        samples[i, :, 2] = e[:, 2]        points[i, :len(xy)] = torch.tensor(xy, dtype=torch.float64)        mask[i, :len(xy)] = True    return samples, points, maskdef turned(samples, points, mask, angle):    """The groups turned by `angle` (radians, one a group) about their    centres, then normalised as the contract does (`ink_input.encode` step    3, over the turned input points): float32 [b, 64, 3]."""    import torch    c, s = torch.cos(angle)[:, None], torch.sin(angle)[:, None]    big = torch.finfo(torch.float64).max    lo = torch.where(mask[..., None], points, big).amin(1)    hi = torch.where(mask[..., None], points, -big).amax(1)    centre = (lo + hi) / 2    def turn(xy):        d = xy - centre[:, None, :]        return torch.stack([centre[:, None, 0] + c * d[..., 0] - s * d[..., 1], centre[:, None, 1] + s * d[..., 0] + c * d[..., 1]], -1)    p = turn(points)    lo = torch.where(mask[..., None], p, big).amin(1)    hi = torch.where(mask[..., None], p, -big).amax(1)    w, h = hi[:, 0] - lo[:, 0], hi[:, 1] - lo[:, 1]    size = torch.maximum(w, h)    size = torch.where(size < 1e-6, torch.ones_like(size), size)    offset = torch.stack([(1 - w / size) / 2, (1 - h / size) / 2], -1)    xy = (turn(samples[..., :2]) - lo[:, None, :]) / size[:, None, None] + offset[:, None, :]    return torch.cat([xy, samples[..., 2:]], 2).float()def measured_turned(model, samples, points, mask, S, truth, degrees):    """The share read right, case-folded and as its own class admits it,    with every group turned by +`degrees` and by −`degrees`."""    import math    import torch    right = 0    with torch.no_grad():        for sign in (1, -1):            angle = torch.full((len(samples),), sign * math.radians(degrees), dtype=torch.float64)            fold = folded(model(turned(samples, points, mask, angle), S))            right += int((admitted(fold, truth) == symbol_of(truth)).sum())    return round(100 * right / (2 * len(samples)), 1)def load(corpus):    rows = []    for name in sorted(os.listdir(corpus)):        if name.endswith(".jsonl") and name != "replay.jsonl":            with open(os.path.join(corpus, name)) as f:                rows += [json.loads(l) for l in f if l.strip()]    return rowsdef features_command(path):    with open(path) as f:        for line in f:            if line.strip():                row = json.loads(line)                points, count = ink_input.encode(row["strokes"])                print(json.dumps({"points": [[round(v, 6) for v in p] for p in points], "stroke_count": count}))# MARK: Training (torch, Core ML, TensorFlow from here down)def net_class():    import torch    from torch import nn    class InkNet(nn.Module):        def __init__(self):            super().__init__()            self.conv1 = nn.Conv1d(3, 32, 5, padding=2)            self.conv2 = nn.Conv1d(32, 64, 5, padding=2)            self.conv3 = nn.Conv1d(64, 96, 3, padding=1)            self.conv4 = nn.Conv1d(96, 128, 3, padding=1)            self.pool = nn.MaxPool1d(2)            self.fc1 = nn.Linear(257, WIDTH)            self.fc2 = nn.Linear(WIDTH, len(CLASSES))            self.drop = nn.Dropout(0.3)        def logits(self, points, strokes):            x = points.transpose(1, 2)            x = torch.relu(self.conv1(x))            x = self.pool(torch.relu(self.conv2(x)))            x = torch.relu(self.conv3(x))            x = torch.relu(self.conv4(x))            g = torch.cat([x.mean(dim=2), x.amax(dim=2), torch.clamp(strokes, 0, MOST_STROKES) / MOST_STROKES], dim=1)            return self.fc2(self.drop(torch.relu(self.fc1(g))))        def forward(self, points, stroke_count):            return torch.softmax(self.logits(points, stroke_count), dim=1)    return InkNetdef augment(points, rng):    """A random slant, turn, stretch and wobble of each group, back in the unit box."""    import torch    b = points.shape[0]    angle = (torch.rand(b, generator=rng) - 0.5) * (2 * 0.26)    shear = (torch.rand(b, generator=rng) - 0.5) * (2 * 0.3)    sx = 0.75 + torch.rand(b, generator=rng) * 0.5    sy = 0.75 + torch.rand(b, generator=rng) * 0.5    c, s = torch.cos(angle), torch.sin(angle)    m = torch.stack([torch.stack([c * sx, (-s + shear) * sy], 1), torch.stack([s * sx, c * sy], 1)], 1)    xy = points[:, :, :2] - 0.5    xy = torch.einsum("bij,bnj->bni", m, xy)    xy = xy + torch.randn(xy.shape, generator=rng) * 0.008    lo, hi = xy.amin(1, keepdim=True), xy.amax(1, keepdim=True)    size = (hi - lo).amax(2, keepdim=True).clamp_min(1e-6)    xy = (xy - lo) / size + (1 - (hi - lo) / size) / 2    return torch.cat([xy, points[:, :, 2:]], 2)def keras_twin(model):    """The torch net layer for layer in Keras, holding the torch weights."""    import numpy as np    import tensorflow as tf    k = tf.keras    points = k.Input((64, 3), name="points", batch_size=1)    strokes = k.Input((1,), name="stroke_count", batch_size=1)    convs = [k.layers.Conv1D(c.out_channels, c.kernel_size[0], padding="same", activation="relu")             for c in (model.conv1, model.conv2, model.conv3, model.conv4)]    x = convs[0](points)    x = k.layers.MaxPooling1D(2)(convs[1](x))    x = convs[3](convs[2](x))    s = k.layers.Lambda(lambda v: tf.clip_by_value(v, 0.0, float(MOST_STROKES)) / MOST_STROKES)(strokes)    g = k.layers.Concatenate()([k.layers.GlobalAveragePooling1D()(x), k.layers.GlobalMaxPooling1D()(x), s])    fc1 = k.layers.Dense(WIDTH, activation="relu")    fc2 = k.layers.Dense(len(CLASSES))    probabilities = k.layers.Softmax(name="probabilities")(fc2(fc1(g)))    twin = k.Model([points, strokes], probabilities)    for layer, conv in zip(convs, (model.conv1, model.conv2, model.conv3, model.conv4)):        layer.set_weights([conv.weight.detach().numpy().transpose(2, 1, 0), conv.bias.detach().numpy()])    for layer, fc in ((fc1, model.fc1), (fc2, model.fc2)):        layer.set_weights([fc.weight.detach().numpy().T, fc.bias.detach().numpy()])    return twindef train_command(corpus, out, rotation=0.0):    import numpy as np    import torch    from collections import Counter    torch.manual_seed(SEED)    os.makedirs(out, exist_ok=True)    rows = load(corpus)    feats = [ink_input.encode(r["strokes"]) for r in rows]    X = torch.tensor([f[0] for f in feats], dtype=torch.float32)    S = torch.tensor([[float(f[1])] for f in feats], dtype=torch.float32)    Y = torch.tensor([class_of(r) for r in rows])    hold = torch.tensor([held_out(r) for r in rows])    tr, te = (~hold).nonzero().squeeze(1), hold.nonzero().squeeze(1)    split = {        "train": len(tr), "held_out": len(te),        "train_writers": len({(r["source"], r["writer"]) for r, h in zip(rows, hold.tolist()) if not h}),        "held_out_writers": len({(r["source"], r["writer"]) for r, h in zip(rows, hold.tolist()) if h}),        "held_out_by_source": dict(Counter(r["source"] for r, h in zip(rows, hold.tolist()) if h)),    }    print(json.dumps(split), flush=True)    with open(os.path.join(corpus, "heldout-writers.json"), "w") as f:        json.dump(sorted({r["writer"] for r, h in zip(rows, hold.tolist()) if h and r["source"] == "hwrt"}), f)    Net = net_class()    model = Net()    params = sum(p.numel() for p in model.parameters())    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-4)    steps = EPOCHS * ((len(tr) + 127) // 128)    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-3, total_steps=steps)    rng = torch.Generator().manual_seed(SEED)    if rotation:        import math        raw = raw_tensors(rows, feats)    started = time.time()    for epoch in range(EPOCHS):        model.train()        order = tr[torch.randperm(len(tr), generator=rng)]        total = 0.0        for i in range(0, len(order), 128):            idx = order[i:i + 128]            batch = X[idx]            if rotation:                angle = ((torch.rand(len(idx), generator=rng) - 0.5) * 2 * math.radians(rotation)).double()                batch = turned(raw[0][idx], raw[1][idx], raw[2][idx], angle)            loss = torch.nn.functional.cross_entropy(model.logits(augment(batch, rng), S[idx]), Y[idx], label_smoothing=0.05)            opt.zero_grad()            loss.backward()            opt.step()            sched.step()            total += loss.item() * len(idx)        if epoch % 10 == 9 or epoch == EPOCHS - 1:            print(f"epoch {epoch + 1}: loss {total / len(tr):.3f}", flush=True)    seconds = time.time() - started    model.eval()    truth = Y[te]    test_rows = [rows[i] for i in te.tolist()]    measured = measure(model, X[te], S[te], truth, test_rows)    held = raw_tensors(test_rows, [feats[i] for i in te.tolist()])    rotated = turned_by_class(model, held, S[te], truth)    torch.save(model.state_dict(), os.path.join(out, "ink-classifier.pt"))    exported = export(model, X[te][:100], S[te][:100], out)    results = {        "params": params, "epochs": EPOCHS, "seed": SEED, "train_rotation": rotation, "train_seconds": round(seconds),        "held_out_turned_admitted": rotated,        "split": split, **measured,        **exported,    }    with open(os.path.join(out, "results.json"), "w") as f:        json.dump(results, f, indent=1)    print(json.dumps(results, indent=1))def measure(model, X, S, truth, rows):    """The held-out writers read three ways — `admitted` (a letter among the    letters, a digit among the digits: a deck of names, a numeric column),    `any` (among all 36 folded symbols: a column of mixed text) and    `letter_case` (among all 62) — by slice, by symbol, and the confusions."""    import torch    from collections import Counter    with torch.no_grad():        probabilities = model(X, S)    fold = folded(probabilities)    symbol = symbol_of(truth)    pred62, pred_any, pred_admitted = probabilities.argmax(1), fold.argmax(1), admitted(fold, truth)    right = {"admitted": pred_admitted == symbol, "any": pred_any == symbol, "letter_case": pred62 == truth}    def share(mask, keep):        keep = torch.tensor(keep)        return round(100 * mask[keep].float().mean().item(), 1) if keep.any() else None    def slice_(keep):        return {"n": int(sum(keep)), **{way: share(r, keep) for way, r in right.items()}}    slices = {        "all": slice_([True] * len(rows)),        "letters": slice_([r["case"] != "digit" for r in rows]),        "digits": slice_([r["case"] == "digit" for r in rows]),        "lower": slice_([r["case"] == "lower" for r in rows]),        "upper": slice_([r["case"] == "upper" for r in rows]),    }    for src in sorted({r["source"] for r in rows}):        slices[src] = slice_([r["source"] == src for r in rows])        slices[f"{src} letters"] = slice_([r["source"] == src and r["case"] != "digit" for r in rows])    for kind in sorted({r["input"] for r in rows}):        slices[f"input {kind}"] = slice_([r["input"] == kind for r in rows])    per_symbol = {}    for si, name in enumerate(SYMBOLS):        keep = [s == si for s in symbol.tolist()]        if any(keep):            per_symbol[name] = {"n": sum(keep), "admitted": share(right["admitted"], keep), "any": share(right["any"], keep)}    pairs = lambda names, t, p: Counter((names[a], names[b]) for a, b in zip(t.tolist(), p.tolist()) if a != b)    return {        "held_out": slices, "per_symbol": per_symbol,        "top_confusions_admitted": [[t, p, n] for (t, p), n in pairs(SYMBOLS, symbol, pred_admitted).most_common(15)],        "top_confusions_any": [[t, p, n] for (t, p), n in pairs(SYMBOLS, symbol, pred_any).most_common(15)],        "top_confusions_62": [[t, p, n] for (t, p), n in pairs(CLASSES, truth, pred62).most_common(15)],    }def turned_by_class(model, held, S, truth):    """The letters and the digits turned ±20° and ±35°, each as its class admits it."""    out = {}    for name, keep in (("letters", truth < 52), ("digits", truth >= 52)):        index = keep.nonzero().squeeze(1)        if len(index):            part = tuple(t[index] for t in held)            out[name] = {f"{d}": measured_turned(model, *part, S[index], truth[index], d) for d in (20, 35)}    return outdef export(model, X, S, out):    """Core ML from the traced net, TFLite from its Keras twin; both run on    the same held-out groups, their answers compared, their time taken."""    import numpy as np    import torch    import coremltools as ct    import tensorflow as tf    class Traced(torch.nn.Module):        def __init__(self, m):            super().__init__()            self.m = m        def forward(self, points, strokes):            return self.m(points, strokes)    traced = torch.jit.trace(Traced(model).eval(), (X[:1], S[:1]))    ml = ct.convert(        traced,        inputs=[ct.TensorType(name="points", shape=(1, 64, 3)), ct.TensorType(name="stroke_count", shape=(1, 1))],        outputs=[ct.TensorType(name="probabilities")],        convert_to="mlprogram", compute_precision=ct.precision.FLOAT32,        minimum_deployment_target=ct.target.iOS16,    )    ml.short_description = "Ink letter and digit classifier (the ink harness's input contract): points [1,64,3] + stroke_count [1,1] -> probabilities [1,62], a-z, A-Z, then 0-9."    names = ([i.name for i in ml.get_spec().description.input], [o.name for o in ml.get_spec().description.output])    assert names == (["points", "stroke_count"], ["probabilities"]), names    ml_path = os.path.join(out, "ink-classifier.mlpackage")    ml.save(ml_path)    twin = keras_twin(model)    converter = tf.lite.TFLiteConverter.from_keras_model(twin)    tfl_bytes = converter.convert()    tfl_path = os.path.join(out, "ink-classifier.tflite")    with open(tfl_path, "wb") as f:        f.write(tfl_bytes)    interp = tf.lite.Interpreter(model_path=tfl_path)    interp.allocate_tensors()    ins = {d["name"]: d["index"] for d in interp.get_input_details()}    outs = interp.get_output_details()    def tfl(points, strokes):        for name, index in ins.items():            interp.set_tensor(index, strokes if "stroke_count" in name else points)        interp.invoke()        return interp.get_tensor(outs[0]["index"])    def fold(p):        return np.concatenate([p[..., :26] + p[..., 26:52], p[..., 52:]], -1)    with torch.no_grad():        t_letter = model(X, S).numpy()    t_folded = fold(t_letter)    mismatch = {"coreml": 0, "tflite": 0}    worst = {"coreml": 0.0, "tflite": 0.0}    times = {"torch": [], "coreml": [], "tflite": []}    for i in range(len(X)):        p, s = X[i:i + 1].numpy(), S[i:i + 1].numpy()        a = time.perf_counter(); r = ml.predict({"points": p, "stroke_count": s}); times["coreml"].append(time.perf_counter() - a)        a = time.perf_counter(); l2 = tfl(p, s); times["tflite"].append(time.perf_counter() - a)        with torch.no_grad():            a = time.perf_counter(); model(X[i:i + 1], S[i:i + 1]); times["torch"].append(time.perf_counter() - a)        for name, l in (("coreml", r["probabilities"]), ("tflite", l2)):            l = np.asarray(l).reshape(-1)            f = fold(l)            if l.argmax() != t_letter[i].argmax() or f.argmax() != t_folded[i].argmax():                mismatch[name] += 1            worst[name] = max(worst[name], float(np.abs(l - t_letter[i]).max()))    def size(path):        if os.path.isdir(path):            return sum(os.path.getsize(os.path.join(d, n)) for d, _, ns in os.walk(path) for n in ns)        return os.path.getsize(path)    return {        "parity_groups": len(X),        "parity_answer_mismatches_vs_torch": mismatch,        "parity_max_abs_probability_difference_vs_torch": {k: float(f"{v:.2e}") for k, v in worst.items()},        "inference_ms_median_per_group_mac": {k: round(1000 * sorted(v)[len(v) // 2], 3) for k, v in times.items()},        "bytes": {"mlpackage": size(ml_path), "tflite": size(tfl_path), "pt": size(os.path.join(out, "ink-classifier.pt"))},    }def evaluate_command(corpus, weights):    """A trained net (`ink-classifier.pt`) on the held-out writers: upright    (admitted, any, letter_case), and turned ±20° and ±35° as admitted."""    import torch    rows = [r for r in load(corpus) if held_out(r)]    feats = [ink_input.encode(r["strokes"]) for r in rows]    X = torch.tensor([f[0] for f in feats], dtype=torch.float32)    S = torch.tensor([[float(f[1])] for f in feats], dtype=torch.float32)    truth = torch.tensor([class_of(r) for r in rows])    model = net_class()()    model.load_state_dict(torch.load(weights, weights_only=True))    model.eval()    measured = measure(model, X, S, truth, rows)    held = raw_tensors(rows, feats)    print(json.dumps({"n": len(rows), "upright": measured["held_out"], "turned": turned_by_class(model, held, S, truth),                      "top_confusions_62": measured["top_confusions_62"][:10]}, indent=1))def main(argv):    rotation, argv = rotation_flag(argv)    if len(argv) == 3 and argv[1] == "features":        features_command(argv[2])    elif len(argv) == 4 and argv[1] == "train":        train_command(argv[2], argv[3], rotation)    elif len(argv) == 4 and argv[1] == "evaluate":        evaluate_command(argv[2], argv[3])    else:        sys.exit("usage: train.py features <corpus.jsonl> | train.py train <corpus dir> <out dir> [--rotation DEG]"                 " | train.py evaluate <corpus dir> <model.pt>")if __name__ == "__main__":    main(sys.argv)