Spaces:
Running
Running
File size: 9,053 Bytes
a2bd61d | 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | """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)
|