Spaces:
Running
Running
Download train.py from WideChaos/tiny-hash-intent: direct link, hf CLI and curl.
- Browser
- Download file 9.05 kB
-
https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/train.py
- Command line
-
hf download hf://spaces/WideChaos/tiny-hash-intent/train.py
-
curl -L -o train.py https://huggingface.co/spaces/WideChaos/tiny-hash-intent/resolve/main/train.py
9.05 kB
| """Freeze original-train membership, fit once, select on validation, freeze test inputs.""" | |
| import argparse | |
| from collections import Counter | |
| import hashlib, json, math, platform, time | |
| from pathlib import Path | |
| import numpy as np | |
| from model import ( | |
| CONFIG, | |
| PARAMETERS, | |
| Adam, | |
| features, | |
| file_sha, | |
| initialize, | |
| load_csv, | |
| logits_for, | |
| nll, | |
| normalized, | |
| batch_loss_grad, | |
| portable, | |
| decode_portable, | |
| ) | |
| def write(path, value): | |
| path.write_text( | |
| json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + "\n" | |
| ) | |
| def param_digest(p): | |
| h = hashlib.sha256() | |
| for k in PARAMETERS: | |
| h.update(k.encode()) | |
| h.update(p[k].astype("<f8").tobytes()) | |
| return h.hexdigest() | |
| def train(data, out): | |
| root = Path(__file__).resolve().parent | |
| if out.exists(): | |
| raise ValueError("A new output directory is required.") | |
| old = json.loads((root / "PROTOCOL-FREEZE.json").read_text()) | |
| for name, digest in old["sha256"].items(): | |
| if file_sha(root / name) != digest: | |
| raise ValueError("Frozen protocol/source changed: " + name) | |
| source = json.loads((data / "SOURCE.json").read_text()) | |
| files = source["source_origin"]["files"] | |
| for name, info in files.items(): | |
| if file_sha(data / name) != info["sha256"]: | |
| raise ValueError("Original source bytes changed: " + name) | |
| labels = json.loads((data / "categories.json").read_text()) | |
| assert len(labels) == 77 and len(set(labels)) == 77 | |
| rows = load_csv(data / "train.csv", labels) | |
| assert len(rows) == 10003 | |
| lookup = {l: i for i, l in enumerate(labels)} | |
| ys = np.array([lookup[r["category"]] for r in rows]) | |
| allx = [features(r["text"]) for r in rows] | |
| keys = [hashlib.sha256(normalized(r["text"]).encode()).hexdigest() for r in rows] | |
| valids = [i for i, k in enumerate(keys) if int(k, 16) % 10 == 0] | |
| validset = set(valids) | |
| trainids = [i for i in range(len(rows)) if i not in validset] | |
| traincounts = Counter(int(ys[i]) for i in trainids) | |
| valcounts = Counter(int(ys[i]) for i in valids) | |
| if len(traincounts) != 77 or not valids: | |
| raise ValueError( | |
| "Fixed hash split lacks training class support or validation rows; not resampled." | |
| ) | |
| assert not {keys[i] for i in trainids} & {keys[i] for i in valids} | |
| out.mkdir() | |
| names = [ | |
| "model.py", | |
| "train.py", | |
| "CONFIG.json", | |
| "PROTOCOL.md", | |
| "PROTOCOL-FREEZE.json", | |
| "test_model.py", | |
| ] | |
| prefit = { | |
| "phase": "before any gradient update", | |
| "configuration": CONFIG, | |
| "source": source, | |
| "source_sha256": {n: file_sha(data / n) for n in files}, | |
| "implementation_sha256": {n: file_sha(root / n) for n in names}, | |
| "environment": {"python": platform.python_version(), "numpy": np.__version__}, | |
| "labels": labels, | |
| "train_row_ids": trainids, | |
| "validation_row_ids": valids, | |
| "training_class_counts": [traincounts[c] for c in range(77)], | |
| "validation_class_counts": [valcounts[c] for c in range(77)], | |
| "normalized_groups": len(set(keys)), | |
| "training_rows": len(trainids), | |
| "validation_rows": len(valids), | |
| "scope": "hash split of observed normalized text, not source-family or IID guarantee; benchmark already known from earlier separate study", | |
| } | |
| write(out / "PREFIT.json", prefit) | |
| print( | |
| "PREFIT", | |
| file_sha(out / "PREFIT.json"), | |
| len(trainids), | |
| "train", | |
| len(valids), | |
| "validation", | |
| flush=True, | |
| ) | |
| xs = [allx[i] for i in trainids] | |
| ty = ys[trainids] | |
| vx = [allx[i] for i in valids] | |
| vy = ys[valids] | |
| p = initialize( | |
| CONFIG["feature_bins"], | |
| CONFIG["hidden_size"], | |
| CONFIG["classes"], | |
| CONFIG["init_seed"], | |
| CONFIG["init_std"], | |
| ) | |
| initial = param_digest(p) | |
| adam = Adam( | |
| p, CONFIG["learning_rate"], CONFIG["beta1"], CONFIG["beta2"], CONFIG["epsilon"] | |
| ) | |
| trace = [] | |
| best = math.inf | |
| bestepoch = None | |
| start = time.perf_counter() | |
| write( | |
| out / "initial-statistics.json", | |
| { | |
| "parameter_sha256": initial, | |
| "parameters": sum(x.size for x in p.values()), | |
| "validation_uncalibrated_nll": float(nll(logits_for(vx, p), vy).mean()), | |
| "scope": "initial untrained diagnostic, not eligible for epoch selection", | |
| }, | |
| ) | |
| for epoch in range(1, CONFIG["epochs"] + 1): | |
| order = np.random.default_rng(CONFIG["shuffle_seed_base"] + epoch).permutation( | |
| len(xs) | |
| ) | |
| online = 0.0 | |
| seen = 0 | |
| for begin in range(0, len(order), CONFIG["batch_size"]): | |
| batch = order[begin : begin + CONFIG["batch_size"]] | |
| loss, ce, g = batch_loss_grad( | |
| [xs[int(i)] for i in batch], ty[batch], p, CONFIG["l2"] | |
| ) | |
| adam.update(p, g) | |
| online += ce * len(batch) | |
| seen += len(batch) | |
| tl = logits_for(xs, p) | |
| vl = logits_for(vx, p) | |
| train_nll = float(nll(tl, ty).mean()) | |
| val_nll = float(nll(vl, vy).mean()) | |
| if not np.isfinite(train_nll) or not np.isfinite(val_nll): | |
| raise ValueError("Nonfinite epoch evaluation.") | |
| selected = val_nll < best - 1e-12 | |
| if selected: | |
| best = val_nll | |
| bestepoch = epoch | |
| np.savez_compressed(out / "model-float64.npz", **p) | |
| trace.append( | |
| { | |
| "epoch": epoch, | |
| "batch_steps_so_far": adam.step, | |
| "examples_fit_this_epoch": seen, | |
| "train_online_cross_entropy": online / seen, | |
| "train_epoch_end_nll": train_nll, | |
| "validation_nll": val_nll, | |
| "selected_at_this_point": selected, | |
| "elapsed_seconds": time.perf_counter() - start, | |
| } | |
| ) | |
| write(out / "trace.json", trace) | |
| print( | |
| f"epoch{epoch:02d} train_nll={train_nll:.6f} val_nll={val_nll:.6f} best={bestepoch}", | |
| flush=True, | |
| ) | |
| with np.load(out / "model-float64.npz", allow_pickle=False) as z: | |
| selected = {k: z[k].copy() for k in PARAMETERS} | |
| if param_digest(selected) == initial: | |
| raise ValueError("No parameter change; not a completed fit.") | |
| vl = logits_for(vx, selected) | |
| grid = [ | |
| {"temperature": t, "validation_nll": float(nll(vl, vy, t).mean())} | |
| for t in CONFIG["temperature_grid"] | |
| ] | |
| minimum = min(r["validation_nll"] for r in grid) | |
| eligible = [r for r in grid if r["validation_nll"] <= minimum + 1e-12] | |
| temperature = min( | |
| eligible, key=lambda r: (abs(r["temperature"] - 1), r["temperature"]) | |
| )["temperature"] | |
| exported = portable(selected, labels, temperature) | |
| write(out / "model-int8.json", exported) | |
| q = decode_portable(exported) | |
| qvl = logits_for(vx, q) | |
| np.savez_compressed( | |
| out / "validation-logits.npz", | |
| float_logits=vl, | |
| int8_logits=qvl, | |
| gold=vy, | |
| original_train_row_ids=np.array(valids, dtype=np.int64), | |
| ) | |
| calibration = { | |
| "selected_epoch": bestepoch, | |
| "selected_temperature": temperature, | |
| "validation_n": len(valids), | |
| "temperature_grid": grid, | |
| "quantized_validation_nll_at_inherited_temperature": float( | |
| nll(qvl, vy, temperature).mean() | |
| ), | |
| "scope": "grid selected only on validation float model; int8 inherited same T, no new fit", | |
| } | |
| write(out / "calibration.json", calibration) | |
| required = [ | |
| "PREFIT.json", | |
| "initial-statistics.json", | |
| "trace.json", | |
| "model-float64.npz", | |
| "model-int8.json", | |
| "validation-logits.npz", | |
| "calibration.json", | |
| ] | |
| pretest = { | |
| "phase": "training complete, before this model first scores official test", | |
| "configuration": CONFIG, | |
| "selected_epoch": bestepoch, | |
| "selected_temperature": temperature, | |
| "initial_parameter_sha256": initial, | |
| "selected_parameter_sha256": param_digest(selected), | |
| "fit_steps": adam.step, | |
| "total_examples_fit": len(trainids) * CONFIG["epochs"], | |
| "artifact_sha256": {n: file_sha(out / n) for n in required}, | |
| "implementation_sha256": prefit["implementation_sha256"], | |
| "source_sha256": prefit["source_sha256"], | |
| "one_training_run": True, | |
| "scope": "one fit with float/int8 and raw/calibrated representations; prior benchmark knowledge disclosed", | |
| } | |
| write(out / "PRETEST.json", pretest) | |
| print( | |
| "PRETEST", | |
| file_sha(out / "PRETEST.json"), | |
| "selected epoch", | |
| bestepoch, | |
| "T", | |
| temperature, | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| a = argparse.ArgumentParser() | |
| a.add_argument("--data", type=Path, default=Path("data")) | |
| a.add_argument("--output", type=Path, required=True) | |
| x = a.parse_args() | |
| train(x.data, x.output) | |