Download ex02.py from perrabyte/horizonwalker: direct link, hf CLI and curl.
- Browser
- Download file 7.17 kB
-
https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex02.py
- Command line
-
hf download hf://datasets/perrabyte/horizonwalker/ex02.py
-
curl -L -o ex02.py https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex02.py
7.17 kB
| """Teleport misclassified samples across the decision boundary. | |
| 784-dim MNIST, c00.py geometry, explicit epochs, per-epoch progress. | |
| """ | |
| import numpy as np, time | |
| # ββ Data loader with fallback chain βββββββββββββββββββββββββββββ | |
| def load_mnist_784(): | |
| try: # 1. keras | |
| from keras.datasets import mnist | |
| (Xtr, ytr), (Xte, yte) = mnist.load_data() | |
| return (Xtr.reshape(-1, 784).astype(np.float32)/255.0, ytr.astype(int), | |
| Xte.reshape(-1, 784).astype(np.float32)/255.0, yte.astype(int), "keras") | |
| except Exception: pass | |
| try: # 2. torchvision | |
| import torchvision | |
| dtr = torchvision.datasets.MNIST('../mnist_data', train=True, download=True) | |
| dte = torchvision.datasets.MNIST('../mnist_data', train=False, download=True) | |
| return (dtr.data.numpy().reshape(-1,784).astype(np.float32)/255.0, dtr.targets.numpy(), | |
| dte.data.numpy().reshape(-1,784).astype(np.float32)/255.0, dte.targets.numpy(), "torchvision") | |
| except Exception: pass | |
| try: # 3. sklearn openml | |
| from sklearn.datasets import fetch_openml | |
| X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False) | |
| X = X.astype(np.float32)/255.0; y = y.astype(int) | |
| return X[:60000], y[:60000], X[60000:], y[60000:], "sklearn-openml" | |
| except Exception as e: | |
| print(f"[loader] openml failed: {e}") | |
| print("[loader] *** falling back to 8x8 digits (64-dim, NOT MNIST) ***") | |
| from sklearn.datasets import load_digits | |
| X, y = load_digits(return_X_y=True) | |
| X = (X.astype(np.float32)/16.0); y = y.astype(int) | |
| p = np.random.permutation(len(X)); X, y = X[p], y[p] | |
| return X[:1400], y[:1400], X[1400:], y[1400:], "digits-fallback" | |
| # ββ MLPClassifier: exact c00.py geometry + snapshot support βββββ | |
| class MLPClassifier: | |
| def __init__(self, d_in, d_hid, d_out): | |
| self.W1 = np.random.randn(d_in, d_hid) * 0.01 | |
| self.b1 = np.zeros((1, d_hid)) | |
| self.W2 = np.random.randn(d_hid, d_out) * 0.01 | |
| self.b2 = np.zeros((1, d_out)) | |
| self.learning_rate = np.random.rand(4) # c00.py's four i.i.d. lrs | |
| def snapshot(self): | |
| return {k: getattr(self, k).copy() for k in ('W1','b1','W2','b2')} | |
| def _fwd(X, snap): | |
| z1 = X @ snap['W1'] + snap['b1'] | |
| a1 = np.maximum(0, z1) | |
| z2 = a1 @ snap['W2'] + snap['b2'] | |
| return z1, a1, z2 | |
| def predict(self, X, snap): | |
| _, _, z2 = self._fwd(X, snap) | |
| return z2.argmax(axis=1) | |
| def loss(self, X, Y_onehot, snap): | |
| _, _, z2 = self._fwd(X, snap) | |
| e = np.exp(z2 - z2.max(axis=1, keepdims=True)) | |
| yp = e / e.sum(axis=1, keepdims=True) | |
| return float(-np.mean(np.sum(Y_onehot * np.log(yp + 1e-9), axis=1))) | |
| def update(self, X, Y_onehot): | |
| z1, a1, z2 = self._fwd(X, self.snapshot()) | |
| e = np.exp(z2 - z2.max(axis=1, keepdims=True)) | |
| yp = e / e.sum(axis=1, keepdims=True) | |
| m = X.shape[0] | |
| dz2 = (yp - Y_onehot) / m | |
| dW2 = a1.T @ dz2 | |
| db2 = dz2.sum(axis=0, keepdims=True) | |
| dz1 = (dz2 @ self.W2.T) * (z1 > 0) | |
| dW1 = X.T @ dz1 | |
| db1 = dz1.sum(axis=0, keepdims=True) | |
| lr = self.learning_rate | |
| self.W1 -= lr[0]*dW1; self.b1 -= lr[1]*db1 | |
| self.W2 -= lr[2]*dW2; self.b2 -= lr[3]*db2 | |
| # ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| np.random.seed(0) | |
| X_tr, y_tr, X_te, y_te, src = load_mnist_784() | |
| d_in = X_tr.shape[1] | |
| N_VAL = 2000 | |
| X_val, y_val = X_te[:N_VAL], y_te[:N_VAL] | |
| Y_tr, Y_val = np.eye(10)[y_tr], np.eye(10)[y_val] | |
| f = MLPClassifier(d_in, 100, 10) | |
| print(f"data source : {src}") | |
| print(f"train shape : {X_tr.shape} test: {X_te.shape}") | |
| print(f"topology : {d_in} -> 100 -> 10 (c00.py)") | |
| print(f"minibatch : 100") | |
| print(f"lr vector : {np.round(f.learning_rate, 3)} (4 i.i.d. U(0,1))") | |
| print(f"teleporter set: first {N_VAL} test samples") | |
| print() | |
| EPOCHS, BATCH = 15, 100 | |
| n_tr = len(X_tr) | |
| spe = n_tr // BATCH # steps per epoch | |
| last_wrong = np.full(N_VAL, -1, dtype=int) | |
| snaps = [] | |
| hdr = f"{'epoch':>5} | {'val_loss':>9} | {'val_acc':>7} | {'flipped':>7} | {'time':>5}" | |
| print(hdr); print("-" * len(hdr)) | |
| for epoch in range(1, EPOCHS + 1): | |
| t0 = time.time() | |
| order = np.random.permutation(n_tr) | |
| for b in range(spe): | |
| idx = order[b*BATCH:(b+1)*BATCH] | |
| f.update(X_tr[idx], Y_tr[idx]) | |
| snap = f.snapshot(); snaps.append(snap) | |
| pred = f.predict(X_val, snap) | |
| vl = f.loss(X_val, Y_val, snap) | |
| va = float(np.mean(pred == y_val)) | |
| correct = pred == y_val | |
| last_wrong[~correct] = epoch | |
| n_flip = int(np.sum((last_wrong > 0) & correct)) | |
| print(f"{epoch:5d} | {vl:9.4f} | {va:7.4f} | {n_flip:7d} | {time.time()-t0:4.1f}s") | |
| # ββ Teleporter analysis ββββββββββββββββββββββββββββββββββ | |
| print() | |
| final = f.predict(X_val, snaps[-1]) | |
| final_ok = final == y_val | |
| flipped = (last_wrong > 0) & final_ok | |
| LATE = max(1, int(0.7 * EPOCHS)) # "late" = last wrong at epoch >= 10 | |
| late = flipped & (last_wrong >= LATE) | |
| n_flipped, n_late = int(flipped.sum()), int(late.sum()) | |
| # frozen-a1 test on the late flippers | |
| swept = own = 0 | |
| examples = [] | |
| for i in np.where(late)[0]: | |
| e_b = int(last_wrong[i]); e_a = e_b + 1 | |
| if e_a > EPOCHS: continue | |
| sb, sa = snaps[e_b - 1], snaps[e_a - 1] | |
| z1 = X_val[i:i+1] @ sb['W1'] + sb['b1'] | |
| a1 = np.maximum(0, z1) | |
| p_b = (a1 @ sb['W2'] + sb['b2']).argmax(axis=1)[0] | |
| p_a = (a1 @ sa['W2'] + sa['b2']).argmax(axis=1)[0] | |
| if p_b != y_val[i] and p_a == y_val[i]: | |
| swept += 1 | |
| if len(examples) < 3: examples.append((i, e_b, e_a)) | |
| else: | |
| own += 1 | |
| print("=== teleporter analysis ===") | |
| print(f"holdout : {N_VAL}") | |
| print(f"end correct : {int(final_ok.sum())} ({100*final_ok.mean():.1f}%)") | |
| print(f"ever wrong -> ended right: {n_flipped} (late-cross candidate pool)") | |
| print(f" of which flipped LATE : {n_late} (last wrong at epoch >= {LATE})") | |
| print(f" boundary-swept : {swept} <- actual teleports (frozen a1 passes)") | |
| print(f" own-gradient : {own} <- ordinary corrections") | |
| if n_late: | |
| print(f" swept fraction : {100*swept/n_late:.1f}%") | |
| if examples: | |
| print(" sample examples:") | |
| for i, eb, ea in examples: | |
| print(f" idx {i:4d} true={y_val[i]} flipped epoch {eb}->{ea} (frozen a1, W2 advanced)") | |
| return f, snaps, X_val, y_val, last_wrong | |
| if __name__ == "__main__": | |
| main() | |