Spaces:
Running
Running
Download denseam_repro.py from UncleanCode/denseam-hp-transfer: direct link, hf CLI and curl.
- Browser
- Download file 7.85 kB
-
https://huggingface.co/spaces/UncleanCode/denseam-hp-transfer/resolve/main/denseam_repro.py
- Command line
-
hf download hf://spaces/UncleanCode/denseam-hp-transfer/denseam_repro.py
-
curl -L -o denseam_repro.py https://huggingface.co/spaces/UncleanCode/denseam-hp-transfer/resolve/main/denseam_repro.py
7.85 kB
| """Reproduction of arXiv:2605.10164 - Hyperparameter Transfer for Dense Associative Memories | |
| (Holtzman, Krotov, Hanin, 2026). | |
| Target: Table 1 + Figure 4. Claim under test: | |
| "With the centered parameterisation of Table 1, the optimal effective learning | |
| rate eta_0 for a DenseAM trained on MNIST denoising is the SAME across six | |
| input-dimension scales obtained by plaquette coarse graining." | |
| Model (eq. 1.1 / 2.1): | |
| f(x) = s2 * W^T sigma_C( s1 * W g(x) + b ) + c, | |
| sigma_C = C o sigma o C, C = I_K - (1/K) 11^T, g = tanh, | |
| sigma = ReLU (p=1) or softmax. | |
| Parameterisation (Table 1, proportional regime eq. 1.3): | |
| s1 = 1/sqrt(N), s2 = 1/sqrt(K), | |
| SGD : eta_W = eta_0 * sqrt(K); Adam: eta_W = eta_0, | |
| biases: eta_b = eta_c = eta_0 (eta_{b,0} = eta_{c,0} = eta_0). | |
| Data (Appendix J): MNIST, plaquette coarse graining with block size j giving | |
| N_j = ceil(28/j)^2 inputs, pixels centred across the dataset. kappa = K/N = 2, | |
| rho = P/N = 5, beta = B/P = 0.1, 256 epochs. | |
| Choices the caption does not pin down are marked ASSUMPTION; they are listed in | |
| README.md together with a sensitivity check. | |
| """ | |
| import argparse | |
| import gzip | |
| import json | |
| import math | |
| import os | |
| import time | |
| import numpy as np | |
| import torch | |
| # --------------------------------------------------------------------------- data | |
| def load_mnist(raw_dir): | |
| """Train images as float32 in [0,1], shape (60000, 784).""" | |
| path = os.path.join(raw_dir, "train-images-idx3-ubyte.gz") | |
| with gzip.open(path, "rb") as fh: | |
| buf = fh.read() | |
| n = int.from_bytes(buf[4:8], "big") | |
| return np.frombuffer(buf, dtype=np.uint8, offset=16).reshape(n, 784).astype(np.float32) / 255.0 | |
| def plaquette(images, j): | |
| """Average over j x j blocks (Appendix J); grid ceil(28/j), remainder | |
| edge-replicated. ASSUMPTION: edge replication for the padded border.""" | |
| m = math.ceil(28 / j) | |
| img = images.reshape(-1, 28, 28) | |
| pad = m * j - 28 | |
| if pad: | |
| img = np.pad(img, ((0, 0), (0, pad), (0, pad)), mode="edge") | |
| return img.reshape(-1, m, j, m, j).mean(axis=(2, 4)).reshape(len(images), m * m) | |
| def make_dataset(j, raw_dir, pixel_scale=2.0, pixel_shift=-1.0): | |
| """Coarse-grained, rescaled, pixel-centred MNIST (all 60000 images). | |
| ASSUMPTION: pixels mapped to [-1, 1] so that the MSE scale is comparable to | |
| the 1e-2 .. 4e-1 range of Figure 4.""" | |
| x = load_mnist(raw_dir) | |
| x = pixel_shift + pixel_scale * x | |
| x = plaquette(x, j) | |
| x = x - x.mean(axis=0, keepdims=True) | |
| return x.astype(np.float32) | |
| # -------------------------------------------------------------------------- model | |
| def centre(v): | |
| """C = I - 11^T/K applied across the hidden dimension.""" | |
| return v - v.mean(dim=-1, keepdim=True) | |
| class DenseAM(torch.nn.Module): | |
| def __init__(self, n_in, width, s1, s2, act): | |
| super().__init__() | |
| self.W = torch.nn.Parameter(torch.randn(width, n_in)) | |
| self.b = torch.nn.Parameter(torch.randn(width)) | |
| self.c = torch.nn.Parameter(torch.randn(n_in)) | |
| self.s1, self.s2, self.act = s1, s2, act | |
| def forward(self, x): | |
| g = torch.tanh(x) | |
| z = centre(self.s1 * (g @ self.W.t()) + self.b) # pre-activation, centred | |
| if self.act == "relu": | |
| a = centre(torch.relu(z)) # post-activation, centred | |
| elif self.act == "softmax": | |
| a = centre(torch.softmax(z, dim=-1)) | |
| else: | |
| a = centre(z) | |
| return self.s2 * (a @ self.W) + self.c | |
| # ----------------------------------------------------------------------- training | |
| SCALES = [(1, 784, 1568, 3920, 392), | |
| (2, 196, 392, 980, 98), | |
| (3, 100, 200, 500, 50), | |
| (4, 49, 98, 240, 24), | |
| (5, 36, 72, 180, 18), | |
| (6, 25, 50, 120, 12)] | |
| TRAIN_POOL = 40000 # training points drawn from images 0..39999 | |
| EVAL_SLICE = (58000, 60000) # held-out images, never used for fitting | |
| def run_one(cfg): | |
| t0 = time.time() | |
| j = cfg["j"] | |
| _, n_in, width, n_data, batch = [s for s in SCALES if s[0] == j][0] | |
| act, opt_name, eta0 = cfg["act"], cfg["opt"], cfg["eta0"] | |
| epochs = cfg.get("epochs", 256) | |
| noise = cfg.get("noise", 0.1) # ASSUMPTION: sigma_eps unstated | |
| seed = cfg.get("seed", 0) | |
| torch.manual_seed(seed) | |
| torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "1"))) | |
| x = make_dataset(j, cfg["raw_dir"], cfg.get("pixel_scale", 2.0), cfg.get("pixel_shift", -1.0)) | |
| idx = np.random.RandomState(1000 + seed).choice(TRAIN_POOL, n_data, replace=False) | |
| xb = torch.from_numpy(x[idx]) | |
| xe = torch.from_numpy(x[EVAL_SLICE[0]:EVAL_SLICE[1]]) | |
| s1 = 1.0 / math.sqrt(n_in) | |
| s2 = 1.0 / math.sqrt(width) | |
| model = DenseAM(n_in, width, s1, s2, act) | |
| eta_w = eta0 * math.sqrt(width) if opt_name == "sgd" else eta0 | |
| groups = [{"params": [model.W], "lr": eta_w}, | |
| {"params": [model.b, model.c], "lr": eta0}] | |
| optim = torch.optim.SGD(groups) if opt_name == "sgd" else torch.optim.Adam(groups) | |
| steps_per_epoch = max(1, n_data // batch) | |
| curve, eval_curve = [], [] | |
| diverged = False | |
| gen = torch.Generator().manual_seed(seed) | |
| def evaluate(): | |
| with torch.no_grad(): | |
| tr = float(((model(xb) - xb) ** 2).mean()) | |
| ev = float(((model(xe) - xe) ** 2).mean()) | |
| return tr, ev | |
| for ep in range(epochs): | |
| perm = torch.randperm(n_data, generator=gen) | |
| for k in range(steps_per_epoch): | |
| sel = perm[k * batch:(k + 1) * batch] | |
| clean = xb[sel] | |
| noisy = clean + noise * torch.randn(clean.shape, generator=gen) | |
| loss = ((model(noisy) - clean) ** 2).mean() | |
| if not torch.isfinite(loss): | |
| diverged = True | |
| break | |
| optim.zero_grad() | |
| loss.backward() | |
| optim.step() | |
| if diverged: | |
| break | |
| if (ep + 1) % 16 == 0: | |
| tr, ev = evaluate() | |
| curve.append([ep + 1, tr]) | |
| eval_curve.append([ep + 1, ev]) | |
| if diverged: | |
| mse = float("nan") | |
| ev_mse = float("nan") | |
| else: | |
| mse, ev_mse = evaluate() | |
| out = dict(cfg) | |
| out.pop("raw_dir", None) | |
| out.update(n_in=n_in, width=width, n_data=n_data, batch=batch, | |
| s1=s1, s2=s2, eta_w=eta_w, | |
| final_train_mse=mse, final_eval_mse=ev_mse, | |
| diverged=diverged, curve=curve, eval_curve=eval_curve, | |
| wall_s=round(time.time() - t0, 1)) | |
| return out | |
| # --------------------------------------------------------------------------- modal | |
| try: | |
| import modal | |
| app = modal.App("denseam-repro") | |
| image = (modal.Image.debian_slim(python_version="3.11") | |
| .pip_install("numpy") | |
| .pip_install("torch", index_url="https://download.pytorch.org/whl/cpu") | |
| .add_local_file("data/train-images-idx3-ubyte.gz", | |
| "/data/train-images-idx3-ubyte.gz")) | |
| def remote_run(cfg): | |
| cfg = dict(cfg) | |
| cfg["raw_dir"] = "/data" | |
| return run_one(cfg) | |
| except Exception: | |
| app = None | |
| remote_run = None | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--j", type=int, default=6) | |
| ap.add_argument("--act", default="relu") | |
| ap.add_argument("--opt", default="sgd") | |
| ap.add_argument("--eta0", type=float, default=0.03) | |
| ap.add_argument("--raw-dir", default="data") | |
| ap.add_argument("--out", default=None) | |
| a = ap.parse_args() | |
| res = run_one(dict(j=a.j, act=a.act, opt=a.opt, eta0=a.eta0, seed=0, raw_dir=a.raw_dir)) | |
| print(json.dumps({k: v for k, v in res.items() if not k.endswith("curve")}, indent=2)) | |
| if a.out: | |
| with open(a.out, "w") as fh: | |
| json.dump(res, fh, indent=2) | |
| if __name__ == "__main__": | |
| main() | |