vimarsh's picture
Upload variants.py with huggingface_hub
cefd94c verified
Raw
History Blame Contribute Delete
4.53 kB
"""
Model extensions for Claim 5 (Sec. 7.1-7.2):
(1) softmax variant -> reuses capacity.train_run(softmax=True)
(2) value-channel / message-retrieval variant (Sec. 7.2): frozen random value map
W_V, mix messages with raw max-over-heads scores, train MSE to neighbor message.
Both keep the key-query path identical (max-over-heads, no 1/sqrt(d_k)) and test whether
the multi-head advantage persists.
"""
import math, argparse, json
import numpy as np
import torch
import torch.nn.functional as F
from capacity import (make_embeddings, make_permutation, sample_contexts,
MaxHeadAttention)
def value_retrieval_run(m, d_model, D_K, h, seed, device, d_msg=None,
ell=16, rho=0.5, lr=1e-3, max_steps=20000, batch=64,
check_every=500, patience=8, pool=20000, verbose=False):
"""Sec. 7.2: value-routing message retrieval. Reports test MSE (lower=better)."""
torch.manual_seed(seed)
d_msg = d_msg or d_model
X = make_embeddings(m, d_model, seed, device)
pi = make_permutation(m, seed)
pi_t = torch.as_tensor(pi)
WV = (torch.randn(d_model, d_msg, generator=torch.Generator().manual_seed(seed + 5))
/ math.sqrt(d_model)).to(device) # frozen random value map
Y_all = X @ WV # per-node messages (m, d_msg)
def batch_tensors(ctx):
ctx_t = torch.as_tensor(ctx)
Xc = X[ctx_t.to(device)] # (n, ell, d_model)
tgt = pi_t[ctx_t] # (n, ell) neighbor id
# valid position: neighbor in-context
inctx = (tgt.unsqueeze(2) == ctx_t.unsqueeze(1)) # (n, ell, ell)
valid = inctx.any(dim=2) # (n, ell)
ymsg = Y_all[tgt.to(device)] # (n, ell, d_msg) true neighbor msg
Vc = X[ctx_t.to(device)] @ WV # (n, ell, d_msg) in-context messages
return Xc, Vc, ymsg, valid.to(device)
model = MaxHeadAttention(d_model, D_K, h, agg="max").to(device)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
train_ctx = sample_contexts(pi, m, ell, rho, pool, seed + 3)
val_ctx = sample_contexts(pi, m, ell, rho, 500, seed + 1)
test_ctx = sample_contexts(pi, m, ell, rho, 2000, seed + 2)
Xtr, Vtr, Ytr, valtr = batch_tensors(train_ctx)
Xv, Vv, Yv, valv = batch_tensors(val_ctx)
Xte, Vte, Yte, valte = batch_tensors(test_ctx)
def mse(Xc, Vc, ymsg, valid):
S = model.scores(Xc) # (n, ell, ell) raw max-over-heads
yhat = torch.einsum("nij,njd->nid", S, Vc) # (n, ell, d_msg)
err = ((yhat - ymsg) ** 2).sum(-1) # (n, ell)
return err[valid].mean()
g = torch.Generator().manual_seed(seed + 7)
order = torch.randperm(pool, generator=g); ptr = 0
best_val = float("inf"); bad = 0
for step in range(1, max_steps + 1):
if ptr + batch > pool:
order = torch.randperm(pool, generator=g); ptr = 0
idx = order[ptr:ptr + batch]; ptr += batch
loss = mse(Xtr[idx], Vtr[idx], Ytr[idx], valtr[idx])
opt.zero_grad(); loss.backward(); opt.step()
if step % check_every == 0:
with torch.no_grad():
v = mse(Xv, Vv, Yv, valv).item()
if verbose:
print(f" step {step} valMSE {v:.4f}", flush=True)
if v < best_val - 1e-4:
best_val = v; bad = 0
else:
bad += 1
if bad >= patience:
break
with torch.no_grad():
test_mse = mse(Xte, Vte, Yte, valte).item()
return {"m": m, "d_model": d_model, "D_K": D_K, "h": h, "d_k": D_K // h,
"seed": seed, "test_mse": test_mse, "steps": step}
if __name__ == "__main__":
dev = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
print("device", dev)
# Value retrieval: m=64, compressed d_model=16 -> multi-head advantage (Fig 6 top)
for dm in [16, 32]:
print(f"\n=== Value retrieval m=64 d_model={dm} (Sec 7.2, Fig 6) ===")
for h in [1, 2, 4, 8]:
for DK in [16, 32]:
if DK % h or DK // h < 2:
continue
r = value_retrieval_run(64, dm, DK, h, seed=0, device=dev,
max_steps=8000, batch=64)
print(f" d_model={dm} h={h} D_K={DK} test_MSE={r['test_mse']:.4f}")