| |
| """exp02_neural — reduced-scale neural verification of Claims 4, 5, 6. |
| |
| Real CIFAR-100 + CIFAR-100N (UCSC-REAL, human noisy labels), SmallCNN, CPU. |
| Optimizers: SGD, SAM (Foret et al. 2021), fSGLD (Eq 5). See specs/exp02_neural.md. |
| CPU only, torch/joblib. See BLOCKERS.md for the reduced-scale rationale. |
| """ |
| import os |
|
|
| for _v in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS"): |
| os.environ.setdefault(_v, "1") |
|
|
| import argparse |
| import hashlib |
| import json |
| import math |
| import pickle |
| import sys |
| import tarfile |
| import time |
| import urllib.request |
|
|
| import numpy as np |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| from joblib import Parallel, delayed |
|
|
| ROOT = os.path.dirname(os.path.abspath(__file__)) |
| BASE = os.path.dirname(ROOT) |
| WORK_DIR = os.path.join(BASE, "work") |
| DATA_DIR = os.path.join(WORK_DIR, "data") |
| RESULTS_DIR = os.path.join(BASE, "results") |
|
|
| CIFAR100_URL = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" |
| CIFAR100_MD5 = "eb9058c3a382ffc7106e4002c42a8d85" |
| CIFAR100N_URL = "https://github.com/UCSC-REAL/cifar-10-100n/raw/main/data/CIFAR-100_human.pt" |
|
|
| MEAN = np.array([0.5071, 0.4865, 0.4409], dtype=np.float32) |
| STD = np.array([0.2673, 0.2564, 0.2762], dtype=np.float32) |
|
|
| BETA = 1e8 |
| ETA_FSGLD = 0.1 |
| SIGMA_FSGLD = BETA ** (-(1 + ETA_FSGLD) / 4.0) |
| WD = 5e-4 |
| RHO_SAM = 0.05 |
| BASE_LR = 0.1 |
| FT_LR = 0.02 |
| BATCH = 128 |
|
|
|
|
| def log(msg): |
| print(msg, file=sys.stderr, flush=True) |
|
|
|
|
| |
| def _md5(path): |
| h = hashlib.md5() |
| with open(path, "rb") as f: |
| for chunk in iter(lambda: f.read(1 << 20), b""): |
| h.update(chunk) |
| return h.hexdigest() |
|
|
|
|
| def _download(url, path): |
| log(f"[data] downloading {url} -> {path}") |
| tmp = path + ".part" |
| urllib.request.urlretrieve(url, tmp) |
| os.replace(tmp, path) |
|
|
|
|
| def load_cifar100(provenance): |
| os.makedirs(DATA_DIR, exist_ok=True) |
| tar_path = os.path.join(DATA_DIR, "cifar-100-python.tar.gz") |
| if not os.path.exists(tar_path) or _md5(tar_path) != CIFAR100_MD5: |
| _download(CIFAR100_URL, tar_path) |
| md5ok = _md5(tar_path) == CIFAR100_MD5 |
| log(f"[data] cifar100 tarball md5_ok={md5ok} sha256={hashlib.sha256(open(tar_path,'rb').read()).hexdigest()}") |
|
|
| with tarfile.open(tar_path, "r:gz") as tf: |
| train_raw = pickle.load(tf.extractfile("cifar-100-python/train"), encoding="latin1") |
| test_raw = pickle.load(tf.extractfile("cifar-100-python/test"), encoding="latin1") |
|
|
| train_data = np.asarray(train_raw["data"], dtype=np.uint8) |
| test_data = np.asarray(test_raw["data"], dtype=np.uint8) |
| train_fine = np.asarray(train_raw["fine_labels"], dtype=np.int64) |
| test_fine = np.asarray(test_raw["fine_labels"], dtype=np.int64) |
|
|
| struct_ok = ( |
| train_data.shape == (50000, 3072) |
| and test_data.shape == (10000, 3072) |
| and len(np.unique(train_fine)) == 100 |
| and train_data.min() >= 0 and train_data.max() <= 255 |
| ) |
| provenance["cifar100_sha256_ok"] = bool(md5ok and struct_ok) |
| provenance["n_train"] = int(train_data.shape[0]) |
| provenance["n_test"] = int(test_data.shape[0]) |
| log(f"[data] cifar100 struct_ok={struct_ok} n_train={train_data.shape[0]} n_test={test_data.shape[0]}") |
| return train_data, train_fine, test_data, test_fine |
|
|
|
|
| def load_cifar100n(provenance): |
| os.makedirs(DATA_DIR, exist_ok=True) |
| pt_path = os.path.join(DATA_DIR, "CIFAR-100_human.pt") |
| if not os.path.exists(pt_path): |
| _download(CIFAR100N_URL, pt_path) |
| d = torch.load(pt_path, weights_only=False) |
| noisy = np.asarray(d["noisy_label"], dtype=np.int64) |
| clean = np.asarray(d["clean_label"], dtype=np.int64) |
| provenance["cifar100n_len"] = int(len(noisy)) |
| noise_rate = float(np.mean(noisy != clean)) |
| provenance["cifar100n_noise_rate"] = noise_rate |
| log(f"[data] cifar100n len={len(noisy)} noise_rate={noise_rate:.4f}") |
| return noisy, clean |
|
|
|
|
| def preprocess(data_u8): |
| imgs = data_u8.reshape(-1, 3, 32, 32).astype(np.float32) / 255.0 |
| imgs = (imgs - MEAN.reshape(1, 3, 1, 1)) / STD.reshape(1, 3, 1, 1) |
| return imgs.astype(np.float32) |
|
|
|
|
| def get_subset_indices(n_subset, seed_tag): |
| path = os.path.join(WORK_DIR, f"exp02_subset_indices_{seed_tag}_{n_subset}.npy") |
| if os.path.exists(path): |
| return np.load(path) |
| idx = np.random.default_rng(0).choice(50000, n_subset, replace=False) |
| np.save(path, idx) |
| return idx |
|
|
|
|
| |
| def augment_batch(x_np): |
| |
| B = x_np.shape[0] |
| padded = np.pad(x_np, ((0, 0), (0, 0), (4, 4), (4, 4)), mode="reflect") |
| out = np.empty_like(x_np) |
| for i in range(B): |
| top = np.random.randint(0, 9) |
| left = np.random.randint(0, 9) |
| crop = padded[i, :, top:top + 32, left:left + 32] |
| if np.random.rand() < 0.5: |
| crop = crop[:, :, ::-1] |
| out[i] = crop |
| return np.ascontiguousarray(out) |
|
|
|
|
| |
| class SmallCNN(nn.Module): |
| def __init__(self, n_classes=100): |
| super().__init__() |
| self.c1 = nn.Conv2d(3, 32, 3, padding=1) |
| self.b1 = nn.BatchNorm2d(32) |
| self.c2 = nn.Conv2d(32, 64, 3, padding=1) |
| self.b2 = nn.BatchNorm2d(64) |
| self.c3 = nn.Conv2d(64, 128, 3, padding=1) |
| self.b3 = nn.BatchNorm2d(128) |
| self.c4 = nn.Conv2d(128, 128, 3, padding=1) |
| self.b4 = nn.BatchNorm2d(128) |
| self.pool = nn.MaxPool2d(2) |
| self.gap = nn.AdaptiveAvgPool2d(4) |
| self.fc1 = nn.Linear(128 * 16, 256) |
| self.fc2 = nn.Linear(256, n_classes) |
|
|
| def forward(self, x): |
| x = F.relu(self.b1(self.c1(x))) |
| x = self.pool(F.relu(self.b2(self.c2(x)))) |
| x = self.pool(F.relu(self.b3(self.c3(x)))) |
| x = F.relu(self.b4(self.c4(x))) |
| x = self.gap(x).flatten(1) |
| x = F.relu(self.fc1(x)) |
| return self.fc2(x) |
|
|
|
|
| |
| def lr_at(epoch, base_lr, milestones): |
| lr = base_lr |
| for m in milestones: |
| if epoch >= m: |
| lr *= 0.1 |
| return lr |
|
|
|
|
| def sgd_step(model, opt, xb, yb): |
| opt.zero_grad() |
| out = model(xb) |
| loss = F.cross_entropy(out, yb) |
| loss.backward() |
| opt.step() |
| return loss.item(), 1 |
|
|
|
|
| def sam_step(model, opt, xb, yb, rho): |
| |
| opt.zero_grad() |
| out = model(xb) |
| loss1 = F.cross_entropy(out, yb) |
| loss1.backward() |
| params = [p for p in model.parameters() if p.grad is not None] |
| with torch.no_grad(): |
| grad_norm = torch.norm(torch.stack([p.grad.norm(2) for p in params])) + 1e-12 |
| eps_list = [] |
| for p in params: |
| e = p.grad * (rho / grad_norm) |
| p.add_(e) |
| eps_list.append(e) |
| |
| opt.zero_grad() |
| out2 = model(xb) |
| loss2 = F.cross_entropy(out2, yb) |
| loss2.backward() |
| with torch.no_grad(): |
| for p, e in zip(params, eps_list): |
| p.sub_(e) |
| opt.step() |
| return loss1.item(), 2 |
|
|
|
|
| def fsgld_step(model, params, lam, sigma, beta, wd, xb, yb): |
| with torch.no_grad(): |
| eps_list = [torch.randn_like(p) * sigma for p in params] |
| for p, e in zip(params, eps_list): |
| p.add_(e) |
| for p in params: |
| if p.grad is not None: |
| p.grad = None |
| out = model(xb) |
| loss = F.cross_entropy(out, yb) |
| loss.backward() |
| with torch.no_grad(): |
| for p, e in zip(params, eps_list): |
| p.sub_(e) |
| for p in params: |
| g = p.grad + wd * p |
| xi = torch.randn_like(p) |
| p.add_(-lam * g + math.sqrt(2 * lam / beta) * xi) |
| return loss.item(), 1 |
|
|
|
|
| |
| def make_optimizer(name, model): |
| if name == "SGD": |
| return torch.optim.SGD(model.parameters(), lr=BASE_LR, momentum=0.9, weight_decay=WD) |
| if name == "SAM": |
| return torch.optim.SGD(model.parameters(), lr=BASE_LR, momentum=0.9, weight_decay=WD) |
| return None |
|
|
|
|
| def set_lr(opt, lr): |
| for g in opt.param_groups: |
| g["lr"] = lr |
|
|
|
|
| def run_epochs(model, optimizer_name, train_x, train_y, epochs, milestones, base_lr, |
| batch_size, measure_timing=False, warmup_steps=10, timing_steps=50): |
| n = train_x.shape[0] |
| torch_opt = make_optimizer(optimizer_name, model) if optimizer_name in ("SGD", "SAM") else None |
| params = [p for p in model.parameters()] |
| s_per_iter = None |
| all_times = [] |
| step_times = [] |
| last_loss = None |
| global_step = 0 |
| for epoch in range(epochs): |
| lr = lr_at(epoch, base_lr, milestones) |
| if torch_opt is not None: |
| set_lr(torch_opt, lr) |
| perm = np.random.permutation(n) |
| model.train() |
| for start in range(0, n, batch_size): |
| idx = perm[start:start + batch_size] |
| xb_np = augment_batch(train_x[idx]) |
| xb = torch.from_numpy(xb_np) |
| yb = torch.from_numpy(train_y[idx]) |
| t0 = time.time() if measure_timing else None |
| if optimizer_name == "SGD": |
| loss, _ = sgd_step(model, torch_opt, xb, yb) |
| elif optimizer_name == "SAM": |
| loss, _ = sam_step(model, torch_opt, xb, yb, RHO_SAM) |
| else: |
| loss, _ = fsgld_step(model, params, lr, SIGMA_FSGLD, BETA, WD, xb, yb) |
| if measure_timing: |
| dt = time.time() - t0 |
| global_step += 1 |
| all_times.append(dt) |
| if global_step > warmup_steps and len(step_times) < timing_steps: |
| step_times.append(dt) |
| last_loss = loss |
| if measure_timing and not step_times: |
| step_times = all_times |
| if measure_timing and step_times: |
| s_per_iter = float(np.mean(step_times)) |
| return last_loss, s_per_iter |
|
|
|
|
| @torch.no_grad() |
| def evaluate(model, test_x, test_y, batch_size=256): |
| model.eval() |
| correct = 0 |
| n = test_x.shape[0] |
| for start in range(0, n, batch_size): |
| xb = torch.from_numpy(test_x[start:start + batch_size]) |
| yb = torch.from_numpy(test_y[start:start + batch_size]) |
| out = model(xb) |
| pred = out.argmax(1) |
| correct += (pred == yb).sum().item() |
| return correct / n |
|
|
|
|
| |
| def hvp(loss, params, v): |
| grads = torch.autograd.grad(loss, params, create_graph=True) |
| flat_grad = torch.cat([g.reshape(-1) for g in grads]) |
| flat_v = torch.cat([vi.reshape(-1) for vi in v]) |
| gv = (flat_grad * flat_v).sum() |
| hv = torch.autograd.grad(gv, params, retain_graph=True) |
| return [h.detach() for h in hv] |
|
|
|
|
| def compute_flatness(model, x_batch, y_batch, m_hutch, top_iters, tol=1e-4): |
| model.eval() |
| params = [p for p in model.parameters() if p.requires_grad] |
| x = torch.from_numpy(x_batch) |
| y = torch.from_numpy(y_batch) |
|
|
| def get_loss(): |
| out = model(x) |
| return F.cross_entropy(out, y) |
|
|
| |
| traces = [] |
| for _ in range(m_hutch): |
| v = [torch.randint(0, 2, p.shape, dtype=torch.float32) * 2 - 1 for p in params] |
| loss = get_loss() |
| hv = hvp(loss, params, v) |
| t = sum((vi * hi).sum().item() for vi, hi in zip(v, hv)) |
| traces.append(t) |
| hess_trace = float(np.mean(traces)) |
|
|
| |
| v = [torch.randn_like(p) for p in params] |
| norm = math.sqrt(sum((vi ** 2).sum().item() for vi in v)) |
| v = [vi / norm for vi in v] |
| lam_prev = 0.0 |
| lam_top = 0.0 |
| for it in range(top_iters): |
| loss = get_loss() |
| hv = hvp(loss, params, v) |
| norm = math.sqrt(sum((hi ** 2).sum().item() for hi in hv)) |
| if norm < 1e-12: |
| break |
| v = [hi / norm for hi in hv] |
| loss = get_loss() |
| hv2 = hvp(loss, params, v) |
| lam_top = sum((vi * hi).sum().item() for vi, hi in zip(v, hv2)) |
| if abs(lam_top - lam_prev) < tol: |
| lam_prev = lam_top |
| break |
| lam_prev = lam_top |
| return hess_trace, float(lam_top) |
|
|
|
|
| |
| def ckpt_path(prefix, name): |
| return os.path.join(WORK_DIR, f"{prefix}_{name}.json") |
|
|
|
|
| def load_ckpt(path): |
| with open(path) as f: |
| return json.load(f) |
|
|
|
|
| def save_ckpt(path, obj): |
| tmp = path + ".tmp" |
| with open(tmp, "w") as f: |
| json.dump(obj, f) |
| os.replace(tmp, path) |
|
|
|
|
| def scratch_unit(prefix, optimizer_name, seed, train_x, train_y, test_x, test_y, epochs, milestones, |
| warmup_steps=10, timing_steps=50): |
| path = ckpt_path(prefix, f"scratch_{optimizer_name}_{seed}") |
| if os.path.exists(path): |
| log(f"[scratch] skip existing {optimizer_name} seed={seed}") |
| return load_ckpt(path) |
| torch.set_num_threads(1) |
| torch.manual_seed(seed) |
| np.random.seed(seed) |
| t0 = time.time() |
| model = SmallCNN() |
| last_loss, s_per_iter = run_epochs(model, optimizer_name, train_x, train_y, epochs, milestones, |
| BASE_LR, BATCH, measure_timing=True, |
| warmup_steps=warmup_steps, timing_steps=timing_steps) |
| test_acc = evaluate(model, test_x, test_y) |
| model_path = os.path.join(WORK_DIR, f"{prefix}_scratchmodel_{optimizer_name}_{seed}.pt") |
| torch.save(model.state_dict(), model_path) |
| row = {"optimizer": optimizer_name, "seed": seed, "test_acc": test_acc, |
| "train_loss": last_loss, "s_per_iter": s_per_iter} |
| save_ckpt(path, row) |
| log(f"[scratch] {optimizer_name} seed={seed} acc={test_acc:.4f} s_per_iter={s_per_iter:.4f} wall={time.time()-t0:.1f}s") |
| return row |
|
|
|
|
| def ablation_unit(prefix, eta, seed, train_x, train_y, test_x, test_y, epochs, milestones): |
| tag = f"{eta:.3f}".replace("-", "m") |
| path = ckpt_path(prefix, f"ablation_eta{tag}_{seed}") |
| if os.path.exists(path): |
| log(f"[ablation] skip existing eta={eta} seed={seed}") |
| return load_ckpt(path) |
| torch.set_num_threads(1) |
| torch.manual_seed(seed) |
| np.random.seed(seed) |
| t0 = time.time() |
| sigma = BETA ** (-(1 + eta) / 4.0) |
| model = SmallCNN() |
| params = [p for p in model.parameters()] |
|
|
| n = train_x.shape[0] |
| for epoch in range(epochs): |
| lam = lr_at(epoch, BASE_LR, milestones) |
| perm = np.random.permutation(n) |
| model.train() |
| for start in range(0, n, BATCH): |
| idx = perm[start:start + BATCH] |
| xb = torch.from_numpy(augment_batch(train_x[idx])) |
| yb = torch.from_numpy(train_y[idx]) |
| fsgld_step(model, params, lam, sigma, BETA, WD, xb, yb) |
| test_acc = evaluate(model, test_x, test_y) |
| row = {"eta": eta, "seed": seed, "test_acc": test_acc} |
| save_ckpt(path, row) |
| log(f"[ablation] eta={eta} seed={seed} acc={test_acc:.4f} wall={time.time()-t0:.1f}s") |
| return row |
|
|
|
|
| def pretrain_unit(prefix, seed, train_x, clean_y, epochs, milestones): |
| path = os.path.join(WORK_DIR, f"{prefix}_pretrain_seed{seed}.pt") |
| if os.path.exists(path): |
| log(f"[pretrain] skip existing seed={seed}") |
| return path |
| torch.set_num_threads(1) |
| torch.manual_seed(seed) |
| np.random.seed(seed) |
| t0 = time.time() |
| model = SmallCNN() |
| run_epochs(model, "SGD", train_x, clean_y, epochs, milestones, BASE_LR, BATCH) |
| torch.save(model.state_dict(), path) |
| log(f"[pretrain] seed={seed} wall={time.time()-t0:.1f}s") |
| return path |
|
|
|
|
| def finetune_unit(prefix, optimizer_name, seed, pretrain_path, train_x, noisy_y, test_x, test_y, |
| epochs, milestones): |
| path = ckpt_path(prefix, f"finetune_{optimizer_name}_{seed}") |
| if os.path.exists(path): |
| log(f"[finetune] skip existing {optimizer_name} seed={seed}") |
| return load_ckpt(path) |
| torch.set_num_threads(1) |
| torch.manual_seed(seed + 1000) |
| np.random.seed(seed + 1000) |
| t0 = time.time() |
| model = SmallCNN() |
| model.load_state_dict(torch.load(pretrain_path)) |
| run_epochs(model, optimizer_name, train_x, noisy_y, epochs, milestones, FT_LR, BATCH) |
| test_acc = evaluate(model, test_x, test_y) |
| row = {"optimizer": optimizer_name, "seed": seed, "test_acc": test_acc} |
| save_ckpt(path, row) |
| log(f"[finetune] {optimizer_name} seed={seed} acc={test_acc:.4f} wall={time.time()-t0:.1f}s") |
| return row |
|
|
|
|
| def flatness_unit(prefix, optimizer_name, model_path, x_batch, y_batch, m_hutch, top_iters): |
| path = ckpt_path(prefix, f"flatness_{optimizer_name}") |
| if os.path.exists(path): |
| log(f"[flatness] skip existing {optimizer_name}") |
| return load_ckpt(path) |
| torch.set_num_threads(1) |
| t0 = time.time() |
| model = SmallCNN() |
| model.load_state_dict(torch.load(model_path)) |
| hess_trace, lam_top = compute_flatness(model, x_batch, y_batch, m_hutch, top_iters) |
| row = {"optimizer": optimizer_name, "hess_trace": hess_trace, "lambda_top": lam_top} |
| save_ckpt(path, row) |
| log(f"[flatness] {optimizer_name} trace={hess_trace:.4f} lam_top={lam_top:.4f} wall={time.time()-t0:.1f}s") |
| return row |
|
|
|
|
| |
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--toy", action="store_true") |
| args = parser.parse_args() |
| toy = args.toy |
|
|
| os.makedirs(WORK_DIR, exist_ok=True) |
| os.makedirs(RESULTS_DIR, exist_ok=True) |
| job_cores = int(os.environ.get("JOB_CORES", 4)) |
| prefix = "exp02_toy" if toy else "exp02" |
|
|
| t_start = time.time() |
|
|
| provenance = {} |
| train_u8, train_fine, test_u8, test_fine = load_cifar100(provenance) |
| noisy_label, clean_label = load_cifar100n(provenance) |
|
|
| seeds = [0, 1] if toy else [0, 1, 2] |
| n_subset = 400 if toy else 15000 |
| epochs_scratch = 2 if toy else 30 |
| epochs_ft = 2 if toy else 15 |
| epochs_pretrain = 2 if toy else 15 |
| milestones_scratch = [1] if toy else [15, 25] |
| milestones_ft = [1] if toy else [10] |
| m_hutch = 4 if toy else 100 |
| top_iters = 5 if toy else 100 |
| flat_batch = 100 if toy else 2000 |
| warmup_steps = 1 if toy else 10 |
| timing_steps = 3 if toy else 50 |
| etas = [-0.5, 0.1, 0.5, 0.9, 1.5] |
|
|
| subset_tag = "toy" if toy else "full" |
| sub_idx = get_subset_indices(n_subset, subset_tag) |
| train_x_all = preprocess(train_u8) |
| test_x_all = preprocess(test_u8) |
| train_x = train_x_all[sub_idx] |
| train_noisy_y = noisy_label[sub_idx].astype(np.int64) |
| train_clean_y = clean_label[sub_idx].astype(np.int64) |
| test_x = test_x_all |
| test_y = test_fine.astype(np.int64) |
|
|
| |
| scratch_jobs = [(opt, s) for opt in ("SGD", "SAM", "fSGLD") for s in seeds] |
| scratch_rows = Parallel(n_jobs=job_cores)( |
| delayed(scratch_unit)(prefix, opt, s, train_x, train_noisy_y, test_x, test_y, |
| epochs_scratch, milestones_scratch, |
| warmup_steps=warmup_steps, timing_steps=timing_steps) |
| for opt, s in scratch_jobs |
| ) |
|
|
| def summarize(rows, key="test_acc"): |
| accs = [r[key] for r in rows] |
| return {"acc_mean": float(np.mean(accs)), "acc_std": float(np.std(accs))} |
|
|
| scratch_summary = {} |
| for opt in ("SGD", "SAM", "fSGLD"): |
| rows = [r for r in scratch_rows if r["optimizer"] == opt] |
| s = summarize(rows) |
| s["s_per_iter"] = float(np.mean([r["s_per_iter"] for r in rows])) |
| scratch_summary[opt] = s |
|
|
| efficiency = { |
| "sam_over_fsgld_s_per_iter": scratch_summary["SAM"]["s_per_iter"] / scratch_summary["fSGLD"]["s_per_iter"], |
| "sam_over_sgd": scratch_summary["SAM"]["s_per_iter"] / scratch_summary["SGD"]["s_per_iter"], |
| "fsgld_over_sgd": scratch_summary["fSGLD"]["s_per_iter"] / scratch_summary["SGD"]["s_per_iter"], |
| } |
|
|
| |
| ablation_jobs = [(eta, s) for eta in etas for s in seeds] |
| ablation_rows = Parallel(n_jobs=job_cores)( |
| delayed(ablation_unit)(prefix, eta, s, train_x, train_noisy_y, test_x, test_y, |
| epochs_scratch, milestones_scratch) |
| for eta, s in ablation_jobs |
| ) |
| ablation_summary = [] |
| for eta in etas: |
| rows = [r for r in ablation_rows if abs(r["eta"] - eta) < 1e-9] |
| s = summarize(rows) |
| s["eta"] = eta |
| ablation_summary.append(s) |
|
|
| |
| Parallel(n_jobs=job_cores)( |
| delayed(pretrain_unit)(prefix, s, train_x, train_clean_y, epochs_pretrain, milestones_scratch) |
| for s in seeds |
| ) |
|
|
| ft_jobs = [(opt, s) for opt in ("SGD", "SAM", "fSGLD") for s in seeds] |
| finetune_rows = Parallel(n_jobs=job_cores)( |
| delayed(finetune_unit)(prefix, opt, s, |
| os.path.join(WORK_DIR, f"{prefix}_pretrain_seed{s}.pt"), |
| train_x, train_noisy_y, test_x, test_y, epochs_ft, milestones_ft) |
| for opt, s in ft_jobs |
| ) |
| finetune_summary = {} |
| for opt in ("SGD", "SAM", "fSGLD"): |
| rows = [r for r in finetune_rows if r["optimizer"] == opt] |
| finetune_summary[opt] = summarize(rows) |
|
|
| |
| flat_idx = np.random.default_rng(0).choice(train_x.shape[0], min(flat_batch, train_x.shape[0]), replace=False) |
| flat_x = train_x[flat_idx] |
| flat_y = train_clean_y[flat_idx] |
| flatness_rows = Parallel(n_jobs=job_cores)( |
| delayed(flatness_unit)(prefix, opt, |
| os.path.join(WORK_DIR, f"{prefix}_scratchmodel_{opt}_0.pt"), |
| flat_x, flat_y, m_hutch, top_iters) |
| for opt in ("SGD", "SAM", "fSGLD") |
| ) |
|
|
| results = { |
| "scratch": scratch_rows, |
| "scratch_summary": scratch_summary, |
| "efficiency": efficiency, |
| "ablation": ablation_rows, |
| "ablation_summary": ablation_summary, |
| "finetune": finetune_rows, |
| "finetune_summary": finetune_summary, |
| "flatness": flatness_rows, |
| "provenance": provenance, |
| "meta": { |
| "scale": ("REDUCED/toy: SmallCNN 0.5M params, tiny subset, few epochs, CPU; see BLOCKERS.md" |
| if toy else |
| "REDUCED: SmallCNN 0.5M params, 15k subset, 30 epochs, CPU; see BLOCKERS.md"), |
| "beta": BETA, "eta": ETA_FSGLD, "sigma": SIGMA_FSGLD, |
| "n_seeds": len(seeds), "epochs_scratch": epochs_scratch, |
| }, |
| } |
|
|
| out_path = os.path.join(RESULTS_DIR, "exp02.json") |
| with open(out_path, "w") as f: |
| json.dump(results, f, indent=2) |
|
|
| print(f"exp02_neural: {'TOY' if toy else 'FULL'} run complete in {time.time()-t_start:.2f}s") |
| print(f" scratch: SGD={scratch_summary['SGD']['acc_mean']:.4f} " |
| f"SAM={scratch_summary['SAM']['acc_mean']:.4f} fSGLD={scratch_summary['fSGLD']['acc_mean']:.4f}") |
| print(f" s_per_iter: SGD={scratch_summary['SGD']['s_per_iter']:.4f} " |
| f"SAM={scratch_summary['SAM']['s_per_iter']:.4f} fSGLD={scratch_summary['fSGLD']['s_per_iter']:.4f}") |
| print(f" efficiency: {efficiency}") |
| print(f" finetune: SGD={finetune_summary['SGD']['acc_mean']:.4f} " |
| f"SAM={finetune_summary['SAM']['acc_mean']:.4f} fSGLD={finetune_summary['fSGLD']['acc_mean']:.4f}") |
| print(f" provenance: {provenance}") |
| print(f" results -> {out_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|