Yashp2003's picture
download
raw
5.87 kB
# /// script
# dependencies = ["torch", "numpy"]
# ///
"""ICML 2026 #13315 — Figure 2(B)(C)(D) sweeps on the paper's config.
- (B) Excess risk vs K (number of patterns per data point): K in {1,2,4,8}
- (C) Excess risk vs min_u pi_tilde_u (pattern proportion skew): uniform, 0.05, 0.02
- (D) Sampling strategy: t ~ Unif([T]) vs first 40% vs last 40%
All at d=64, M=8, P=256, rho=0.3, T=50, alpha1=0.98, alphaT=0.95.
"""
import torch
import torch.nn as nn
import numpy as np
import json
import time
import os
torch.manual_seed(42)
np.random.seed(42)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
def make_patterns(d, M):
mu = torch.randn(M, d)
mu = mu - mu.mean(dim=0)
for i in range(M):
for j in range(i):
mu[i] -= mu[i] @ mu[j] / (mu[j] @ mu[j]) * mu[j]
mu[i] = mu[i] / mu[i].norm() * np.sqrt(d)
return mu
def sample_mtgm(num_samples, d, M, K, P, rho, pi_tilde, mu, device="cpu"):
dev = mu.device
pi_tilde = pi_tilde.to(dev)
Z = torch.zeros(num_samples, M, device=dev)
idx = torch.argsort(torch.rand(num_samples, M, device=dev), dim=1)[:, :K]
Z.scatter_(1, idx, 1.0)
pi_Z = Z.float() * pi_tilde.unsqueeze(0)
pi_Z = pi_Z / pi_Z.sum(dim=1, keepdim=True)
Y = torch.multinomial(pi_Z, num_samples=P, replacement=True)
X = mu[Y].transpose(1, 2) + rho * torch.randn(num_samples, d, P, device=dev)
return X.to(device), Y.to(device)
class OneLayerTransformer(nn.Module):
def __init__(self, d, T):
super().__init__()
self.d = d
self.W = nn.Parameter(torch.zeros(d, d))
self.v = nn.Parameter(torch.randn(T) / np.sqrt(d))
def forward(self, X, t):
X_T = X.permute(0, 2, 1)
qk = X_T @ self.W @ X / self.d
attn = torch.softmax(qk, dim=1)
agg = X @ attn
v_t = self.v[t]
return v_t.unsqueeze(-1).unsqueeze(-1) * (X - agg)
def train(model, X_train, alpha_bar, T, d, P, num_iters, lr, batch_size=128, t_mode="unif"):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
n = X_train.size(0)
lo, hi = (0, T) if t_mode == "unif" else ((0, int(0.4 * T)) if t_mode == "first" else (int(0.6 * T), T))
model.train()
for step in range(num_iters):
idx = torch.randint(0, n, (batch_size,))
x0 = X_train[idx]
t_idx = torch.randint(lo, hi, (batch_size,))
eps = torch.randn_like(x0)
xt = torch.sqrt(alpha_bar[t_idx].view(-1, 1, 1)) * x0 + torch.sqrt(1 - alpha_bar[t_idx].view(-1, 1, 1)) * eps
loss = (model(xt, t_idx) - eps).pow(2).sum(dim=(1, 2)).mean() / (2 * d * P)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return losses_eval(model, X_train[:256], alpha_bar, T, d, P)
@torch.no_grad()
def losses_eval(model, X, alpha_bar, T, d, P):
model.eval()
n = X.size(0)
total = 0.0
for t in range(T):
eps = torch.randn_like(X)
sq = torch.sqrt(alpha_bar[t])
xt = sq * X + torch.sqrt(1 - alpha_bar[t]) * eps
f = model(xt, torch.full((n,), t, dtype=torch.long, device=xt.device))
total += (f - eps).pow(2).sum(dim=(1, 2)).mean().item() / (2 * d * P)
return total / T
@torch.no_grad()
def concentration(model, X, Y, alpha_bar, T, d, P):
model.eval()
n = min(32, X.size(0))
t = T // 2
xt = torch.sqrt(alpha_bar[t]) * X[:n] + torch.sqrt(1 - alpha_bar[t]) * torch.randn_like(X[:n])
qk = xt.permute(0, 2, 1) @ model.W @ xt / d
attn = torch.softmax(qk, dim=1)
Ys = Y[:n]
same = []
for b in range(n):
for p in range(P):
mask = (Ys[b] == Ys[b, p]).float()
same.append(attn[b, :, p].dot(mask).item())
return float(np.mean(same))
def run_sweep(tag, cfg, alpha_bar, mu, out):
d, M, K, P, rho, T = cfg["d"], cfg["M"], cfg["K"], cfg["P"], cfg["rho"], cfg["T"]
pi_tilde = torch.ones(M) / M if cfg.get("pi_skew", 0) == 0 else None
if pi_tilde is None:
pi_tilde = torch.full((M,), 1.0)
pi_tilde[:3] = cfg["pi_skew"]
pi_tilde = pi_tilde / pi_tilde.sum()
t_mode = cfg.get("t_mode", "unif")
t0 = time.time()
Xtr, Ytr = sample_mtgm(cfg["num_train"], d, M, K, P, rho, pi_tilde, mu, device=DEVICE)
Xte, Yte = sample_mtgm(512, d, M, K, P, rho, pi_tilde, mu, device=DEVICE)
model = OneLayerTransformer(d, T).to(DEVICE)
train(model, Xtr, alpha_bar.to(DEVICE), T, d, P, cfg["num_iters"], cfg["lr"], cfg["batch_size"], t_mode)
loss = losses_eval(model, Xte, alpha_bar.to(DEVICE), T, d, P)
conc = concentration(model, Xte, Yte, alpha_bar.to(DEVICE), T, d, P)
res = {"tag": tag, "ddpm_loss": loss, "concentration": conc,
"cfg": {k: v for k, v in cfg.items() if k != "num_train"}, "wall_s": time.time() - t0}
print(f"{tag}: loss={loss:.4f} conc={conc:.3f} ({time.time()-t0:.0f}s)")
out[tag] = res
def main():
d, M, P, rho, T = 64, 8, 256, 0.3, 50
alpha_t = torch.linspace(0.98, 0.95, T)
alpha_bar = torch.cumprod(alpha_t, dim=0)
mu = make_patterns(d, M).to(DEVICE)
base = {"d": d, "M": M, "P": P, "rho": rho, "T": T,
"num_train": 4096, "num_iters": 6000, "lr": 3e-3, "batch_size": 128}
out = {}
for K in [1, 2, 8]:
cfg = dict(base); cfg["K"] = K
run_sweep(f"K{K}", cfg, alpha_bar, mu, out)
for skew in [0.05, 0.02]:
cfg = dict(base); cfg["K"] = 4; cfg["pi_skew"] = skew
run_sweep(f"piskew{skew}", cfg, alpha_bar, mu, out)
for tmode in ["first", "last"]:
cfg = dict(base); cfg["K"] = 4; cfg["t_mode"] = tmode
run_sweep(f"tmode-{tmode}", cfg, alpha_bar, mu, out)
outdir = os.environ.get("OUT_DIR", ".")
with open(os.path.join(outdir, "sweeps.json"), "w") as f:
json.dump(out, f, indent=2)
print("\nSweeps saved:", json.dumps(out, indent=1)[:2000])
if __name__ == "__main__":
main()

Xet Storage Details

Size:
5.87 kB
·
Xet hash:
02cf1d82e86147408df75f73dcdce2932f3d5e34353f7a37aeefaffcd994e9d9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.