Download ex01.py from perrabyte/horizonwalker: direct link, hf CLI and curl.
- Browser
- Download file 4.93 kB
-
https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex01.py
- Command line
-
hf download hf://datasets/perrabyte/horizonwalker/ex01.py
-
curl -L -o ex01.py https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex01.py
4.93 kB
| """Teleport misclassified samples across the decision boundary. | |
| Track per-sample predictions over epochs. For samples that flip late, | |
| test whether the flip was caused by the boundary moving past a FROZEN | |
| representation (the teleport) or by the sample's own gradient (ordinary | |
| correction).""" | |
| import numpy as np | |
| from sklearn.datasets import load_digits | |
| # ββ Data (stand-in for the wav read in c00.py) βββββββββββββββββ | |
| X_all, y_all = load_digits(return_X_y=True) | |
| X_all = X_all / 16.0 | |
| perm = np.random.permutation(len(X_all)) | |
| X_train, y_train = X_all[perm[:1500]], y_all[perm[:1500]] | |
| X_hold, y_hold = X_all[perm[1500:]], y_all[perm[1500:]] # 297 held-out samples | |
| np.random.seed(0) | |
| # ββ Classifier: exact shape of c00.py, plus a snapshot βββββββββ | |
| 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 _fwd(self, X, snap): | |
| z1 = X @ snap['W1'] + snap['b1'] | |
| a1 = np.maximum(0, z1) | |
| z2 = a1 @ snap['W2'] + snap['b2'] | |
| return a1, z2 | |
| def snapshot(self): | |
| return {k: getattr(self, k).copy() for k in ('W1', 'b1', 'W2', 'b2')} | |
| def predict(self, snap, X, freeze_a1=None): | |
| a1, z2 = self._fwd(X, snap) | |
| if freeze_a1 is not None: | |
| z2 = freeze_a1 @ snap['W2'] + snap['b2'] | |
| return z2.argmax(axis=1) | |
| def update(self, X, yt_onehot): | |
| 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 - yt_onehot | |
| dW2 = a1.T @ dz2 / m | |
| db2 = dz2.sum(axis=0, keepdims=True) / m | |
| da1 = dz2 @ self.W2.T | |
| dz1 = da1 * (np.maximum(0, X @ self.W1 + self.b1) > 0) | |
| dW1 = X.T @ dz1 / m | |
| db1 = dz1.sum(axis=0, keepdims=True) / m | |
| lr = self.learning_rate | |
| self.W1 -= lr[0] * dW1; self.b1 -= lr[1] * db1 | |
| self.W2 -= lr[2] * dW2; self.b2 -= lr[3] * db2 | |
| f = MLPClassifier(64, 100, 10) | |
| # ββ Train, snapshotting the holdout predictions every 10 epochs β | |
| STEPS, SNAP_EVERY = 60000, 10 | |
| snaps, epoch_nums, preds_over_time = [], [], [] | |
| for step in range(STEPS): | |
| idx = np.random.randint(0, len(X_train), 100) | |
| f.update(X_train[idx], np.eye(10)[y_train[idx]]) | |
| if step % SNAP_EVERY == 0: | |
| s = f.snapshot() | |
| snaps.append(s) | |
| epoch_nums.append(step) | |
| preds_over_time.append(f.predict(s, X_hold)) | |
| # ββ Locate teleporters: last-wrong < first-correct-after ββββββββ | |
| teleporters = [] | |
| for i in range(len(X_hold)): | |
| seq = [int(p[i]) for p in preds_over_time] | |
| true = int(y_hold[i]) | |
| wrong_at = [j for j, p in enumerate(seq) if p != true] | |
| if not wrong_at: | |
| continue | |
| last_wrong = max(wrong_at) | |
| if last_wrong == len(seq) - 1: # still wrong at end β departed, not arrived | |
| continue | |
| teleporters.append(dict( | |
| i=i, | |
| j_before=last_wrong, | |
| j_after=last_wrong + 1, | |
| epoch_before=epoch_nums[last_wrong], | |
| epoch_after=epoch_nums[last_wrong + 1], | |
| )) | |
| # ββ The teleport test ββββββββββββββββββββββββββββββββββββββββββ | |
| # Freeze the sample's hidden representation a1 at the "before" snapshot. | |
| # Advance only the output layer (W2, b2) to the "after" snapshot. | |
| # If argmax flips, the boundary swept past a stationary sample. | |
| n_teleport = n_swept = 0 | |
| for t in teleporters: | |
| i = t['i'] | |
| a1_before, _ = f._fwd(X_hold[i:i+1], snaps[t['j_before']]) | |
| pred_frozen_before = f.predict(snaps[t['j_before']], X_hold[i:i+1], freeze_a1=a1_before)[0] | |
| pred_frozen_after = f.predict(snaps[t['j_after' ]], X_hold[i:i+1], freeze_a1=a1_before)[0] | |
| crossed_by_boundary = (pred_frozen_before != y_hold[i]) and (pred_frozen_after == y_hold[i]) | |
| t['swept'] = crossed_by_boundary | |
| n_teleport += 1 | |
| n_swept += int(crossed_by_boundary) | |
| # ββ Report βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"holdout size : {len(X_hold)}") | |
| print(f"samples that flip late : {n_teleport}") | |
| print(f"β¦of which boundary-swept : {n_swept} ({100*n_swept/max(n_teleport,1):.0f}%)") | |
| print(f"β¦of which own-gradient : {n_teleport - n_swept}") | |
| for t in sorted(teleporters, key=lambda x: x['epoch_after'])[:10]: | |
| tag = "SWEPT " if t['swept'] else "own-lr" | |
| print(f" sample {t['i']:>3} true={y_hold[t['i']]} " | |
| f"epoch {t['epoch_before']:>3}β{t['epoch_after']:>3} {tag}") | |