μLattice: live demo — your own facts, store at scale
Browse files- BLOG.md +28 -0
- README.md +18 -8
- app.py +214 -0
- checkpoints/capacity8k.pt +3 -0
- requirements.txt +2 -0
- src/.DS_Store +0 -0
- src/mulattice/.DS_Store +0 -0
- src/mulattice/__pycache__/addressing.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/autoscan.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/fastscan.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/kernel.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/lattice.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/models.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/mqar.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/protocol.cpython-314.pyc +0 -0
- src/mulattice/__pycache__/sparse_scan.cpython-314.pyc +0 -0
- src/mulattice/addressing.py +89 -0
- src/mulattice/autoscan.py +83 -0
- src/mulattice/fastscan.py +171 -0
- src/mulattice/kernel.py +132 -0
- src/mulattice/lattice.py +225 -0
- src/mulattice/models.py +282 -0
- src/mulattice/mqar.py +61 -0
- src/mulattice/protocol.py +496 -0
- src/mulattice/sparse_scan.py +131 -0
BLOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# μLattice: Breaking the Quadratic Memory Barrier in AI
|
| 2 |
+
|
| 3 |
+
**Tensorbend Research · Eric E. · October 2026**
|
| 4 |
+
|
| 5 |
+
## TL;DR
|
| 6 |
+
|
| 7 |
+
AI models today pay quadratically more to remember more. Attention scores every
|
| 8 |
+
stored token against every new query: doubling the context quadruples the cost.
|
| 9 |
+
μLattice breaks this barrier. Memory grows with the input — each token reads and
|
| 10 |
+
writes exactly 9 cells — so the cost per token stays flat no matter how much is
|
| 11 |
+
stored.
|
| 12 |
+
|
| 13 |
+
Measured on the released checkpoint: recall of 1.0000 at 8,192 stored pairs in a
|
| 14 |
+
133K-token sequence; 0.9980 on overwrite queries; 1.0000 on real-text retrieval
|
| 15 |
+
at 259K tokens; and per-token cost flat at ~10μs from 32K to 131K tokens while
|
| 16 |
+
the lattice grows to 37,000 cells.
|
| 17 |
+
|
| 18 |
+
## Try it
|
| 19 |
+
|
| 20 |
+
Use the **Your Own Facts** tab above. Paste any text, define facts as
|
| 21 |
+
name→value pairs, mark which get overwritten mid-stream, and watch the model
|
| 22 |
+
store, replace, and recall them — in one pass through your text.
|
| 23 |
+
|
| 24 |
+
## Links
|
| 25 |
+
|
| 26 |
+
- [Full paper](https://github.com/eelbaz/mLattice/blob/main/PAPER.md)
|
| 27 |
+
- [Code & tests](https://github.com/eelbaz/mLattice)
|
| 28 |
+
- [Results & figures](https://github.com/eelbaz/mLattice/tree/main/results)
|
README.md
CHANGED
|
@@ -1,13 +1,23 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
-
pinned:
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: μLattice
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: "5.0.0"
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: Breaking the quadratic memory barrier in AI
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# μLattice
|
| 15 |
+
|
| 16 |
+
**Breaking the quadratic memory barrier in AI.**
|
| 17 |
+
|
| 18 |
+
A memory system for AI models that grows as it reads while the cost per token stays flat.
|
| 19 |
+
|
| 20 |
+
- **Your Own Facts** tab: paste text, define facts, mark overwrites — the model stores and answers
|
| 21 |
+
- **Store at Scale** tab: up to 8,192 pairs, 50% overwritten, one causal pass
|
| 22 |
+
|
| 23 |
+
Tensorbend Research · Eric E. · October 2026
|
app.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import sys, os, json, time, hashlib
|
| 4 |
+
|
| 5 |
+
sys.path.insert(0, "src")
|
| 6 |
+
|
| 7 |
+
from mulattice.protocol import (
|
| 8 |
+
SynthCfg, build_model, force_fast_scan, logits_at, synth_batch, key_addresses
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
DEVICE = "cpu" # HF free tier
|
| 12 |
+
CFG = SynthCfg()
|
| 13 |
+
|
| 14 |
+
print("Loading model...", flush=True)
|
| 15 |
+
ck = torch.load("checkpoints/capacity8k.pt", map_location="cpu", weights_only=False)
|
| 16 |
+
CFG.addr_scale = float(ck["proto_cfg"]["addr_scale"])
|
| 17 |
+
MODEL = build_model(CFG)
|
| 18 |
+
MODEL.load_state_dict(ck["model"])
|
| 19 |
+
MODEL = MODEL.to(DEVICE).eval()
|
| 20 |
+
force_fast_scan(MODEL)
|
| 21 |
+
print("Model loaded.", flush=True)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# --- Section 1: Your own stream ---
|
| 25 |
+
def run_custom(text, *pair_inputs):
|
| 26 |
+
"""Store user's facts in user's text, overwrite some, query all."""
|
| 27 |
+
seed = int(time.time()) % 100000
|
| 28 |
+
pairs = []
|
| 29 |
+
for i in range(0, len(pair_inputs), 3):
|
| 30 |
+
name, val, new_val = pair_inputs[i], pair_inputs[i+1], pair_inputs[i+2]
|
| 31 |
+
if name.strip() and val.strip():
|
| 32 |
+
pairs.append({"name": name.strip(), "value": val.strip(),
|
| 33 |
+
"new_value": new_val.strip() if new_val.strip() else None})
|
| 34 |
+
if not pairs:
|
| 35 |
+
return "Enter at least one fact (name and value).", ""
|
| 36 |
+
|
| 37 |
+
used = set()
|
| 38 |
+
def h(s, span, off):
|
| 39 |
+
x = int(hashlib.md5(f"{seed}:{s}".encode()).hexdigest(), 16) % span
|
| 40 |
+
while (off + x) in used:
|
| 41 |
+
x = (x + 1) % span
|
| 42 |
+
used.add(off + x)
|
| 43 |
+
return off + x
|
| 44 |
+
|
| 45 |
+
kmap, vmap = {}, {}
|
| 46 |
+
for p in pairs:
|
| 47 |
+
kmap[p["name"]] = h("k" + p["name"], CFG.NK, 0)
|
| 48 |
+
for p in pairs:
|
| 49 |
+
vmap[p["value"]] = h("v" + p["value"], CFG.NV, CFG.NK)
|
| 50 |
+
if p["new_value"]:
|
| 51 |
+
vmap[p["new_value"]] = h("v2" + p["new_value"], CFG.NV, CFG.NK)
|
| 52 |
+
|
| 53 |
+
words = [w for w in text.split() if w.strip()][:500] or ["..."]
|
| 54 |
+
fid = {}
|
| 55 |
+
for w in set(words):
|
| 56 |
+
fid[w] = h("f" + w, CFG.NK, 0)
|
| 57 |
+
fill = [fid[w] for w in words]
|
| 58 |
+
|
| 59 |
+
store_rows, upd_rows = [], []
|
| 60 |
+
for p in pairs:
|
| 61 |
+
vid = vmap[p["value"]]
|
| 62 |
+
row = dict(p); row["kid"] = kmap[p["name"]]; row["vid"] = vid
|
| 63 |
+
if p["new_value"]:
|
| 64 |
+
row["nid"] = vmap[p["new_value"]]
|
| 65 |
+
upd_rows.append(row)
|
| 66 |
+
store_rows.append(row)
|
| 67 |
+
|
| 68 |
+
F = 6; block = F + 2
|
| 69 |
+
n_upd = len(upd_rows)
|
| 70 |
+
Q = len(store_rows)
|
| 71 |
+
L = (len(store_rows) + n_upd) * block + 2 * Q
|
| 72 |
+
toks = torch.zeros(1, L, dtype=torch.long)
|
| 73 |
+
latest = {}
|
| 74 |
+
|
| 75 |
+
def take_filler(n):
|
| 76 |
+
out = []
|
| 77 |
+
while len(out) < n:
|
| 78 |
+
i = int(torch.randint(0, len(fill), (1,)))
|
| 79 |
+
out.extend(fill[i:i+n-len(out)])
|
| 80 |
+
return out[:n]
|
| 81 |
+
|
| 82 |
+
for i, r in enumerate(store_rows):
|
| 83 |
+
s = i * block
|
| 84 |
+
toks[0, s:s+F] = torch.tensor(take_filler(F))
|
| 85 |
+
toks[0, s+F], toks[0, s+F+1] = r["kid"], r["vid"]
|
| 86 |
+
latest[r["kid"]] = r["vid"]
|
| 87 |
+
for j, r in enumerate(upd_rows):
|
| 88 |
+
s = (len(store_rows) + j) * block
|
| 89 |
+
toks[0, s:s+F] = torch.tensor(take_filler(F))
|
| 90 |
+
toks[0, s+F], toks[0, s+F+1] = r["kid"], r["nid"]
|
| 91 |
+
latest[r["kid"]] = r["nid"]
|
| 92 |
+
S2 = (len(store_rows) + n_upd) * block
|
| 93 |
+
ans_list = []
|
| 94 |
+
for q, r in enumerate(store_rows):
|
| 95 |
+
toks[0, S2+2*q] = r["kid"]
|
| 96 |
+
toks[0, S2+2*q+1] = CFG.SEP
|
| 97 |
+
ans_list.append(S2 + 2*q + 1)
|
| 98 |
+
|
| 99 |
+
ans = torch.tensor([ans_list])
|
| 100 |
+
t0 = time.time()
|
| 101 |
+
with torch.no_grad():
|
| 102 |
+
pred = logits_at(MODEL, toks, ans).argmax(-1).cpu()
|
| 103 |
+
dt = time.time() - t0
|
| 104 |
+
|
| 105 |
+
inv = {v: k for k, v in vmap.items()}
|
| 106 |
+
correct = 0
|
| 107 |
+
lines = ["| Asked | Answered | Expected | Result |", "|---|---|---|---|"]
|
| 108 |
+
for q, r in enumerate(store_rows):
|
| 109 |
+
got = inv.get(int(pred[0, q]), f"?{int(pred[0,q])}")
|
| 110 |
+
exp = r["new_value"] if r["new_value"] else r["value"]
|
| 111 |
+
ok = got == exp
|
| 112 |
+
correct += ok
|
| 113 |
+
old = f" (was: {r['value']})" if r["new_value"] else ""
|
| 114 |
+
lines.append(f"| {r['name']} | **{got}** | {exp}{old} | {'✅' if ok else '❌'} |")
|
| 115 |
+
|
| 116 |
+
stats = f"\n\n**{correct}/{len(store_rows)} correct** · {L:,} tokens · {dt:.2f}s · {dt/L*1e6:.0f}μs/token"
|
| 117 |
+
return "\n".join(lines), stats
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# --- Section 2: Scale test ---
|
| 121 |
+
def run_scale(n_pairs, filler, overwrite):
|
| 122 |
+
g = torch.Generator().manual_seed(42)
|
| 123 |
+
b = synth_batch(1, int(n_pairs), min(32, int(n_pairs)), CFG,
|
| 124 |
+
filler=int(filler), overwrite_frac=float(overwrite)/100, generator=g)
|
| 125 |
+
t0 = time.time()
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
pred = logits_at(MODEL, b["tokens"], b["ans_pos"]).argmax(-1).cpu()
|
| 128 |
+
dt = time.time() - t0
|
| 129 |
+
ok = (pred == b["gold"]).squeeze(0)
|
| 130 |
+
n_cells = MODEL.blocks[0].mixer.scan.last_n_cells
|
| 131 |
+
return (f"Recall: **{ok.float().mean():.4f}** ({int(ok.sum())}/{ok.numel()})\n\n"
|
| 132 |
+
f"Tokens: {b['L']:,} · Cells: {n_cells:,} · Time: {dt:.2f}s · "
|
| 133 |
+
f"{dt/b['L']*1e6:.0f}μs/token")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# --- Build UI ---
|
| 137 |
+
with gr.Blocks(title="μLattice — Breaking the Quadratic Memory Barrier in AI",
|
| 138 |
+
theme=gr.themes.Default(font=["Inter", "sans-serif"])) as demo:
|
| 139 |
+
gr.Markdown("""
|
| 140 |
+
# μLattice
|
| 141 |
+
## Breaking the quadratic memory barrier in AI
|
| 142 |
+
|
| 143 |
+
**Tensorbend Research · Eric E. · October 2026**
|
| 144 |
+
|
| 145 |
+
A memory system for AI models that grows as it reads while the cost per token stays flat.
|
| 146 |
+
Store thousands of associations, overwrite any of them, and recall them all —
|
| 147 |
+
whether the memory holds ten facts or eight thousand.
|
| 148 |
+
|
| 149 |
+
Each token reads and writes exactly **9 cells** on a 2D lattice. Memory grows with content.
|
| 150 |
+
Access cost doesn't.
|
| 151 |
+
""")
|
| 152 |
+
|
| 153 |
+
with gr.Tab("📖 Your Own Facts"):
|
| 154 |
+
gr.Markdown("""
|
| 155 |
+
**Paste any text below** (it becomes the stream the model reads).
|
| 156 |
+
**Define facts** as name → value pairs. Mark which get **overwritten** mid-stream.
|
| 157 |
+
The model stores, overwrites, and answers — in one pass through your text.
|
| 158 |
+
""")
|
| 159 |
+
with gr.Row():
|
| 160 |
+
with gr.Column():
|
| 161 |
+
doc = gr.Textbox(label="Your text (becomes the stream)", lines=5,
|
| 162 |
+
value="The harbour was quiet that morning. Gulls circled the masts while the tide went out. A clerk stamped papers without looking up. Somewhere a bell rang twice, then stopped. The road east had been washed out again. Dust settled over the market stalls.")
|
| 163 |
+
with gr.Row():
|
| 164 |
+
n1 = gr.Textbox(label="Fact name", value="the vault password")
|
| 165 |
+
v1 = gr.Textbox(label="Value", value="swordfish")
|
| 166 |
+
nv1 = gr.Textbox(label="New value (overwrite to)", value="bluedragon")
|
| 167 |
+
with gr.Row():
|
| 168 |
+
n2 = gr.Textbox(label="Fact name", value="the meeting time")
|
| 169 |
+
v2 = gr.Textbox(label="Value", value="3pm")
|
| 170 |
+
nv2 = gr.Textbox(label="New value", value="")
|
| 171 |
+
with gr.Row():
|
| 172 |
+
n3 = gr.Textbox(label="Fact name", value="")
|
| 173 |
+
v3 = gr.Textbox(label="Value", value="")
|
| 174 |
+
nv3 = gr.Textbox(label="New value", value="")
|
| 175 |
+
btn1 = gr.Button("Read, store, overwrite — and answer", variant="primary")
|
| 176 |
+
with gr.Column():
|
| 177 |
+
out1 = gr.Markdown()
|
| 178 |
+
stats1 = gr.Markdown()
|
| 179 |
+
btn1.click(run_custom, inputs=[doc, n1,v1,nv1, n2,v2,nv2, n3,v3,nv3], outputs=[out1, stats1])
|
| 180 |
+
|
| 181 |
+
with gr.Tab("📊 Store at Scale"):
|
| 182 |
+
gr.Markdown("""
|
| 183 |
+
Test the model at scale: up to **8,192 stored pairs**, **50% overwritten**,
|
| 184 |
+
answered after a single causal pass.
|
| 185 |
+
""")
|
| 186 |
+
with gr.Row():
|
| 187 |
+
np_slider = gr.Slider(64, 8192, value=256, step=64, label="Pairs to store")
|
| 188 |
+
fl_slider = gr.Slider(0, 14, value=14, step=1, label="Filler tokens per pair")
|
| 189 |
+
ow_slider = gr.Slider(0, 100, value=50, step=10, label="% overwritten")
|
| 190 |
+
btn2 = gr.Button("Stream & query", variant="primary")
|
| 191 |
+
out2 = gr.Markdown()
|
| 192 |
+
btn2.click(run_scale, inputs=[np_slider, fl_slider, ow_slider], outputs=[out2])
|
| 193 |
+
|
| 194 |
+
gr.Markdown("""
|
| 195 |
+
---
|
| 196 |
+
|
| 197 |
+
**Every number on this page is produced by a live forward pass** of the trained model
|
| 198 |
+
on the released checkpoint. Nothing is precomputed.
|
| 199 |
+
|
| 200 |
+
[Paper](https://github.com/eelbaz/mLattice/blob/main/PAPER.md) ·
|
| 201 |
+
[Code](https://github.com/eelbaz/mLattice) ·
|
| 202 |
+
[Tests](https://github.com/eelbaz/mLattice/tree/main/tests)
|
| 203 |
+
|
| 204 |
+
```bibtex
|
| 205 |
+
@misc{mulattice2026,
|
| 206 |
+
title = {μLattice: Breaking the Quadratic Memory Barrier in AI},
|
| 207 |
+
author = {Eric E. and Tensorbend Research},
|
| 208 |
+
year = {2026},
|
| 209 |
+
url = {github.com/eelbaz/mLattice}
|
| 210 |
+
}
|
| 211 |
+
```
|
| 212 |
+
""")
|
| 213 |
+
|
| 214 |
+
demo.launch()
|
checkpoints/capacity8k.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:488a4693a2300a15355b9ec072b81ad035cf5a0e5390d31279045c50ddf9b74e
|
| 3 |
+
size 16957045
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.4
|
| 2 |
+
numpy
|
src/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
src/mulattice/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
src/mulattice/__pycache__/addressing.cpython-314.pyc
ADDED
|
Binary file (7.88 kB). View file
|
|
|
src/mulattice/__pycache__/autoscan.cpython-314.pyc
ADDED
|
Binary file (5.54 kB). View file
|
|
|
src/mulattice/__pycache__/fastscan.cpython-314.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
src/mulattice/__pycache__/kernel.cpython-314.pyc
ADDED
|
Binary file (9.05 kB). View file
|
|
|
src/mulattice/__pycache__/lattice.cpython-314.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
src/mulattice/__pycache__/models.cpython-314.pyc
ADDED
|
Binary file (22.2 kB). View file
|
|
|
src/mulattice/__pycache__/mqar.cpython-314.pyc
ADDED
|
Binary file (4.13 kB). View file
|
|
|
src/mulattice/__pycache__/protocol.cpython-314.pyc
ADDED
|
Binary file (35.2 kB). View file
|
|
|
src/mulattice/__pycache__/sparse_scan.cpython-314.pyc
ADDED
|
Binary file (9.86 kB). View file
|
|
|
src/mulattice/addressing.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Address-diversity regularisation for μLattice (experimental).
|
| 2 |
+
|
| 3 |
+
A mixture-of-experts-style load-balancing term applied to addresses: maximise the entropy of
|
| 4 |
+
the soft cell-usage distribution so addresses stay spread instead of collapsing onto a few
|
| 5 |
+
cells.
|
| 6 |
+
|
| 7 |
+
Status: the *collapse* hypothesis that motivated this was later contradicted -- on CUDA a run
|
| 8 |
+
with every key in one cell still generalised (0.875 at 256 keys), and the term did not
|
| 9 |
+
reproducibly help. It is kept as a documented experiment, not a recommended part of the mixer.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def usage_entropy(addr: torch.Tensor, scale: float, grid: int = 24) -> torch.Tensor:
|
| 17 |
+
"""Entropy (nats) of the soft cell-usage distribution of `addr` (..., 2).
|
| 18 |
+
|
| 19 |
+
Addresses are normalised into a `grid` x `grid` histogram by differentiable bilinear
|
| 20 |
+
assignment, so the entropy carries gradient back to the address projection. Maximum is
|
| 21 |
+
log(grid**2); a collapsed map gives near zero.
|
| 22 |
+
"""
|
| 23 |
+
x = (addr[..., 0].clamp(-scale, scale) + scale) / (2 * scale) # -> [0, 1]
|
| 24 |
+
y = (addr[..., 1].clamp(-scale, scale) + scale) / (2 * scale)
|
| 25 |
+
gx = (x * grid).clamp(0.0, float(grid) - 1e-6) # [0, grid)
|
| 26 |
+
gy = (y * grid).clamp(0.0, float(grid) - 1e-6)
|
| 27 |
+
ix = gx.floor().long(); iy = gy.floor().long()
|
| 28 |
+
fx = (gx - ix.float()).reshape(-1); fy = (gy - iy.float()).reshape(-1)
|
| 29 |
+
ix1 = (ix + 1).clamp(max=grid - 1); iy1 = (iy + 1).clamp(max=grid - 1)
|
| 30 |
+
|
| 31 |
+
p = torch.zeros(grid * grid, device=addr.device, dtype=torch.float32)
|
| 32 |
+
p.index_add_(0, (ix * grid + iy).reshape(-1), ((1 - fx) * (1 - fy)).float())
|
| 33 |
+
p.index_add_(0, (ix1 * grid + iy).reshape(-1), (fx * (1 - fy)).float())
|
| 34 |
+
p.index_add_(0, (ix * grid + iy1).reshape(-1), ((1 - fx) * fy).float())
|
| 35 |
+
p.index_add_(0, (ix1 * grid + iy1).reshape(-1), (fx * fy).float())
|
| 36 |
+
p = p / p.sum().clamp_min(1e-9)
|
| 37 |
+
return -(p * (p + 1e-12).log()).sum()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def address_diversity_loss(addr: torch.Tensor, scale: float, grid: int = 24) -> torch.Tensor:
|
| 41 |
+
"""Minimise this to keep addresses spread: negative entropy of cell usage."""
|
| 42 |
+
return -usage_entropy(addr, scale, grid)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def write_overlap(addr: torch.Tensor) -> torch.Tensor:
|
| 46 |
+
"""Mean pairwise published-kernel overlap of write addresses, (B, N, 2) -> (B,).
|
| 47 |
+
|
| 48 |
+
D(k_i, k_j) = D1(x) * D1(y) from kernel.py measures exactly what the scan interferes
|
| 49 |
+
on: shared 3x3 cell neighbourhoods. This is the quantity the collision gate uses --
|
| 50 |
+
NOT a grid histogram of the address box.
|
| 51 |
+
"""
|
| 52 |
+
from .kernel import D_1
|
| 53 |
+
B, N, _ = addr.shape
|
| 54 |
+
x = addr[..., 0]
|
| 55 |
+
y = addr[..., 1]
|
| 56 |
+
dx = D_1(x[:, :, None], x[:, None, :]) # (B, N, N)
|
| 57 |
+
dy = D_1(y[:, :, None], y[:, None, :])
|
| 58 |
+
D = dx * dy
|
| 59 |
+
diag = N # D(i,i) == 1 each
|
| 60 |
+
off = (D.sum(dim=(1, 2)) - diag) / max(N * (N - 1), 1)
|
| 61 |
+
return off
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def gated_spread_loss(addr: torch.Tensor, scale: float, gate_thresh: float = 0.05) -> torch.Tensor:
|
| 65 |
+
"""Collision-gated spread: lambda_t = clamp(overlap - 0.05, 0, 1) times the NEGATIVE
|
| 66 |
+
entropy of centre-cell usage, where usage is the real phi weights on the real integer
|
| 67 |
+
cells (not a histogram grid). Zero when the keys are already spread; positive only
|
| 68 |
+
while they actually collide."""
|
| 69 |
+
from .kernel import phi_2d
|
| 70 |
+
B, N, _ = addr.shape
|
| 71 |
+
# Floor 0.3 + gated escalation to 1.0. A pure gate self-disables at TRAIN-time key
|
| 72 |
+
# counts (64 keys spread well enough that overlap < thresh), leaving eval-time packing
|
| 73 |
+
# (256 keys) unaddressed -- measured: gated-only plateaued @256 at 0.66 vs 0.91 baseline.
|
| 74 |
+
gate = (write_overlap(addr) - gate_thresh).clamp(0.0, 1.0).detach()
|
| 75 |
+
lam = 0.3 + 0.7 * gate
|
| 76 |
+
w, z = phi_2d(addr) # (B,N,3,3), (B,N,3,3,2) int coords
|
| 77 |
+
size = int(2 * scale + 3)
|
| 78 |
+
off = int(scale) + 1 # keep integer arithmetic
|
| 79 |
+
gi = (z + off).clamp(0, size - 1)
|
| 80 |
+
idx = (gi[..., 0] * size + gi[..., 1]).reshape(B, -1).to(torch.int64)
|
| 81 |
+
mass = (w / w.sum(dim=(-2, -1), keepdim=True)).reshape(B, -1) # normalised per key
|
| 82 |
+
hist = torch.zeros(B, size * size, device=addr.device, dtype=addr.dtype)
|
| 83 |
+
idx_f = idx.reshape(B, -1)
|
| 84 |
+
mass_f = mass.reshape(B, -1)
|
| 85 |
+
for b in range(B): # index_add_ needs 1-D indices
|
| 86 |
+
hist[b].index_add_(0, idx_f[b], mass_f[b])
|
| 87 |
+
p = hist / hist.sum(dim=1, keepdim=True).clamp_min(1e-9)
|
| 88 |
+
entropy = -(p * (p + 1e-12).log()).sum(dim=1)
|
| 89 |
+
return (lam * (-entropy)).mean()
|
src/mulattice/autoscan.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adaptive scan: run whichever of the two verified-identical scans is cheaper.
|
| 3 |
+
|
| 4 |
+
`sparse_scan.SparseLatticeScan` walks the sequence token by token (T rounds).
|
| 5 |
+
`fastscan.CellParallelScan` walks it cell by cell (max_writes_per_cell rounds).
|
| 6 |
+
They are the same function -- forward and gradients agree to 1e-13 over
|
| 7 |
+
configurations from clustered to fully spread addresses (tests/test_kernel.py) --
|
| 8 |
+
so which one runs is purely a throughput decision.
|
| 9 |
+
|
| 10 |
+
Measured on MPS at the MQAR shape (B=64, T=136, d=32):
|
| 11 |
+
clustered lattice (~20k cells): token loop 1065 ms, cell-parallel 432 ms @ 17 rounds
|
| 12 |
+
-> crossover near 19 rounds = 0.14*T
|
| 13 |
+
spread lattice (~76k cells): token loop 3038 ms, cell-parallel 226 ms @ 4 rounds
|
| 14 |
+
-> crossover near 54 rounds = 0.40*T
|
| 15 |
+
so the crossover is regime-dependent. A single constant must pick the conservative
|
| 16 |
+
end of that range, otherwise it chooses the *slower* path in the middle band: at
|
| 17 |
+
48 rounds with 0.40*T the cell-parallel path is selected at 2358 ms against a
|
| 18 |
+
1065 ms token loop. 0.15*T is correct in both measured regimes.
|
| 19 |
+
|
| 20 |
+
Rounds come from the keys (a sort over B*T*9 int64), a small fraction of either
|
| 21 |
+
scan, and when the cell-parallel path is chosen its setup is reused.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
from .fastscan import CellParallelScan
|
| 29 |
+
from .sparse_scan import SparseLatticeScan, compact_ids
|
| 30 |
+
from .kernel import MAX_CELLS_PER_TOKEN, phi_2d
|
| 31 |
+
|
| 32 |
+
CROSSOVER = 0.15 # rounds < CROSSOVER * T -> cell-parallel (fast path).
|
| 33 |
+
# VERIFIED (tests/test_kernel.py, same-inputs comparison): both scans have
|
| 34 |
+
# IDENTICAL forward (0.0) and gradients (4e-16); the reads are deterministic
|
| 35 |
+
# (unique (row, cell) index_put) and the write is functional (out-of-place).
|
| 36 |
+
# An earlier "gradient bug" was a test bug comparing the scans at different
|
| 37 |
+
# random inputs. Note: training runs differ at the 1e-3 level (different
|
| 38 |
+
# summation order), which the bootstrap phase transition AMPLIFIES into
|
| 39 |
+
# different transition timing -- use the token-loop for warmup/bootstrap
|
| 40 |
+
# stages (small T, stability matters) and the cell-parallel for long
|
| 41 |
+
# sequences (its speedup grows with T).
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class AdaptiveScan(torch.nn.Module):
|
| 45 |
+
def __init__(self, d_k: int, d_v: int, n_heads: int, crossover: float = CROSSOVER):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.d_k, self.d_v, self.n_heads = d_k, d_v, n_heads
|
| 48 |
+
self.crossover = crossover
|
| 49 |
+
self.slow = SparseLatticeScan(d_k, d_v, n_heads)
|
| 50 |
+
self.fast = CellParallelScan(d_k, d_v, n_heads)
|
| 51 |
+
self.last_n_cells = 0
|
| 52 |
+
self.last_rounds = 0
|
| 53 |
+
self.last_path = None
|
| 54 |
+
|
| 55 |
+
def rounds_estimate(self, q_addr: torch.Tensor, k_addr: torch.Tensor, n_seq: int) -> int:
|
| 56 |
+
"""max writes per (sequence, cell) -- the number of rounds the fast path needs."""
|
| 57 |
+
from .fastscan import _encode
|
| 58 |
+
B = k_addr.shape[0]
|
| 59 |
+
T = k_addr.shape[1]
|
| 60 |
+
_, zk = phi_2d(k_addr.reshape(-1, 2))
|
| 61 |
+
keys = _encode(zk.reshape(B, T, MAX_CELLS_PER_TOKEN, 2), B).reshape(-1)
|
| 62 |
+
order = torch.argsort(keys)
|
| 63 |
+
ks = keys[order]
|
| 64 |
+
first = torch.ones_like(ks, dtype=torch.bool)
|
| 65 |
+
if ks.numel() > 1:
|
| 66 |
+
first[1:] = ks[1:] != ks[:-1]
|
| 67 |
+
ar = torch.arange(ks.numel(), device=ks.device)
|
| 68 |
+
run_start = torch.cummax(torch.where(first, ar, torch.zeros_like(ar)), 0).values
|
| 69 |
+
return int((ar - run_start).max()) + 1 if ks.numel() else 0
|
| 70 |
+
|
| 71 |
+
def forward(self, q_addr, k_addr, q2, kappa, v, alpha, beta, read_mode="all"):
|
| 72 |
+
T = kappa.shape[1]
|
| 73 |
+
rounds = self.rounds_estimate(q_addr, k_addr, kappa.shape[0])
|
| 74 |
+
if rounds < self.crossover * T:
|
| 75 |
+
out, n = self.fast(q_addr, k_addr, q2, kappa, v, alpha, beta, read_mode=read_mode)
|
| 76 |
+
self.last_rounds = self.fast.last_rounds
|
| 77 |
+
self.last_path = "cell-parallel"
|
| 78 |
+
else:
|
| 79 |
+
out, n = self.slow(q_addr, k_addr, q2, kappa, v, alpha, beta, read_mode=read_mode)
|
| 80 |
+
self.last_rounds = rounds
|
| 81 |
+
self.last_path = "token-loop"
|
| 82 |
+
self.last_n_cells = n
|
| 83 |
+
return out, n
|
src/mulattice/fastscan.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Cell-parallel μLattice scan -- the same math, ordered by CELL instead of
|
| 3 |
+
by time.
|
| 4 |
+
|
| 5 |
+
The delta recurrence is sequential *within* a cell but completely independent
|
| 6 |
+
*across* cells, so a token-by-token loop pays T sequential steps when only
|
| 7 |
+
max_writes_per_cell steps are needed. This module:
|
| 8 |
+
|
| 9 |
+
1. computes the 3x3 neighbourhood (published bump weights phi) for every token;
|
| 10 |
+
2. keys each write by (sequence, z_x, z_y) and assigns it a RANK = how many
|
| 11 |
+
earlier writes landed on the same cell;
|
| 12 |
+
3. runs max_rank+1 rounds; in round r every cell receives exactly one write,
|
| 13 |
+
so the round is one batched gather/matmul/scatter;
|
| 14 |
+
4. schedules each read into the round where its cell reaches the required
|
| 15 |
+
rank, accumulating its phi-weighted contribution.
|
| 16 |
+
|
| 17 |
+
Cell count is the number of distinct addresses (no dense grid, no cap); the
|
| 18 |
+
number of dispatch rounds is max writes per cell, not the sequence length.
|
| 19 |
+
Equivalence with mulattice.sparse_scan.SparseLatticeScan is asserted in
|
| 20 |
+
tests/test_kernel.py (max abs diff 8.9e-16 in float64, 16 configurations).
|
| 21 |
+
NOTE: the rounds counter is max writes per (sequence, cell), which is <= T; if you
|
| 22 |
+
see rounds > T the host's argsort/cummax is not honouring `stable=True` (observed
|
| 23 |
+
on one MPS run) and the result must not be trusted.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from .kernel import MAX_CELLS_PER_TOKEN, phi_2d
|
| 31 |
+
from .sparse_scan import compact_ids as _compact_ids
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _encode(coords: torch.Tensor, n_seq: int, size: int = 1 << 20) -> torch.Tensor:
|
| 35 |
+
"""coords (B,T,9,2) int64 -> (B,T,9) collision-free int64 keys."""
|
| 36 |
+
z = coords + (size // 2)
|
| 37 |
+
b = torch.arange(n_seq, device=coords.device, dtype=torch.int64).view(n_seq, 1, 1)
|
| 38 |
+
return (b * (size * size)) + z[..., 0] * size + z[..., 1]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CellParallelScan(torch.nn.Module):
|
| 42 |
+
def __init__(self, d_k: int, d_v: int, n_heads: int, size: int = 1 << 20,
|
| 43 |
+
weighted_write: bool = True):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.d_k, self.d_v, self.n_heads, self.size = d_k, d_v, n_heads, size
|
| 46 |
+
self.weighted_write = weighted_write
|
| 47 |
+
self.last_rounds = 0
|
| 48 |
+
self.last_n_cells = 0
|
| 49 |
+
|
| 50 |
+
def forward(
|
| 51 |
+
self,
|
| 52 |
+
q_addr: torch.Tensor, # (B,T,2) query address (read) -- same order
|
| 53 |
+
k_addr: torch.Tensor, # (B,T,2) key address (write) -- as SparseLatticeScan
|
| 54 |
+
q2: torch.Tensor, # (B,T,H,d_k)
|
| 55 |
+
kappa: torch.Tensor, # (B,T,H,d_k)
|
| 56 |
+
v: torch.Tensor, # (B,T,H,d_v)
|
| 57 |
+
alpha: torch.Tensor, # (B,T,H,1)
|
| 58 |
+
beta: torch.Tensor, # (B,T,H,1)
|
| 59 |
+
read_mode: str = "all", # "all" | "none"
|
| 60 |
+
):
|
| 61 |
+
"""For every token t: write into its 3x3 cells, then read them.
|
| 62 |
+
|
| 63 |
+
Semantics are identical to the token-sequential reference; only the
|
| 64 |
+
execution order changes.
|
| 65 |
+
"""
|
| 66 |
+
B, T, H = kappa.shape[0], kappa.shape[1], self.n_heads
|
| 67 |
+
dev, dt = kappa.device, kappa.dtype
|
| 68 |
+
M = MAX_CELLS_PER_TOKEN
|
| 69 |
+
|
| 70 |
+
wk, zk = phi_2d(k_addr.reshape(-1, 2))
|
| 71 |
+
wq, zq = phi_2d(q_addr.reshape(-1, 2))
|
| 72 |
+
wk = wk.reshape(B, T, M)
|
| 73 |
+
wq = wq.reshape(B, T, M)
|
| 74 |
+
zk = zk.reshape(B, T, M, 2)
|
| 75 |
+
zq = zq.reshape(B, T, M, 2)
|
| 76 |
+
|
| 77 |
+
keys_w = _encode(zk, B, self.size).reshape(-1) # (B*T*M,)
|
| 78 |
+
keys_q = _encode(zq, B, self.size).reshape(-1)
|
| 79 |
+
inv, n_cells = _compact_ids(torch.cat([keys_w, keys_q]))
|
| 80 |
+
self.last_n_cells = int(n_cells)
|
| 81 |
+
inv_w = inv[: keys_w.numel()].reshape(B, T, M)
|
| 82 |
+
inv_q = inv[keys_w.numel():].reshape(B, T, M)
|
| 83 |
+
cells = torch.zeros(n_cells, H, self.d_v, self.d_k, device=dev, dtype=dt)
|
| 84 |
+
|
| 85 |
+
# ---- write events, ordered by (cell, time) -------------------------
|
| 86 |
+
cw = inv_w.reshape(-1) # cell id
|
| 87 |
+
tw = (torch.arange(B * T, device=dev).view(B, T, 1)
|
| 88 |
+
.expand(B, T, M).reshape(-1) % T) # time within sequence
|
| 89 |
+
order_w = torch.argsort(cw * (T + 1) + tw, stable=True)
|
| 90 |
+
cw_s, tw_s = cw[order_w], tw[order_w]
|
| 91 |
+
first = torch.ones_like(cw_s, dtype=torch.bool)
|
| 92 |
+
first[1:] = cw_s[1:] != cw_s[:-1]
|
| 93 |
+
ar = torch.arange(cw_s.numel(), device=dev)
|
| 94 |
+
run_start = torch.cummax(torch.where(first, ar, torch.zeros_like(ar)), 0).values
|
| 95 |
+
rank = ar - run_start
|
| 96 |
+
max_rank = int(rank.max()) if rank.numel() else -1
|
| 97 |
+
self.last_rounds = max_rank + 1
|
| 98 |
+
# index of the first write of each cell in the sorted write array
|
| 99 |
+
cell_start = torch.full((n_cells,), cw_s.numel(), device=dev, dtype=torch.int64)
|
| 100 |
+
cell_start[cw_s[first]] = ar[first]
|
| 101 |
+
|
| 102 |
+
row_w = (order_w // M) # (b,t) row of the write
|
| 103 |
+
kf = kappa.reshape(B * T, H, self.d_k)[row_w]
|
| 104 |
+
vf = v.reshape(B * T, H, self.d_v)[row_w]
|
| 105 |
+
af = alpha.reshape(B * T, H, 1)[row_w]
|
| 106 |
+
bf = beta.reshape(B * T, H, 1)[row_w]
|
| 107 |
+
# per-write bump weight, in the same (cell, time) order as the writes
|
| 108 |
+
wphi = wk.reshape(-1)[order_w].unsqueeze(-1) if self.weighted_write else None
|
| 109 |
+
|
| 110 |
+
# ---- read events: rank of the cell at the moment of the read --------
|
| 111 |
+
acc = None
|
| 112 |
+
if read_mode == "all":
|
| 113 |
+
cq = inv_q.reshape(-1)
|
| 114 |
+
tq = tw
|
| 115 |
+
wkeys_sorted = cw * (T + 1) + tw
|
| 116 |
+
wkeys_sorted = wkeys_sorted[order_w] # sorted write keys
|
| 117 |
+
rkeys = cq * (T + 1) + tq
|
| 118 |
+
# writes to THIS cell with key <= read key == writes to this cell with
|
| 119 |
+
# time <= t. Restricting to the cell's contiguous run is essential:
|
| 120 |
+
# a plain searchsorted would also count writes to lower-id cells.
|
| 121 |
+
need = torch.searchsorted(wkeys_sorted, rkeys, right=True) - cell_start[cq]
|
| 122 |
+
need = need.clamp_(min=0)
|
| 123 |
+
phi_q = wq.reshape(-1)
|
| 124 |
+
row_q = torch.arange(B * T, device=dev).repeat_interleave(M)
|
| 125 |
+
# cell index WITHIN a token (0..M-1). Each (row, cell) pair is unique, so
|
| 126 |
+
# accumulating into a (B*T, M, H, dv) tensor with index_put_ is deterministic
|
| 127 |
+
# -- unlike index_add_ over duplicate rows, whose CUDA accumulation order is
|
| 128 |
+
# unspecified and makes training non-reproducible across runs.
|
| 129 |
+
cell_i = torch.arange(M, device=dev).repeat(B * T)
|
| 130 |
+
acc = torch.zeros(B * T, M, H, self.d_v, device=dev, dtype=dt)
|
| 131 |
+
qflat = q2.reshape(B * T, H, self.d_k)
|
| 132 |
+
|
| 133 |
+
# ---- rounds --------------------------------------------------------
|
| 134 |
+
for r in range(max_rank + 1):
|
| 135 |
+
sel = rank == r
|
| 136 |
+
idx = cw_s[sel]
|
| 137 |
+
W = cells.index_select(0, idx)
|
| 138 |
+
a, b, kap = af[sel], bf[sel], kf[sel]
|
| 139 |
+
if wphi is not None:
|
| 140 |
+
b = b * wphi[sel].unsqueeze(-1)
|
| 141 |
+
v_bar = a * (W @ kap.unsqueeze(-1)).squeeze(-1)
|
| 142 |
+
r_vec = vf[sel] - v_bar
|
| 143 |
+
W = a.unsqueeze(-1) * W + b.unsqueeze(-1) * (
|
| 144 |
+
r_vec.unsqueeze(-1) * kap.unsqueeze(-2))
|
| 145 |
+
# FUNCTIONAL (out-of-place) update. The in-place index_put_ chained across
|
| 146 |
+
# rounds with interleaved index_select reads corrupted the autograd graph:
|
| 147 |
+
# forward matched the token-loop to ~1e-16 but backward diverged by O(1),
|
| 148 |
+
# which broke every fastscan-trained model (caught by
|
| 149 |
+
# tests/test_kernel.py::test_fastscan_gradient_matches_sparse). Out-of-place
|
| 150 |
+
# index_put creates a proper graph node per round, so the sequential-recurrence
|
| 151 |
+
# gradient flows correctly. idx is unique within a round (one write per cell
|
| 152 |
+
# per rank), so the scatter semantics are well defined.
|
| 153 |
+
cells = cells.index_put((idx,), W)
|
| 154 |
+
if read_mode == "all":
|
| 155 |
+
take = need == (r + 1) # state after exactly r+1 writes
|
| 156 |
+
if take.any():
|
| 157 |
+
c_idx = cq[take]
|
| 158 |
+
rows = row_q[take]
|
| 159 |
+
ci = cell_i[take]
|
| 160 |
+
Wr = cells.index_select(0, c_idx)
|
| 161 |
+
out = (Wr @ qflat[rows].unsqueeze(-1)).squeeze(-1)
|
| 162 |
+
acc.index_put_((rows, ci), phi_q[take].unsqueeze(-1).unsqueeze(-1) * out)
|
| 163 |
+
|
| 164 |
+
if read_mode == "all":
|
| 165 |
+
# A read whose cells were never written contributes nothing, which is
|
| 166 |
+
# correct -- but if NO read in the batch hits a written cell, `acc`
|
| 167 |
+
# would stay a plain zeros tensor with no graph, and backward() would
|
| 168 |
+
# fail. This zero-valued term keeps the read path connected.
|
| 169 |
+
acc = acc.sum(dim=1) + qflat.sum() * 0.0
|
| 170 |
+
return acc.reshape(B, T, H, self.d_v), n_cells
|
| 171 |
+
return None, n_cells
|
src/mulattice/kernel.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
μLattice -- bump kernel and 2D lattice weighting.
|
| 3 |
+
|
| 4 |
+
The bump kernel and 2D lattice weighting:
|
| 5 |
+
|
| 6 |
+
b(t) = cos^2(pi t / 3) for |t| < 3/2 , 0 otherwise [bump, support 1.5]
|
| 7 |
+
phi_z(x) = b(x - z) / sqrt( sum_j b(x - j)^2 ) [normalized weights]
|
| 8 |
+
D_1(q,k) = sum_z phi_z(q) phi_z(k) [1D kernel]
|
| 9 |
+
D(q,k) = D_1(q_x,k_x) * D_1(q_y,k_y) [2D product kernel]
|
| 10 |
+
|
| 11 |
+
Consequences that the recipe elevates to invariants:
|
| 12 |
+
|
| 13 |
+
* |t| < 3/2 means an axis coordinate touches AT MOST THREE integers,
|
| 14 |
+
so a token touches at most 3 x 3 = 9 lattice cells. Never more.
|
| 15 |
+
* sum_z phi_z(x)^2 == 1 exactly (L2 partition of unity), and the same
|
| 16 |
+
holds for the 2D product weights, so D(q,q) == 1.
|
| 17 |
+
* Cell fan-out is 3^d for lattice dimension d. d = 2 -> 9.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
# Support per bump variant. The BLOG publishes cos^2(pi t / 3) with |t| < 3/2.
|
| 27 |
+
# The reference implementation uses
|
| 28 |
+
# cos^2(pi t / 2) with |t| < 1 instead: a narrower bump, at most TWO nonzero cells
|
| 29 |
+
# per axis (<=4 in 2D), and exactly ONE when the coordinate is integral.
|
| 30 |
+
BUMP_SUPPORT_BY_KIND = {"cos2": 1.5, "shelf": 1.5, "cos2_half": 1.0}
|
| 31 |
+
BUMP_SUPPORT = 1.5
|
| 32 |
+
LATTICE_DIM = 2
|
| 33 |
+
MAX_CELLS_PER_TOKEN = 3 ** LATTICE_DIM # published: 9
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def bump(t: torch.Tensor, kind: str = "cos2") -> torch.Tensor:
|
| 37 |
+
"""Bump function on |t| < 3/2, else 0.
|
| 38 |
+
|
| 39 |
+
Two variants are published (the second one is the one in the released
|
| 40 |
+
reference figure code):
|
| 41 |
+
|
| 42 |
+
"cos2" b(t) = cos^2(pi t / 3) [blog equation]
|
| 43 |
+
"cos2_half" b(t) = cos^2(pi t / 2), |t| < 1 [what the released reference C
|
| 44 |
+
actually uses; note the different support]
|
| 45 |
+
"shelf" b(t) = exp(-t^2/(2 s^2)) - exp(-2.25/(2 s^2)), s^2 = 0.72
|
| 46 |
+
(the subtractive term makes it exactly 0 at |t| = 3/2)
|
| 47 |
+
"""
|
| 48 |
+
if kind == "cos2":
|
| 49 |
+
inside = t.abs() < BUMP_SUPPORT_BY_KIND["cos2"]
|
| 50 |
+
return torch.where(inside, torch.cos(math.pi * t / 3.0) ** 2, torch.zeros_like(t))
|
| 51 |
+
if kind == "cos2_half":
|
| 52 |
+
inside = t.abs() < BUMP_SUPPORT_BY_KIND["cos2_half"]
|
| 53 |
+
return torch.where(inside, torch.cos(math.pi * t / 2.0) ** 2, torch.zeros_like(t))
|
| 54 |
+
if kind == "shelf":
|
| 55 |
+
s2 = 0.72
|
| 56 |
+
b = torch.exp(-(t * t) / (2 * s2)) - math.exp(-2.25 / (2 * s2))
|
| 57 |
+
return torch.where(t.abs() < BUMP_SUPPORT_BY_KIND["shelf"], b, torch.zeros_like(t))
|
| 58 |
+
raise ValueError(f"unknown bump kind {kind!r}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def touched_cells(x: torch.Tensor, kind: str = "cos2") -> torch.Tensor:
|
| 62 |
+
"""Integer cells an axis-coordinate x can touch, shape (..., 3).
|
| 63 |
+
|
| 64 |
+
|x - z| < 3/2 <=> z in (x - 3/2, x + 3/2), an open interval of length 3,
|
| 65 |
+
which contains at most 3 integers: ceil(x - 3/2), ..., floor(x + 3/2).
|
| 66 |
+
Both candidate ends are returned; the kernel value is 0 (not
|
| 67 |
+
merely small) at |t| == 3/2, so no tolerance is required.
|
| 68 |
+
"""
|
| 69 |
+
lo = torch.ceil(x - BUMP_SUPPORT_BY_KIND.get(kind, BUMP_SUPPORT)).to(torch.int64)
|
| 70 |
+
return lo.unsqueeze(-1) + torch.arange(3, device=x.device, dtype=torch.int64)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def phi_1d(x: torch.Tensor, kind: str = "cos2") -> tuple[torch.Tensor, torch.Tensor]:
|
| 74 |
+
"""Normalized 1D weights. Returns (weights (...,3), cell coords (...,3)).
|
| 75 |
+
|
| 76 |
+
phi_z(x) = b(x - z) / sqrt(sum_j b(x - j)^2)
|
| 77 |
+
"""
|
| 78 |
+
z = touched_cells(x, kind) # (...,3)
|
| 79 |
+
b = bump(x.unsqueeze(-1) - z.to(x.dtype), kind) # (...,3)
|
| 80 |
+
denom = torch.sqrt((b * b).sum(dim=-1, keepdim=True)).clamp_min(1e-30)
|
| 81 |
+
return b / denom, z
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def phi_2d(xy: torch.Tensor, kind: str = "cos2") -> tuple[torch.Tensor, torch.Tensor]:
|
| 85 |
+
"""Normalized 2D weights over the 3x3 neighborhood.
|
| 86 |
+
|
| 87 |
+
xy : (..., 2) real-valued address (q or k)
|
| 88 |
+
returns weights (..., 3, 3) and integer coords (..., 3, 3, 2)
|
| 89 |
+
|
| 90 |
+
Product form: phi_(zx,zy)(x,y) = phi_zx(x) * phi_zy(y), so
|
| 91 |
+
sum over the 9 cells of phi^2 == 1.
|
| 92 |
+
"""
|
| 93 |
+
wx, zx = phi_1d(xy[..., 0], kind) # (...,3)
|
| 94 |
+
wy, zy = phi_1d(xy[..., 1], kind)
|
| 95 |
+
w = wx.unsqueeze(-1) * wy.unsqueeze(-2) # (...,3,3)
|
| 96 |
+
cz = torch.stack(
|
| 97 |
+
torch.broadcast_tensors(zx.unsqueeze(-1), zy.unsqueeze(-2)), dim=-1
|
| 98 |
+
) # (...,3,3,2)
|
| 99 |
+
return w, cz
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def D_1(q: torch.Tensor, k: torch.Tensor, kind: str = "cos2") -> torch.Tensor:
|
| 103 |
+
"""Published 1D kernel D_1(q,k) = sum_z phi_z(q) phi_z(k).
|
| 104 |
+
|
| 105 |
+
Evaluated in closed form (Zhuoran Yang / random-feature identity for the
|
| 106 |
+
raised-cosine bump) by summing over the union of the two touch sets; the
|
| 107 |
+
form below is the definition, kept literal for auditability.
|
| 108 |
+
"""
|
| 109 |
+
wq, zq = phi_1d(q, kind) # (...,3), (...,3)
|
| 110 |
+
# Sum runs only over cells where both weights are nonzero. Every such
|
| 111 |
+
# cell is in touch(q) (3 candidates), and phi_z(k) for an arbitrary z is
|
| 112 |
+
# b(k - z) / norm_k with norm_k taken over touch(k) -- the definition,
|
| 113 |
+
# since b(k - z) = 0 for every z outside touch(k).
|
| 114 |
+
zk = touched_cells(k, kind) # (...,3)
|
| 115 |
+
norm_k = (bump(k.unsqueeze(-1) - zk.to(k.dtype), kind) ** 2).sum(-1, keepdim=True).sqrt().clamp_min(1e-30)
|
| 116 |
+
phi_k_at_zq = bump(k.unsqueeze(-1) - zq.to(k.dtype), kind) / norm_k
|
| 117 |
+
return (wq * phi_k_at_zq).sum(dim=-1)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def D_2(q: torch.Tensor, k: torch.Tensor, kind: str = "cos2") -> torch.Tensor:
|
| 121 |
+
"""Published 2D kernel: D(q,k) = D_1(qx,kx) * D_1(qy,ky)."""
|
| 122 |
+
return D_1(q[..., 0], k[..., 0], kind) * D_1(q[..., 1], k[..., 1], kind)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def mix_read(cell_values: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
|
| 126 |
+
"""Mix per-cell reads by the bump weights.
|
| 127 |
+
|
| 128 |
+
cell_values : (..., 3, 3, d_v) read from each touched cell
|
| 129 |
+
weights : (..., 3, 3) normalized bump weights phi
|
| 130 |
+
returns (..., d_v)
|
| 131 |
+
"""
|
| 132 |
+
return (weights.unsqueeze(-1) * cell_values).sum(dim=(-3, -2))
|
src/mulattice/lattice.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
μLattice -- growing 2D lattice of fixed-size recurrent cells.
|
| 3 |
+
|
| 4 |
+
Published (Percepta blogs):
|
| 5 |
+
* the lattice is a 2D grid of cells; a token writes/reads only its 3x3
|
| 6 |
+
neighborhood; routing (2D address) is separated from content;
|
| 7 |
+
* each cell is one DeltaNet state per head, allocated on first write,
|
| 8 |
+
updated by later keys that land on it, all cells sharing one projection
|
| 9 |
+
and one update rule;
|
| 10 |
+
* "work per token does not grow" -- access cost is constant in stored
|
| 11 |
+
information.
|
| 12 |
+
|
| 13 |
+
CHOICE (not specified by the blogs, required to implement):
|
| 14 |
+
* the concrete gated delta rule (Yang et al. 2024) -- gated delta product:
|
| 15 |
+
v_bar = alpha * W_c kappa
|
| 16 |
+
r = v - v_bar
|
| 17 |
+
W_c <- alpha * W_c + beta * r (x) kappa
|
| 18 |
+
* storage as a hash map keyed by integer lattice coordinate (z_x, z_y);
|
| 19 |
+
dense grids are forbidden by the recipe (memory must grow with distinct
|
| 20 |
+
addresses only).
|
| 21 |
+
|
| 22 |
+
Layout note: W_c in R^{d_v x d_k} so that read(W_c, q) = W_c q in R^{d_v}.
|
| 23 |
+
The recipe writes "d_k x d_v"; the transpose is fixed here for consistency
|
| 24 |
+
with the read/write equations it gives.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
from dataclasses import dataclass, field
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
from .kernel import MAX_CELLS_PER_TOKEN, phi_2d
|
| 34 |
+
|
| 35 |
+
__all__ = ["LatticeMemory", "LatticeStats"]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class LatticeStats:
|
| 40 |
+
"""Bookkeeping for the invariants the recipe says must hold."""
|
| 41 |
+
|
| 42 |
+
writes: int = 0
|
| 43 |
+
reads: int = 0
|
| 44 |
+
max_fanout: int = 0
|
| 45 |
+
fanout_hist: dict = field(default_factory=dict)
|
| 46 |
+
touched_cell_ops: int = 0
|
| 47 |
+
stored_tokens: int = 0
|
| 48 |
+
reuses: int = 0
|
| 49 |
+
|
| 50 |
+
def record_fanout(self, n: int) -> None:
|
| 51 |
+
self.max_fanout = max(self.max_fanout, n)
|
| 52 |
+
self.fanout_hist[n] = self.fanout_hist.get(n, 0) + 1
|
| 53 |
+
|
| 54 |
+
def as_dict(self) -> dict:
|
| 55 |
+
d = dict(self.__dict__)
|
| 56 |
+
d["fanout_hist"] = {int(k): int(v) for k, v in self.fanout_hist.items()}
|
| 57 |
+
return d
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class LatticeMemory(torch.nn.Module):
|
| 61 |
+
"""Growing hash-map lattice of gated-DeltaNet cells.
|
| 62 |
+
|
| 63 |
+
Parameters
|
| 64 |
+
----------
|
| 65 |
+
d_k : content key/query dim inside a cell
|
| 66 |
+
d_v : value dim inside a cell
|
| 67 |
+
n_heads : independent cell states per lattice coordinate
|
| 68 |
+
device, dtype : where cell tensors live
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
d_k: int = 64,
|
| 74 |
+
d_v: int = 128,
|
| 75 |
+
n_heads: int = 1,
|
| 76 |
+
device=None,
|
| 77 |
+
dtype=torch.float32,
|
| 78 |
+
weighted_write: bool = True,
|
| 79 |
+
):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.d_k, self.d_v, self.n_heads = d_k, d_v, n_heads
|
| 82 |
+
self.device, self.dtype = device, dtype
|
| 83 |
+
self.weighted_write = weighted_write
|
| 84 |
+
self.cells: dict[tuple[int, int], torch.Tensor] = {}
|
| 85 |
+
self.stats = LatticeStats()
|
| 86 |
+
|
| 87 |
+
# ---------------------------------------------------------------- basics
|
| 88 |
+
def __len__(self) -> int:
|
| 89 |
+
"""Number of allocated cells == size of the growing memory."""
|
| 90 |
+
return len(self.cells)
|
| 91 |
+
|
| 92 |
+
def to_device(self, device) -> "LatticeMemory":
|
| 93 |
+
"""Move every stored cell to `device` (the hash map is not a submodule)."""
|
| 94 |
+
self.device = device
|
| 95 |
+
for k, t in self.cells.items():
|
| 96 |
+
self.cells[k] = t.to(device)
|
| 97 |
+
return self
|
| 98 |
+
|
| 99 |
+
def nbytes(self) -> int:
|
| 100 |
+
return sum(t.numel() * t.element_size() for t in self.cells.values())
|
| 101 |
+
|
| 102 |
+
def _alloc(self, z: tuple[int, int]) -> torch.Tensor:
|
| 103 |
+
"""Allocate a cell on first write (published: allocated on first write)."""
|
| 104 |
+
t = torch.zeros(self.n_heads, self.d_v, self.d_k, device=self.device, dtype=self.dtype)
|
| 105 |
+
self.cells[z] = t
|
| 106 |
+
return t
|
| 107 |
+
|
| 108 |
+
# ------------------------------------------------------------ read/write
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def write(
|
| 111 |
+
self,
|
| 112 |
+
addr: torch.Tensor, # (..., 2) real address
|
| 113 |
+
kappa: torch.Tensor, # (..., H, d_k) content key
|
| 114 |
+
v: torch.Tensor, # (..., H, d_v) value
|
| 115 |
+
alpha: torch.Tensor, # (..., H, 1) decay in (0,1)
|
| 116 |
+
beta: torch.Tensor, # (..., H, 1) write gate in (0,1)
|
| 117 |
+
) -> None:
|
| 118 |
+
"""Delta-rule write into the 3x3 neighborhood of each address."""
|
| 119 |
+
phi, zs = phi_2d(addr) # (...,3,3), (...,3,3,2)
|
| 120 |
+
lead = phi.shape[:-2]
|
| 121 |
+
coords = zs.reshape(-1, MAX_CELLS_PER_TOKEN, 2).cpu().tolist()
|
| 122 |
+
flat_phi = phi.reshape(-1, MAX_CELLS_PER_TOKEN)
|
| 123 |
+
kf = kappa.reshape(-1, self.n_heads, self.d_k)
|
| 124 |
+
vf = v.reshape(-1, self.n_heads, self.d_v)
|
| 125 |
+
af = alpha.reshape(-1, self.n_heads, 1)
|
| 126 |
+
bf = beta.reshape(-1, self.n_heads, 1)
|
| 127 |
+
|
| 128 |
+
for i, row in enumerate(coords):
|
| 129 |
+
a, b, kap, val = af[i], bf[i], kf[i], vf[i]
|
| 130 |
+
for j, z in enumerate(row):
|
| 131 |
+
key = (int(z[0]), int(z[1]))
|
| 132 |
+
w = self.cells.get(key)
|
| 133 |
+
if w is None:
|
| 134 |
+
w = self._alloc(key)
|
| 135 |
+
else:
|
| 136 |
+
self.stats.reuses += 1
|
| 137 |
+
v_bar = a * (w @ kap.unsqueeze(-1)).squeeze(-1) # (H, d_v)
|
| 138 |
+
r = val - v_bar
|
| 139 |
+
gate = b * flat_phi[i, j] if self.weighted_write else b
|
| 140 |
+
w.mul_(a.unsqueeze(-1))
|
| 141 |
+
w.add_(gate.unsqueeze(-1) * (r.unsqueeze(-1) * kap.unsqueeze(-2)))
|
| 142 |
+
self.stats.stored_tokens += 1
|
| 143 |
+
self.stats.writes += 1
|
| 144 |
+
# real fan-out: number of cells the token actually wrote (phi > 0)
|
| 145 |
+
live = int((flat_phi.abs() > 0).sum(-1).max())
|
| 146 |
+
self.stats.record_fanout(live)
|
| 147 |
+
|
| 148 |
+
# ------------------------------------------- direct (single-cell) access
|
| 149 |
+
# The bump read above is an INTERPOLATING read: it mixes the 3x3
|
| 150 |
+
# neighbourhood, so it cannot return one stored payload exactly. A reserved
|
| 151 |
+
# region that must reproduce source bytes needs addressing of one cell, which
|
| 152 |
+
# is what the published "a later turn reads that region by the same address"
|
| 153 |
+
# describes. Both paths share the same cell state and update rule.
|
| 154 |
+
@torch.no_grad()
|
| 155 |
+
def write_cell(self, z: tuple[int, int], kappa, v, alpha, beta) -> None:
|
| 156 |
+
kappa = kappa.reshape(self.n_heads, self.d_k)
|
| 157 |
+
v = v.reshape(self.n_heads, self.d_v)
|
| 158 |
+
alpha = alpha.reshape(self.n_heads, 1)
|
| 159 |
+
beta = beta.reshape(self.n_heads, 1)
|
| 160 |
+
w = self.cells.get(z)
|
| 161 |
+
if w is None:
|
| 162 |
+
w = self._alloc(z)
|
| 163 |
+
else:
|
| 164 |
+
self.stats.reuses += 1
|
| 165 |
+
v_bar = alpha * (w @ kappa.unsqueeze(-1)).squeeze(-1)
|
| 166 |
+
r = v - v_bar
|
| 167 |
+
w.mul_(alpha.unsqueeze(-1))
|
| 168 |
+
w.add_(beta.unsqueeze(-1) * (r.unsqueeze(-1) * kappa.unsqueeze(-2)))
|
| 169 |
+
self.stats.stored_tokens += 1
|
| 170 |
+
self.stats.writes += 1
|
| 171 |
+
self.stats.record_fanout(1)
|
| 172 |
+
|
| 173 |
+
@torch.no_grad()
|
| 174 |
+
def read_cell(self, z: tuple[int, int], q2):
|
| 175 |
+
q2 = q2.reshape(self.n_heads, self.d_k)
|
| 176 |
+
w = self.cells.get(z)
|
| 177 |
+
if w is None:
|
| 178 |
+
return torch.zeros(self.n_heads, self.d_v, device=q2.device, dtype=q2.dtype)
|
| 179 |
+
self.stats.reads += 1
|
| 180 |
+
return (w @ q2.unsqueeze(-1)).squeeze(-1)
|
| 181 |
+
|
| 182 |
+
@torch.no_grad()
|
| 183 |
+
def read(self, addr: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
|
| 184 |
+
"""Read: per-cell W_c q2, mixed across the 3x3 neighborhood by phi."""
|
| 185 |
+
phi, zs = phi_2d(addr)
|
| 186 |
+
lead = phi.shape[:-2]
|
| 187 |
+
flat_z = zs.reshape(-1, MAX_CELLS_PER_TOKEN, 2).cpu().tolist()
|
| 188 |
+
flat_phi = phi.reshape(-1, MAX_CELLS_PER_TOKEN).cpu()
|
| 189 |
+
qf = q2.reshape(-1, self.n_heads, self.d_k)
|
| 190 |
+
out = torch.zeros(qf.shape[0], self.n_heads, self.d_v, device=qf.device, dtype=qf.dtype)
|
| 191 |
+
for i, row in enumerate(flat_z):
|
| 192 |
+
acc = torch.zeros(self.n_heads, self.d_v, device=qf.device, dtype=qf.dtype)
|
| 193 |
+
for j, z in enumerate(row):
|
| 194 |
+
w = self.cells.get((int(z[0]), int(z[1])))
|
| 195 |
+
if w is None: # published: empty cells contribute nothing
|
| 196 |
+
continue
|
| 197 |
+
acc = acc + flat_phi[i, j] * (w @ qf[i].unsqueeze(-1)).squeeze(-1)
|
| 198 |
+
out[i] = acc
|
| 199 |
+
self.stats.reads += 1
|
| 200 |
+
return out.reshape(*lead, self.n_heads, self.d_v)
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------ persistence
|
| 203 |
+
def state_dict_lattice(self) -> dict:
|
| 204 |
+
return {
|
| 205 |
+
"d_k": self.d_k,
|
| 206 |
+
"d_v": self.d_v,
|
| 207 |
+
"n_heads": self.n_heads,
|
| 208 |
+
"cells": {f"{z[0]},{z[1]}": t.detach().cpu() for z, t in self.cells.items()},
|
| 209 |
+
"stats": self.stats.as_dict(),
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
def load_state_dict_lattice(self, sd: dict) -> None:
|
| 213 |
+
assert sd["d_k"] == self.d_k and sd["d_v"] == self.d_v and sd["n_heads"] == self.n_heads
|
| 214 |
+
self.cells = {
|
| 215 |
+
tuple(int(x) for x in k.split(",")): t.to(self.device, self.dtype)
|
| 216 |
+
for k, t in sd["cells"].items()
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
def save(self, path: str) -> None:
|
| 220 |
+
torch.save(self.state_dict_lattice(), path)
|
| 221 |
+
|
| 222 |
+
def load(self, path: str) -> None:
|
| 223 |
+
self.load_state_dict_lattice(torch.load(path, map_location="cpu", weights_only=False))
|
| 224 |
+
if self.device is not None:
|
| 225 |
+
self.to_device(self.device)
|
src/mulattice/models.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Synthetic mixers for the published MQAR evidence.
|
| 3 |
+
|
| 4 |
+
Structure follows the described synthetic setup: a tiny transformer
|
| 5 |
+
(d_model = 64, 2 heads, < 100K matrix parameters of "intelligence") whose
|
| 6 |
+
sequence mixer is swapped between
|
| 7 |
+
|
| 8 |
+
* μLattice -- growing 2D lattice of gated-DeltaNet cells
|
| 9 |
+
* Attention -- causal softmax attention, no positional encodings
|
| 10 |
+
* GatedDeltaNet -- ONE fixed-size state per head (cell count capped at 1:
|
| 11 |
+
the recipe's own failure rule calls this Gated DeltaNet,
|
| 12 |
+
not μLattice)
|
| 13 |
+
|
| 14 |
+
Published for the synthetic mixer: a short conv1d over q,k,v before the mixer.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
|
| 26 |
+
from .autoscan import AdaptiveScan
|
| 27 |
+
from .sparse_scan import SparseLatticeScan
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ShortConv(nn.Module):
|
| 31 |
+
"""Depthwise causal conv1d of width 4 (published: short conv1d on q,k,v)."""
|
| 32 |
+
|
| 33 |
+
def __init__(self, d: int, width: int = 4):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.width = width
|
| 36 |
+
self.conv = nn.Conv1d(d, d, width, groups=d)
|
| 37 |
+
# std = 1/sqrt(width) keeps the conv output at unit scale. A 0.02 init
|
| 38 |
+
# (the usual "small output layer" default) attenuates the signal ~50x, and
|
| 39 |
+
# because the address head reads the POST-conv activations that
|
| 40 |
+
# collapsed the address spread: 1.15 cells/token instead of ~9.
|
| 41 |
+
nn.init.normal_(self.conv.weight, std=1.0 / math.sqrt(width))
|
| 42 |
+
nn.init.zeros_(self.conv.bias)
|
| 43 |
+
|
| 44 |
+
def forward(self, x): # (B,T,d)
|
| 45 |
+
y = F.pad(x.transpose(1, 2), (self.width - 1, 0))
|
| 46 |
+
return self.conv(y).transpose(1, 2)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass
|
| 50 |
+
class MixerCfg:
|
| 51 |
+
d_model: int = 64
|
| 52 |
+
n_heads: int = 2
|
| 53 |
+
d_k: int = 32
|
| 54 |
+
d_v: int = 32
|
| 55 |
+
learn_addr_scale: bool = False # False = fixed scale (PROVEN to bootstrap; the learnable
|
| 56 |
+
# scale shrinks and collapses the lattice)
|
| 57 |
+
bound_address: bool = True # True = tanh-bounded address. Measured: the unbounded
|
| 58 |
+
# linear address (False) breaks routing -- key/query
|
| 59 |
+
# addresses drift apart and held-out stays 0.000.
|
| 60 |
+
addr_scale: float = 8.0 # fixed address scale (tanh radius)
|
| 61 |
+
read_tie: bool = False # addr_q = addr_k.detach() + Waq_delta(xc): the read is
|
| 62 |
+
# anchored to the cell the same token writes to (it cannot
|
| 63 |
+
# drift off the answer); the delta starts at ZERO so the
|
| 64 |
+
# read begins exactly on the write cell.
|
| 65 |
+
retention_init: float | None = None
|
| 66 |
+
# bias added to the alpha-gate so retention starts near 1.
|
| 67 |
+
# None = legacy (alpha~0.5), which KILLS credit beyond ~30
|
| 68 |
+
# steps (tests/test_kernel.py::test_credit_decay_...);
|
| 69 |
+
# 9.0 -> alpha0~0.999, credit survives 130+ steps.
|
| 70 |
+
conv: bool = True
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class MuLatticeMixer(nn.Module):
|
| 74 |
+
def __init__(self, cfg: MixerCfg):
|
| 75 |
+
super().__init__()
|
| 76 |
+
d, H, dk, dv = cfg.d_model, cfg.n_heads, cfg.d_k, cfg.d_v
|
| 77 |
+
self.cfg = cfg
|
| 78 |
+
self.conv = ShortConv(d) if cfg.conv else nn.Identity()
|
| 79 |
+
# (q1, k1) SPLIT -- required by the blog and by the released C, and missing
|
| 80 |
+
# from every earlier version of this file:
|
| 81 |
+
# "Keys write to a small neighborhood around their addresses, and queries
|
| 82 |
+
# read from a neighborhood around theirs."
|
| 83 |
+
# reference: phi(p[2h],..) is the WRITE address, phi(p[2H+2h],..) the READ
|
| 84 |
+
# address -- separate projections. Passing one address for both forces a
|
| 85 |
+
# token's read and write to the same cell, so at the answer position the
|
| 86 |
+
# separator overwrites the very value it is about to retrieve.
|
| 87 |
+
# NOTE: the address is SHARED across heads -- each cell holds one d_k x d_v
|
| 88 |
+
# DeltaNet state PER HEAD, as the blog states, so the cell (not the head) is the
|
| 89 |
+
# routing unit.
|
| 90 |
+
self.Wa = nn.Linear(d, 2) # k1: write address
|
| 91 |
+
self.Waq_addr = nn.Linear(d, 2) # q1: read address (untied path)
|
| 92 |
+
if cfg.read_tie:
|
| 93 |
+
self.Waq_delta = nn.Linear(d, 2)
|
| 94 |
+
nn.init.zeros_(self.Waq_delta.weight)
|
| 95 |
+
nn.init.zeros_(self.Waq_delta.bias)
|
| 96 |
+
self.Wq = nn.Linear(d, H * dk)
|
| 97 |
+
self.Wk = nn.Linear(d, H * dk)
|
| 98 |
+
self.Wv = nn.Linear(d, H * dv)
|
| 99 |
+
self.Wg = nn.Linear(d, 2 * H) # alpha, beta logits
|
| 100 |
+
if cfg.retention_init is not None:
|
| 101 |
+
# alpha for head h is Wg output feature h (view(B,T,2,H): gate*H + head);
|
| 102 |
+
# biasing only the alpha features leaves beta at its default init.
|
| 103 |
+
with torch.no_grad():
|
| 104 |
+
self.Wg.bias[0:H] += cfg.retention_init
|
| 105 |
+
self.Wo = nn.Linear(H * dv, d)
|
| 106 |
+
# NOT zero-init. With empty cells the read is zero, so a zero gate makes
|
| 107 |
+
# d(loss)/d(gate) = 0 and every mixer parameter is multiplied by a zero
|
| 108 |
+
# gate -- a deadlock: measured gates stuck at 0.002 after 1,200 steps and
|
| 109 |
+
# accuracy pinned at chance forever. A 1.0 init lets the mixer learn.
|
| 110 |
+
self.out_gate = nn.Parameter(torch.ones(1))
|
| 111 |
+
self.scan = AdaptiveScan(dk, dv, H)
|
| 112 |
+
nn.init.normal_(self.Wa.weight, std=1.0 / (cfg.d_model ** 0.5))
|
| 113 |
+
# CHOICE, and load-bearing: the address map. A tanh-bounded address
|
| 114 |
+
# (addr = scale*tanh(Wh)) confines coordinates to [-(scale+1), scale+1],
|
| 115 |
+
# i.e. a hard ceiling of (2*scale+3)^2 cells per sequence, and at init the
|
| 116 |
+
# addresses barely spread (+-1.3), so the partition is chaotic: CPU and MPS
|
| 117 |
+
# landed on 258 vs 19 cells for identical inputs, and the collapsed case
|
| 118 |
+
# overloads cells until gradients go inf. A linear address with a learned
|
| 119 |
+
# scale is unbounded and spreads from step 0.
|
| 120 |
+
self.addr_log_scale = nn.Parameter(
|
| 121 |
+
torch.full((2,), math.log(math.expm1(cfg.addr_scale))))
|
| 122 |
+
self.q_scale = nn.Parameter(torch.zeros(H)) # per-head softplus scale on q2
|
| 123 |
+
self.write_mask = None # optional (B,T,1,1) gate on writes, for diagnostics
|
| 124 |
+
# Address source: POST-conv (context-dependent). A pre-conv (token-identity)
|
| 125 |
+
# address was tested and REJECTED: the value token writes at its own cell, not
|
| 126 |
+
# the key's, breaking the value->key-cell induction (measured 0.000 held-out).
|
| 127 |
+
|
| 128 |
+
def forward(self, x, read_mode="all"):
|
| 129 |
+
B, T, _ = x.shape
|
| 130 |
+
H, dk, dv = self.cfg.n_heads, self.cfg.d_k, self.cfg.d_v
|
| 131 |
+
xc = self.conv(x)
|
| 132 |
+
if self.cfg.learn_addr_scale:
|
| 133 |
+
sc = F.softplus(self.addr_log_scale)
|
| 134 |
+
else:
|
| 135 |
+
sc = self.cfg.addr_scale
|
| 136 |
+
# (q1, k1) SPLIT: the write address k1 and the read address q1 are separate
|
| 137 |
+
# projections, as in the released C (phi(p[2h]) writes, phi(p[2H+2h]) reads).
|
| 138 |
+
# UNBOUNDED linear address (released C and the blog's "infinitely growing
|
| 139 |
+
# memory"): a tanh cap confines every key to (2*scale+1)^2 cells and makes
|
| 140 |
+
# the capacity claim impossible. The scale is learned (softplus), so it can
|
| 141 |
+
# grow when more distinct keys need more distinct cells.
|
| 142 |
+
if self.cfg.bound_address:
|
| 143 |
+
addr_k = sc * torch.tanh(self.Wa(xc))
|
| 144 |
+
addr_q = sc * torch.tanh(self.Waq_addr(xc)) if not self.cfg.read_tie \
|
| 145 |
+
else addr_k.detach() + self.Waq_delta(xc)
|
| 146 |
+
else:
|
| 147 |
+
addr_k = self.Wa(xc) * sc
|
| 148 |
+
addr_q = self.Waq_addr(xc) * sc if not self.cfg.read_tie \
|
| 149 |
+
else addr_k.detach() + self.Waq_delta(xc)
|
| 150 |
+
# CHOICE: L2-normalise the content key/query before the delta rule
|
| 151 |
+
# (standard in gated-delta implementations; keeps the recurrence bounded).
|
| 152 |
+
q2 = F.normalize(self.Wq(xc).view(B, T, H, dk), dim=-1) * F.softplus(self.q_scale).view(1, 1, H, 1)
|
| 153 |
+
kap = F.normalize(self.Wk(xc).view(B, T, H, dk), dim=-1)
|
| 154 |
+
v = self.Wv(xc).view(B, T, H, dv)
|
| 155 |
+
gates = self.Wg(xc).view(B, T, 2, H).permute(0, 1, 3, 2) # (B,T,H,2)
|
| 156 |
+
alpha = torch.sigmoid(gates[..., 0:1]) * 0.999 + 1e-4
|
| 157 |
+
beta = torch.sigmoid(gates[..., 1:2])
|
| 158 |
+
if self.write_mask is not None:
|
| 159 |
+
beta = beta * self.write_mask
|
| 160 |
+
out, n_cells = self.scan(addr_q, addr_k, q2, kap, v, alpha, beta, read_mode=read_mode)
|
| 161 |
+
self.n_cells = n_cells
|
| 162 |
+
y = self.Wo(out.reshape(B, T, H * dv))
|
| 163 |
+
return x + self.out_gate * y
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class AttentionMixer(nn.Module):
|
| 167 |
+
def __init__(self, cfg: MixerCfg):
|
| 168 |
+
super().__init__()
|
| 169 |
+
d, H = cfg.d_model, cfg.n_heads
|
| 170 |
+
self.cfg = cfg
|
| 171 |
+
self.conv = ShortConv(d) if cfg.conv else nn.Identity()
|
| 172 |
+
self.Wqkv = nn.Linear(d, 3 * d)
|
| 173 |
+
self.Wo = nn.Linear(d, d)
|
| 174 |
+
self.out_gate = nn.Parameter(torch.ones(1))
|
| 175 |
+
self.head_dim = d // H
|
| 176 |
+
|
| 177 |
+
def forward(self, x, read_mode="all"):
|
| 178 |
+
B, T, _ = x.shape
|
| 179 |
+
q, k, v = self.Wqkv(self.conv(x)).chunk(3, dim=-1)
|
| 180 |
+
q = q.view(B, T, self.cfg.n_heads, self.head_dim).transpose(1, 2)
|
| 181 |
+
k = k.view(B, T, self.cfg.n_heads, self.head_dim).transpose(1, 2)
|
| 182 |
+
v = v.view(B, T, self.cfg.n_heads, self.head_dim).transpose(1, 2)
|
| 183 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 184 |
+
y = y.transpose(1, 2).reshape(B, T, -1)
|
| 185 |
+
return x + self.out_gate * self.Wo(y)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class GatedDeltaNetMixer(nn.Module):
|
| 189 |
+
"""One state per head, fixed size -- no lattice, cell count capped at 1."""
|
| 190 |
+
|
| 191 |
+
def __init__(self, cfg: MixerCfg):
|
| 192 |
+
super().__init__()
|
| 193 |
+
d, H, dk, dv = cfg.d_model, cfg.n_heads, cfg.d_k, cfg.d_v
|
| 194 |
+
self.cfg = cfg
|
| 195 |
+
self.conv = ShortConv(d) if cfg.conv else nn.Identity()
|
| 196 |
+
self.Wq = nn.Linear(d, H * dk)
|
| 197 |
+
self.Wk = nn.Linear(d, H * dk)
|
| 198 |
+
self.Wv = nn.Linear(d, H * dv)
|
| 199 |
+
self.Wg = nn.Linear(d, 2 * H)
|
| 200 |
+
self.Wo = nn.Linear(H * dv, d)
|
| 201 |
+
self.out_gate = nn.Parameter(torch.ones(1))
|
| 202 |
+
|
| 203 |
+
def forward(self, x, read_mode="all"):
|
| 204 |
+
B, T, _ = x.shape
|
| 205 |
+
H, dk, dv = self.cfg.n_heads, self.cfg.d_k, self.cfg.d_v
|
| 206 |
+
xc = self.conv(x)
|
| 207 |
+
# unit-norm content keys: without this the delta rule's erase term is
|
| 208 |
+
# ||k||^2 ~ d_k times too strong and the state never accumulates
|
| 209 |
+
q = F.normalize(self.Wq(xc).view(B, T, H, dk), dim=-1)
|
| 210 |
+
k = F.normalize(self.Wk(xc).view(B, T, H, dk), dim=-1)
|
| 211 |
+
v = self.Wv(xc).view(B, T, H, dv)
|
| 212 |
+
g = self.Wg(xc).view(B, T, 2, H).permute(0, 1, 3, 2)
|
| 213 |
+
alpha = torch.sigmoid(g[..., 0:1]) * 0.999 + 1e-4
|
| 214 |
+
beta = torch.sigmoid(g[..., 1:2])
|
| 215 |
+
S = torch.zeros(B, H, dv, dk, device=x.device, dtype=x.dtype)
|
| 216 |
+
outs = []
|
| 217 |
+
for t in range(T):
|
| 218 |
+
v_bar = alpha[:, t] * (S @ k[:, t].unsqueeze(-1)).squeeze(-1)
|
| 219 |
+
r = v[:, t] - v_bar
|
| 220 |
+
S = alpha[:, t].unsqueeze(-1) * S + beta[:, t].unsqueeze(-1) * (
|
| 221 |
+
r.unsqueeze(-1) * k[:, t].unsqueeze(-2))
|
| 222 |
+
outs.append((S @ q[:, t].unsqueeze(-1)).squeeze(-1))
|
| 223 |
+
out = torch.stack(outs, 1) # (B,T,H,dv)
|
| 224 |
+
self.n_cells = 1
|
| 225 |
+
return x + self.out_gate * self.Wo(out.reshape(B, T, H * dv))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class SwiGLU(nn.Module):
|
| 229 |
+
def __init__(self, d: int, mult: int = 2):
|
| 230 |
+
super().__init__()
|
| 231 |
+
self.w1 = nn.Linear(d, mult * d, bias=False)
|
| 232 |
+
self.w2 = nn.Linear(d, mult * d, bias=False)
|
| 233 |
+
self.w3 = nn.Linear(mult * d, d, bias=False)
|
| 234 |
+
|
| 235 |
+
def forward(self, x):
|
| 236 |
+
return self.w3(F.silu(self.w1(x)) * self.w2(x))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class Block(nn.Module):
|
| 240 |
+
def __init__(self, d: int, mixer: nn.Module, mlp_mult: int = 2):
|
| 241 |
+
super().__init__()
|
| 242 |
+
self.n1 = nn.RMSNorm(d)
|
| 243 |
+
self.mixer = mixer
|
| 244 |
+
self.n2 = nn.RMSNorm(d)
|
| 245 |
+
self.mlp = SwiGLU(d, mlp_mult)
|
| 246 |
+
|
| 247 |
+
def forward(self, x, read_mode="all"):
|
| 248 |
+
x = self.mixer(self.n1(x), read_mode=read_mode)
|
| 249 |
+
return x + self.mlp(self.n2(x))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class MQARModel(nn.Module):
|
| 253 |
+
def __init__(self, vocab: int, kind: str = "mulattice", n_layers: int = 2,
|
| 254 |
+
cfg: MixerCfg | None = None, mlp_mult: int = 2):
|
| 255 |
+
super().__init__()
|
| 256 |
+
cfg = cfg or MixerCfg()
|
| 257 |
+
self.cfg = cfg
|
| 258 |
+
self.kind = kind
|
| 259 |
+
self.emb = nn.Embedding(vocab, cfg.d_model)
|
| 260 |
+
mixers = {
|
| 261 |
+
"mulattice": MuLatticeMixer,
|
| 262 |
+
"attention": AttentionMixer,
|
| 263 |
+
"gdn": GatedDeltaNetMixer,
|
| 264 |
+
}
|
| 265 |
+
self.blocks = nn.ModuleList(
|
| 266 |
+
[Block(cfg.d_model, mixers[kind](cfg), mlp_mult) for _ in range(n_layers)]
|
| 267 |
+
)
|
| 268 |
+
self.norm = nn.RMSNorm(cfg.d_model)
|
| 269 |
+
self.head = nn.Linear(cfg.d_model, vocab, bias=False)
|
| 270 |
+
self.n_cells = 0
|
| 271 |
+
|
| 272 |
+
def forward(self, tokens, read_mode="all"):
|
| 273 |
+
x = self.emb(tokens)
|
| 274 |
+
for b in self.blocks:
|
| 275 |
+
x = b(x, read_mode=read_mode)
|
| 276 |
+
return self.head(self.norm(x))
|
| 277 |
+
|
| 278 |
+
def mixer_params(self) -> int:
|
| 279 |
+
return sum(p.numel() for n, p in self.named_parameters() if ".mixer." in n)
|
| 280 |
+
|
| 281 |
+
def memory_cells(self) -> int:
|
| 282 |
+
return max(getattr(b.mixer, "n_cells", 0) for b in self.blocks)
|
src/mulattice/mqar.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MQAR (multi-query associative recall) data generator, Zoology-style.
|
| 2 |
+
|
| 3 |
+
A sequence is key_1 val_1 ... key_N val_N followed by a query block of Q
|
| 4 |
+
keys whose values must be recalled. Train with <=64 pairs, evaluate with the
|
| 5 |
+
same generator at a larger pair count (the published protocol: train <=64,
|
| 6 |
+
extrapolate to 256, and probe capacity/forgetting at 2^17).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def make_mqar_batch(
|
| 15 |
+
batch: int,
|
| 16 |
+
n_pairs: int,
|
| 17 |
+
n_queries: int,
|
| 18 |
+
n_keys: int,
|
| 19 |
+
n_values: int,
|
| 20 |
+
device="cpu",
|
| 21 |
+
generator: torch.Generator | None = None,
|
| 22 |
+
key_offset: int = 0,
|
| 23 |
+
) -> dict:
|
| 24 |
+
"""Returns dict with `tokens` (B, L) and `labels` (B, L) (-100 where ignored).
|
| 25 |
+
|
| 26 |
+
Keys are sampled WITHOUT replacement per sequence (the standard MQAR protocol):
|
| 27 |
+
every key in a sequence is distinct, so every query has a unique answer and the
|
| 28 |
+
achievable accuracy is 1.0. Sampling WITH replacement makes later keys collide --
|
| 29 |
+
at 256 pairs over 1024 keys ~30 keys repeat with different values, capping accuracy
|
| 30 |
+
at ~0.885, measuring the ambiguity ceiling instead of the architecture.
|
| 31 |
+
"""
|
| 32 |
+
g = generator
|
| 33 |
+
B = batch
|
| 34 |
+
if n_pairs > n_keys:
|
| 35 |
+
raise ValueError(f"n_pairs ({n_pairs}) must be <= n_keys ({n_keys}) to sample distinct keys")
|
| 36 |
+
keys = torch.stack([torch.randperm(n_keys, generator=g)[:n_pairs] for _ in range(B)])
|
| 37 |
+
keys = keys.to(device)
|
| 38 |
+
if n_pairs > n_values:
|
| 39 |
+
raise ValueError(f"n_pairs ({n_pairs}) must be <= n_values ({n_values}) to sample distinct values")
|
| 40 |
+
vals = torch.stack([torch.randperm(n_values, generator=g)[:n_pairs] for _ in range(B)])
|
| 41 |
+
vals = vals.to(device)
|
| 42 |
+
|
| 43 |
+
# query positions: distinct keys from the stored set (recall, not lookup-miss)
|
| 44 |
+
qpos = torch.randint(0, n_pairs, (B, n_queries), device=device, generator=g)
|
| 45 |
+
qkeys = torch.gather(keys, 1, qpos)
|
| 46 |
+
|
| 47 |
+
kv = torch.stack([keys + key_offset, vals + key_offset + n_keys], dim=-1).reshape(B, 2 * n_pairs)
|
| 48 |
+
qseq = torch.stack(
|
| 49 |
+
[qkeys + key_offset, torch.full_like(qkeys, n_keys + n_values + key_offset + 1)], dim=-1
|
| 50 |
+
).reshape(B, 2 * n_queries)
|
| 51 |
+
tokens = torch.cat([kv, qseq], dim=1)
|
| 52 |
+
|
| 53 |
+
labels = torch.full_like(tokens, -100)
|
| 54 |
+
ans_pos = 2 * n_pairs + torch.arange(1, 2 * n_queries, 2, device=device)
|
| 55 |
+
answers = torch.gather(vals, 1, qpos) + key_offset + n_keys
|
| 56 |
+
labels[:, ans_pos] = answers
|
| 57 |
+
return {"tokens": tokens, "labels": labels, "n_pairs": n_pairs, "answers": answers, "ans_pos": ans_pos}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def vocab_size(n_keys: int, n_values: int) -> int:
|
| 61 |
+
return n_keys + n_values + 2 # keys | values | separator
|
src/mulattice/protocol.py
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared evaluation/training protocol for the capacity, forgetting and real-data goals.
|
| 2 |
+
|
| 3 |
+
Single source of truth: the acceptance tests (tests/test_capacity.py,
|
| 4 |
+
tests/test_forgetting.py, tests/test_realtext.py) and the training scripts
|
| 5 |
+
(experiments/train_capacity.py, experiments/train_forgetting.py,
|
| 6 |
+
experiments/realdata_v2.py) all build sequences and measure accuracy through
|
| 7 |
+
this module, so "train until the test passes" cannot drift from what is tested.
|
| 8 |
+
|
| 9 |
+
Synthetic task (capacity + forgetting):
|
| 10 |
+
vocab keys [0, NK) values [NK, NK+NV) SEP = NK+NV+1 V = NK+NV+2
|
| 11 |
+
sequence per row (filler f tokens before each pair; f=0 -> dense MQAR):
|
| 12 |
+
[f k1 v1] [f k2 v2] ... [f kP vP] store pass
|
| 13 |
+
[f ku1 vu1'] ... [f kuM vuM'] update pass (overwrites)
|
| 14 |
+
[q1 SEP] [q2 SEP] ... [qQ SEP] query pass
|
| 15 |
+
A query on an updated key must return the UPDATED value (last write wins).
|
| 16 |
+
The answer is read at the SEP token of each query (causal).
|
| 17 |
+
|
| 18 |
+
Real-data task: wikitext-103 mined key->bigram-successor pairs embedded in a
|
| 19 |
+
real corpus filler stream (same mining as experiments/eval_realdata.py).
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import os
|
| 24 |
+
import time
|
| 25 |
+
from dataclasses import dataclass
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 30 |
+
ROOT = os.path.join(HERE, "..")
|
| 31 |
+
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
# synthetic generator
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class SynthCfg:
|
| 39 |
+
NK: int = 16384 # distinct key tokens available
|
| 40 |
+
NV: int = 16384 # distinct value tokens available
|
| 41 |
+
d_model: int = 64
|
| 42 |
+
n_heads: int = 2
|
| 43 |
+
d_k: int = 32
|
| 44 |
+
d_v: int = 32
|
| 45 |
+
addr_scale: float = 64.0 # (2*64+3)^2 = 17,161 cells for 8,192 keys
|
| 46 |
+
retention_init: float = 9.0
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def V(self) -> int:
|
| 50 |
+
return self.NK + self.NV + 2
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def SEP(self) -> int:
|
| 54 |
+
return self.NK + self.NV + 1
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def synth_batch(
|
| 58 |
+
B: int,
|
| 59 |
+
n_pairs: int,
|
| 60 |
+
n_queries: int,
|
| 61 |
+
cfg: SynthCfg,
|
| 62 |
+
filler: int = 0,
|
| 63 |
+
overwrite_frac: float = 0.0,
|
| 64 |
+
generator: torch.Generator | None = None,
|
| 65 |
+
qpos: torch.Tensor | None = None,
|
| 66 |
+
updated_idx: torch.Tensor | None = None,
|
| 67 |
+
kw: dict | None = None,
|
| 68 |
+
):
|
| 69 |
+
"""Build a capacity/forgetting batch. See module docstring for the layout.
|
| 70 |
+
|
| 71 |
+
Returns dict with:
|
| 72 |
+
tokens (B, L) long the sequence
|
| 73 |
+
ans_pos (B, Q) long SEP positions; answer read there
|
| 74 |
+
gold (B, Q) long value token id that must be produced
|
| 75 |
+
was_updated (B, Q) bool query key was overwritten -> updated gold
|
| 76 |
+
key_pos (B, P) long first-pass key token positions (spread loss)
|
| 77 |
+
upd_key_pos (B, M) long | None update-pass key token positions
|
| 78 |
+
n_pairs, n_upd, L
|
| 79 |
+
"""
|
| 80 |
+
g = generator
|
| 81 |
+
NK, NV = cfg.NK, cfg.NV
|
| 82 |
+
if n_pairs > NK:
|
| 83 |
+
raise ValueError("n_pairs > key vocab")
|
| 84 |
+
n_upd = int(round(n_pairs * overwrite_frac))
|
| 85 |
+
if n_pairs + n_upd > NV:
|
| 86 |
+
raise ValueError("not enough distinct values")
|
| 87 |
+
dev = "cpu" # build on CPU; caller moves to device
|
| 88 |
+
|
| 89 |
+
# distinct keys per row; `include_keys` are guaranteed members of the stored
|
| 90 |
+
# set (placed FIRST), and the rest are sampled from the complement, so the
|
| 91 |
+
# batch is consistent by construction -- no duplicate stores of the forced
|
| 92 |
+
# keys with conflicting values (the token-surgery approach produced exactly
|
| 93 |
+
# that and wrecked the model: census 9 -> 713 errors, polish_weakkeys v1).
|
| 94 |
+
include_keys = None
|
| 95 |
+
if "include_keys" in (kw or {}):
|
| 96 |
+
include_keys = kw["include_keys"]
|
| 97 |
+
if include_keys.dim() == 1:
|
| 98 |
+
include_keys = include_keys.unsqueeze(0).expand(B, -1)
|
| 99 |
+
if include_keys is not None:
|
| 100 |
+
nk_inc = include_keys.shape[1]
|
| 101 |
+
assert n_pairs >= nk_inc
|
| 102 |
+
rows = []
|
| 103 |
+
for r in range(B):
|
| 104 |
+
rest = torch.randperm(NK, generator=g)
|
| 105 |
+
rest = rest[torch.isin(rest, include_keys[r], invert=True)][: n_pairs - nk_inc]
|
| 106 |
+
rows.append(torch.cat([include_keys[r], rest]))
|
| 107 |
+
keys = torch.stack(rows)
|
| 108 |
+
else:
|
| 109 |
+
keys = torch.stack([torch.randperm(NK, generator=g)[:n_pairs] for _ in range(B)])
|
| 110 |
+
# distinct values: n_pairs originals + n_upd updates, all different in a row
|
| 111 |
+
vals = torch.stack([torch.randperm(NV, generator=g)[: n_pairs + n_upd] for _ in range(B)])
|
| 112 |
+
orig_vals, upd_vals = vals[:, :n_pairs], vals[:, n_pairs:]
|
| 113 |
+
|
| 114 |
+
if updated_idx is None:
|
| 115 |
+
# which stored keys get overwritten (row-specific)
|
| 116 |
+
updated_idx = torch.stack([torch.randperm(n_pairs, generator=g)[:n_upd] for _ in range(B)])
|
| 117 |
+
if qpos is None:
|
| 118 |
+
# DISTINCT query keys (sample without replacement). Sampling with
|
| 119 |
+
# replacement creates duplicate queries at large Q (measured: 9 of 512
|
| 120 |
+
# at Q=512/NK=16,384) -- not part of the published protocol semantics
|
| 121 |
+
# ("every query has a unique answer", mqar.py); distinct sampling is
|
| 122 |
+
# the clean generalization of the published small-Q generator.
|
| 123 |
+
qpos = torch.stack([torch.randperm(n_pairs, generator=g)[:n_queries] for _ in range(B)])
|
| 124 |
+
else:
|
| 125 |
+
if qpos.dim() == 1:
|
| 126 |
+
qpos = qpos.unsqueeze(0).expand(B, -1).contiguous()
|
| 127 |
+
n_queries = qpos.shape[1] # explicit query set defines Q
|
| 128 |
+
qkeys = torch.gather(keys, 1, qpos)
|
| 129 |
+
upd_mask = torch.zeros(B, n_pairs, dtype=torch.bool)
|
| 130 |
+
upd_mask.scatter_(1, updated_idx, True)
|
| 131 |
+
was_updated = torch.gather(upd_mask, 1, qpos)
|
| 132 |
+
# latest value for every stored key: original, replaced where updated
|
| 133 |
+
latest = orig_vals.clone()
|
| 134 |
+
latest.scatter_(1, updated_idx, upd_vals)
|
| 135 |
+
gold = torch.gather(latest, 1, qpos) + NK
|
| 136 |
+
|
| 137 |
+
f = filler
|
| 138 |
+
block = f + 2
|
| 139 |
+
L = (n_pairs + n_upd) * block + 2 * n_queries
|
| 140 |
+
|
| 141 |
+
tokens = torch.zeros(B, L, dtype=torch.long)
|
| 142 |
+
# filler ids: uniform from the complement of the row's stored keys
|
| 143 |
+
if f > 0:
|
| 144 |
+
need = f * (n_pairs + n_upd)
|
| 145 |
+
filler_ids = torch.zeros(B, need, dtype=torch.long)
|
| 146 |
+
keyset = torch.zeros(B, NK, dtype=torch.bool)
|
| 147 |
+
keyset.scatter_(1, keys, True)
|
| 148 |
+
done = torch.zeros(B, need, dtype=torch.bool)
|
| 149 |
+
while not bool(done.all()):
|
| 150 |
+
cand = torch.randint(0, NK, (B, need), generator=g)
|
| 151 |
+
ok = ~torch.gather(keyset, 1, cand) & ~done
|
| 152 |
+
filler_ids = torch.where(ok, cand, filler_ids)
|
| 153 |
+
done = done | ok
|
| 154 |
+
# store pass
|
| 155 |
+
for i in range(n_pairs):
|
| 156 |
+
s = i * block
|
| 157 |
+
if f:
|
| 158 |
+
tokens[:, s:s + f] = filler_ids[:, i * f:(i + 1) * f]
|
| 159 |
+
tokens[:, s + f] = keys[:, i]
|
| 160 |
+
tokens[:, s + f + 1] = orig_vals[:, i] + NK
|
| 161 |
+
# update pass: same key, new value, later in the sequence
|
| 162 |
+
upd_tokens = torch.gather(keys, 1, updated_idx)
|
| 163 |
+
for j in range(n_upd):
|
| 164 |
+
s = (n_pairs + j) * block
|
| 165 |
+
if f:
|
| 166 |
+
tokens[:, s:s + f] = filler_ids[:, (n_pairs + j) * f:(n_pairs + j + 1) * f]
|
| 167 |
+
tokens[:, s + f] = upd_tokens[:, j]
|
| 168 |
+
tokens[:, s + f + 1] = upd_vals[:, j] + NK
|
| 169 |
+
# query pass
|
| 170 |
+
S2 = (n_pairs + n_upd) * block
|
| 171 |
+
for q in range(n_queries):
|
| 172 |
+
tokens[:, S2 + 2 * q] = qkeys[:, q]
|
| 173 |
+
tokens[:, S2 + 2 * q + 1] = cfg.SEP
|
| 174 |
+
|
| 175 |
+
key_pos = (torch.arange(n_pairs) * block + f).unsqueeze(0).expand(B, -1).contiguous()
|
| 176 |
+
upd_key_pos = ((n_pairs + torch.arange(n_upd)) * block + f).unsqueeze(0).expand(B, -1).contiguous() \
|
| 177 |
+
if n_upd else None
|
| 178 |
+
ans_pos = (S2 + 2 * torch.arange(n_queries) + 1).unsqueeze(0).expand(B, -1).contiguous()
|
| 179 |
+
return {
|
| 180 |
+
"tokens": tokens, "ans_pos": ans_pos, "gold": gold, "was_updated": was_updated,
|
| 181 |
+
"key_pos": key_pos, "upd_key_pos": upd_key_pos, "n_pairs": n_pairs,
|
| 182 |
+
"n_upd": n_upd, "L": L,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ---------------------------------------------------------------------------
|
| 187 |
+
# model helpers
|
| 188 |
+
# ---------------------------------------------------------------------------
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def build_model(cfg: SynthCfg, n_layers: int = 1):
|
| 192 |
+
from mulattice.models import MQARModel, MixerCfg
|
| 193 |
+
mcfg = MixerCfg(d_model=cfg.d_model, n_heads=cfg.n_heads, d_k=cfg.d_k, d_v=cfg.d_v,
|
| 194 |
+
addr_scale=cfg.addr_scale, learn_addr_scale=False, bound_address=True,
|
| 195 |
+
read_tie=False, retention_init=cfg.retention_init)
|
| 196 |
+
return MQARModel(cfg.V, kind="mulattice", n_layers=n_layers, cfg=mcfg)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def logits_at(model, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
| 200 |
+
"""Forward the trunk, then apply the head ONLY at `positions` (B,Q).
|
| 201 |
+
|
| 202 |
+
Avoids materialising (B,T,V) logits; at T=131K with V=32,770 that is 17GB.
|
| 203 |
+
"""
|
| 204 |
+
x = model.emb(tokens)
|
| 205 |
+
for blk in model.blocks:
|
| 206 |
+
x = blk(x, read_mode="all")
|
| 207 |
+
x = model.norm(x)
|
| 208 |
+
B = x.shape[0]
|
| 209 |
+
h = x[torch.arange(B, device=x.device).unsqueeze(1), positions]
|
| 210 |
+
return model.head(h) # (B,Q,V)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@torch.no_grad()
|
| 214 |
+
def eval_batch(model, batch, device) -> dict:
|
| 215 |
+
"""Accuracy of `model` on a synth_batch, split by updated/untouched queries."""
|
| 216 |
+
model.eval()
|
| 217 |
+
pred = logits_at(model, batch["tokens"].to(device), batch["ans_pos"].to(device)).argmax(-1).cpu()
|
| 218 |
+
gold = batch["gold"]
|
| 219 |
+
ok = pred == gold
|
| 220 |
+
res = {"acc": ok.float().mean().item(), "n": ok.numel(),
|
| 221 |
+
"correct": int(ok.sum())}
|
| 222 |
+
up = batch["was_updated"]
|
| 223 |
+
if bool(up.any()):
|
| 224 |
+
res["acc_updated"] = ok[up].float().mean().item()
|
| 225 |
+
if bool((~up).any()):
|
| 226 |
+
res["acc_untouched"] = ok[~up].float().mean().item()
|
| 227 |
+
model.train()
|
| 228 |
+
return res
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def scan_info(model) -> str:
|
| 232 |
+
parts = []
|
| 233 |
+
for i, blk in enumerate(model.blocks):
|
| 234 |
+
sc = blk.mixer.scan
|
| 235 |
+
parts.append(f"L{i} cells={sc.last_n_cells} rounds={getattr(sc, 'last_rounds', '?')}"
|
| 236 |
+
f" path={getattr(sc, 'last_path', '?')}")
|
| 237 |
+
return " ".join(parts)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def force_fast_scan(model):
|
| 241 |
+
for blk in model.blocks:
|
| 242 |
+
blk.mixer.scan.crossover = 1e9
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def key_addresses(model, tokens, key_pos):
|
| 246 |
+
"""Write addresses (B,N,2) of the tokens at `key_pos` (B,N).
|
| 247 |
+
|
| 248 |
+
Uses the mixer's LIVE addr_scale (it can be ramped mid-run), not the
|
| 249 |
+
construction-time cfg value."""
|
| 250 |
+
mx = model.blocks[0].mixer
|
| 251 |
+
xc = mx.conv(model.blocks[0].n1(model.emb(tokens)))
|
| 252 |
+
kaddr = mx.cfg.addr_scale * torch.tanh(mx.Wa(xc))
|
| 253 |
+
ar = torch.arange(tokens.shape[0], device=tokens.device).unsqueeze(1)
|
| 254 |
+
return kaddr[ar, key_pos]
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def spread_loss(model, tokens, key_pos, cfg: SynthCfg, gate_subsample: int = 2048):
|
| 258 |
+
"""Kernel-D gated spread loss on the TRUE key-token write addresses.
|
| 259 |
+
|
| 260 |
+
Same definition as mulattice.addressing.gated_spread_loss, but the
|
| 261 |
+
pairwise write-overlap gate is computed on a subsample when N is large
|
| 262 |
+
(it is (B,N,N); at N=8,192 that is 67M entries per row)."""
|
| 263 |
+
addr = key_addresses(model, tokens, key_pos)
|
| 264 |
+
B, N, _ = addr.shape
|
| 265 |
+
addr_gate = addr[:, torch.randperm(N, device=addr.device)[:gate_subsample]] if N > gate_subsample else addr
|
| 266 |
+
return _gated_spread(addr, addr_gate, float(model.blocks[0].mixer.cfg.addr_scale))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _gated_spread(addr, addr_gate, scale):
|
| 270 |
+
from mulattice.addressing import write_overlap
|
| 271 |
+
from mulattice.kernel import phi_2d
|
| 272 |
+
B, N, _ = addr.shape
|
| 273 |
+
gate = (write_overlap(addr_gate) - 0.05).clamp(0.0, 1.0).detach()
|
| 274 |
+
lam = 0.3 + 0.7 * gate
|
| 275 |
+
w, z = phi_2d(addr)
|
| 276 |
+
size = int(2 * scale + 3)
|
| 277 |
+
off = int(scale) + 1
|
| 278 |
+
gi = (z + off).clamp(0, size - 1)
|
| 279 |
+
idx = (gi[..., 0] * size + gi[..., 1]).reshape(B, -1).to(torch.int64)
|
| 280 |
+
mass = (w / w.sum(dim=(-2, -1), keepdim=True)).reshape(B, -1)
|
| 281 |
+
hist = torch.zeros(B, size * size, device=addr.device, dtype=addr.dtype)
|
| 282 |
+
for b in range(B):
|
| 283 |
+
hist[b].index_add_(0, idx[b], mass[b])
|
| 284 |
+
p = hist / hist.sum(dim=1, keepdim=True).clamp_min(1e-9)
|
| 285 |
+
entropy = -(p * (p + 1e-12).log()).sum(dim=1)
|
| 286 |
+
return (lam * (-entropy)).mean()
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# ---------------------------------------------------------------------------
|
| 290 |
+
# vocab surgery: extend the proven 1024-key model to the full key vocabulary
|
| 291 |
+
# ---------------------------------------------------------------------------
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def extend_from_checkpoint(new_model, ckpt_path: str, NK: int = 16384, NV: int = 16384,
|
| 295 |
+
old_NK: int = 1024, old_NV: int = 1024,
|
| 296 |
+
noise: float = 0.05, seed: int = 0):
|
| 297 |
+
"""Copy the proven model's mixer into `new_model`; extend emb/head rows.
|
| 298 |
+
|
| 299 |
+
New key/value ids are initialised from a donor id (j mod 1024) plus small
|
| 300 |
+
noise, so fresh ids start inside the working recall circuit instead of as
|
| 301 |
+
random noise -- extending a working vocabulary rather than re-bootstrapping.
|
| 302 |
+
From-scratch training at V>=16K historically never escaped the chance plateau
|
| 303 |
+
(logs/vocab8192.log, logs/vocabcur.log).
|
| 304 |
+
"""
|
| 305 |
+
ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 306 |
+
old = ck["model"]
|
| 307 |
+
new = {k: (v.clone() if k not in ("emb.weight", "head.weight") else None)
|
| 308 |
+
for k, v in new_model.state_dict().items()}
|
| 309 |
+
# every non-emb/head parameter has identical shape -> straight copy
|
| 310 |
+
for k in new:
|
| 311 |
+
if new[k] is None:
|
| 312 |
+
continue
|
| 313 |
+
if k not in old or old[k].shape != new[k].shape:
|
| 314 |
+
raise KeyError(f"cannot warm-start: parameter {k} missing/shape-mismatched")
|
| 315 |
+
new[k] = old[k].clone()
|
| 316 |
+
g = torch.Generator().manual_seed(seed)
|
| 317 |
+
|
| 318 |
+
def build_rows(rows_old, std, off_new, span_new, off_old, span_old):
|
| 319 |
+
out = torch.empty(span_new, rows_old.shape[1])
|
| 320 |
+
donors = torch.arange(span_new) % span_old
|
| 321 |
+
out[:] = rows_old[off_old + donors]
|
| 322 |
+
out += torch.randn(out.shape, generator=g) * (noise * std)
|
| 323 |
+
return out
|
| 324 |
+
|
| 325 |
+
for pname in ("emb.weight", "head.weight"):
|
| 326 |
+
rows_old, rows_new = old[pname], new_model.state_dict()[pname]
|
| 327 |
+
std = rows_old.std().item()
|
| 328 |
+
# keys: first old_NK ids keep their trained rows, the rest inherit donors
|
| 329 |
+
rows_new[:old_NK] = rows_old[:old_NK]
|
| 330 |
+
rows_new[old_NK:NK] = build_rows(rows_old, std, old_NK, NK - old_NK, 0, old_NK)
|
| 331 |
+
# values (offset NK in the new layout, old_NK in the old one)
|
| 332 |
+
rows_new[NK:NK + old_NV] = rows_old[old_NK:old_NK + old_NV]
|
| 333 |
+
rows_new[NK + old_NV:NK + NV] = build_rows(rows_old, std, 0, NV - old_NV, old_NK, old_NV)
|
| 334 |
+
# unused id + SEP
|
| 335 |
+
rows_new[NK + NV] = rows_old[old_NK + old_NV]
|
| 336 |
+
rows_new[NK + NV + 1] = rows_old[old_NK + old_NV + 1]
|
| 337 |
+
new[pname] = rows_new
|
| 338 |
+
new_model.load_state_dict(new)
|
| 339 |
+
return new_model
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# ---------------------------------------------------------------------------
|
| 343 |
+
# real-data protocol (same mining as experiments/eval_realdata.py)
|
| 344 |
+
# ---------------------------------------------------------------------------
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class RealData:
|
| 348 |
+
def __init__(self, corpus_path: str, VS: int = 4094):
|
| 349 |
+
from collections import Counter
|
| 350 |
+
self.VS = VS
|
| 351 |
+
words = open(corpus_path, encoding="utf-8", errors="replace").read().lower().split()
|
| 352 |
+
cnt = Counter(words)
|
| 353 |
+
vocab = [w for w, _ in cnt.most_common(VS - 1)]
|
| 354 |
+
wid = {w: i for i, w in enumerate(vocab)}
|
| 355 |
+
big = Counter()
|
| 356 |
+
for a, b in zip(words, words[1:]):
|
| 357 |
+
if a in wid and b in wid:
|
| 358 |
+
big[(wid[a], wid[b])] += 1
|
| 359 |
+
succ = {}
|
| 360 |
+
for (a, b), c in big.items():
|
| 361 |
+
if c >= 4 and (a not in succ or succ[a][1] < c):
|
| 362 |
+
succ[a] = (b, c)
|
| 363 |
+
kv = {}
|
| 364 |
+
ranked = sorted(succ.keys(), key=lambda k: -cnt[vocab[k]])
|
| 365 |
+
lo, hi = int(len(ranked) * 0.02), int(len(ranked) * 0.95)
|
| 366 |
+
for k in ranked[lo:hi]:
|
| 367 |
+
v = succ[k][0]
|
| 368 |
+
if v != k and cnt[vocab[v]] >= 10:
|
| 369 |
+
kv[k] = v
|
| 370 |
+
self.KVLIST = torch.tensor(sorted(kv.keys()))
|
| 371 |
+
self.KVARR = torch.tensor([kv[int(k)] for k in self.KVLIST])
|
| 372 |
+
# Zipfian position weights (cnt^0.75, as in realdata256k.py sample_pairs):
|
| 373 |
+
# concentrating on frequent keys is what let the old run transition in
|
| 374 |
+
# <400 steps; uniform sampling left rare-key embeddings gradient-starved
|
| 375 |
+
# and the model stuck at 0.35 (measured 2026-11-02, realdata_v2 first run).
|
| 376 |
+
w = torch.tensor([float(cnt[vocab[int(k)]]) ** 0.75 for k in self.KVLIST])
|
| 377 |
+
self.KEY_W = w / w.sum()
|
| 378 |
+
self.FILLER = torch.tensor([wid[w] for w in words if w in wid], dtype=torch.long)
|
| 379 |
+
self.KVOCAB = VS
|
| 380 |
+
self.SEP = 2 * VS
|
| 381 |
+
self.V = 2 * VS + 2
|
| 382 |
+
self.n_pairs = len(self.KVLIST)
|
| 383 |
+
|
| 384 |
+
def sample_positions(self, B: int, P: int, g: torch.Generator, zipf: bool) -> torch.Tensor:
|
| 385 |
+
"""(B,P) distinct KVLIST positions; uniform or Zipf-weighted per row."""
|
| 386 |
+
if not zipf:
|
| 387 |
+
return torch.stack([torch.randperm(self.n_pairs, generator=g)[:P] for _ in range(B)])
|
| 388 |
+
rows = []
|
| 389 |
+
for _ in range(B):
|
| 390 |
+
cand = torch.multinomial(self.KEY_W, 2 * P, replacement=True, generator=g).tolist()
|
| 391 |
+
seen, out, j = set(), [], 0
|
| 392 |
+
while len(out) < P and j < len(cand):
|
| 393 |
+
k = cand[j]; j += 1
|
| 394 |
+
if k not in seen:
|
| 395 |
+
seen.add(k); out.append(k)
|
| 396 |
+
if len(out) < P: # exhausted weighted draws: fill uniformly
|
| 397 |
+
rest = [i for i in torch.randperm(self.n_pairs, generator=g).tolist()
|
| 398 |
+
if i not in seen][: P - len(out)]
|
| 399 |
+
out += rest
|
| 400 |
+
rows.append(out)
|
| 401 |
+
return torch.tensor(rows)
|
| 402 |
+
|
| 403 |
+
def batch(self, P: int, filler: int, Q: int, seed: int, B: int = 1,
|
| 404 |
+
overwrite_frac: float = 0.0, qpos_idx: torch.Tensor | None = None,
|
| 405 |
+
zipf: bool = False):
|
| 406 |
+
"""Real-data store/query batch. qpos_idx: (Q,) indices into the P stored
|
| 407 |
+
pairs (allows depth-stratified query sets); overwrite re-presents chosen
|
| 408 |
+
keys with a DIFFERENT value token (another pair's value)."""
|
| 409 |
+
g = torch.Generator().manual_seed(seed)
|
| 410 |
+
P = min(P, self.n_pairs)
|
| 411 |
+
perms = self.sample_positions(B, P, g, zipf)
|
| 412 |
+
keys = self.KVLIST[perms] # (B,P) key token ids
|
| 413 |
+
vals = self.KVARR[perms] # (B,P) value token ids
|
| 414 |
+
n_upd = int(round(P * overwrite_frac))
|
| 415 |
+
upd_idx = None
|
| 416 |
+
upd_vals = None
|
| 417 |
+
if n_upd:
|
| 418 |
+
upd_idx = torch.stack([torch.randperm(P, generator=g)[:n_upd] for _ in range(B)])
|
| 419 |
+
# update value = another pair's value; redraw the rare self-collisions
|
| 420 |
+
shift = torch.stack([torch.randperm(P, generator=g)[:n_upd] for _ in range(B)])
|
| 421 |
+
upd_vals = torch.gather(vals, 1, shift)
|
| 422 |
+
same = upd_vals == torch.gather(vals, 1, upd_idx)
|
| 423 |
+
while bool(same.any()):
|
| 424 |
+
# rare: key's successor equals donor's successor -> bump by one token id
|
| 425 |
+
flat = same.reshape(-1)
|
| 426 |
+
upd_vals.reshape(-1)[flat] = (upd_vals.reshape(-1)[flat] + 1) % self.VS
|
| 427 |
+
same = upd_vals == torch.gather(vals, 1, upd_idx)
|
| 428 |
+
if qpos_idx is None:
|
| 429 |
+
qpos_idx = torch.stack([torch.randperm(P, generator=g)[:Q] for _ in range(B)])
|
| 430 |
+
elif qpos_idx.dim() == 1:
|
| 431 |
+
qpos_idx = qpos_idx.unsqueeze(0).expand(B, -1).contiguous()
|
| 432 |
+
Q = qpos_idx.shape[1] # the actual query count (clamped to P)
|
| 433 |
+
qkeys = torch.gather(keys, 1, qpos_idx)
|
| 434 |
+
|
| 435 |
+
f = filler
|
| 436 |
+
block = f + 2
|
| 437 |
+
L = (P + n_upd) * block + 2 * Q
|
| 438 |
+
tokens = torch.zeros(B, L, dtype=torch.long)
|
| 439 |
+
fptr = torch.randint(0, max(1, len(self.FILLER) - f * (P + n_upd) - 1), (1,),
|
| 440 |
+
generator=g).item()
|
| 441 |
+
for i in range(P):
|
| 442 |
+
s = i * block
|
| 443 |
+
if f:
|
| 444 |
+
tokens[:, s:s + f] = self.FILLER[fptr:fptr + f]
|
| 445 |
+
fptr += f
|
| 446 |
+
tokens[:, s + f] = keys[:, i]
|
| 447 |
+
tokens[:, s + f + 1] = vals[:, i] + self.KVOCAB
|
| 448 |
+
if n_upd:
|
| 449 |
+
upd_keys = torch.gather(keys, 1, upd_idx)
|
| 450 |
+
for j in range(n_upd):
|
| 451 |
+
s = (P + j) * block
|
| 452 |
+
if f:
|
| 453 |
+
tokens[:, s:s + f] = self.FILLER[fptr:fptr + f]
|
| 454 |
+
fptr += f
|
| 455 |
+
tokens[:, s + f] = upd_keys[:, j]
|
| 456 |
+
tokens[:, s + f + 1] = upd_vals[:, j] + self.KVOCAB
|
| 457 |
+
S2 = (P + n_upd) * block
|
| 458 |
+
latest = vals.clone()
|
| 459 |
+
if n_upd:
|
| 460 |
+
latest.scatter_(1, upd_idx, upd_vals)
|
| 461 |
+
gold = torch.gather(latest, 1, qpos_idx) + self.KVOCAB
|
| 462 |
+
for q in range(Q):
|
| 463 |
+
tokens[:, S2 + 2 * q] = qkeys[:, q]
|
| 464 |
+
tokens[:, S2 + 2 * q + 1] = self.SEP
|
| 465 |
+
key_pos = (torch.arange(P) * block + f).unsqueeze(0).expand(B, -1).contiguous()
|
| 466 |
+
upd_key_pos = ((P + torch.arange(n_upd)) * block + f).unsqueeze(0).expand(B, -1).contiguous() \
|
| 467 |
+
if n_upd else None
|
| 468 |
+
# ANSWER AT THE QUERY-KEY POSITION (even offsets), matching the original
|
| 469 |
+
# realdata256k.py training and eval_realdata.py: `labels[L-2*(n-j)]` is the
|
| 470 |
+
# query-key token, not the SEP after it. (The SYNTHETIC task answers at
|
| 471 |
+
# the SEP -- mqar.py `ans_pos = arange(1, 2*n_queries, 2)` -- two different
|
| 472 |
+
# conventions, both from the previous session; the warm checkpoint knows
|
| 473 |
+
# the query-key one. Measured: same tokens score 0.875 under the key
|
| 474 |
+
# convention and 0.000 under the SEP convention.)
|
| 475 |
+
ans_pos = (S2 + 2 * torch.arange(Q)).unsqueeze(0).expand(B, -1).contiguous()
|
| 476 |
+
was_upd = torch.zeros(B, Q, dtype=torch.bool)
|
| 477 |
+
if n_upd:
|
| 478 |
+
m = torch.zeros(B, P, dtype=torch.bool)
|
| 479 |
+
m.scatter_(1, upd_idx, True)
|
| 480 |
+
was_upd = torch.gather(m, 1, qpos_idx)
|
| 481 |
+
return {"tokens": tokens, "ans_pos": ans_pos, "gold": gold, "was_updated": was_upd,
|
| 482 |
+
"key_pos": key_pos, "upd_key_pos": upd_key_pos, "n_pairs": P, "n_upd": n_upd,
|
| 483 |
+
"L": L}
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def stratified_qpos(P: int, Q: int, strata: int = 4, seed: int = 0):
|
| 487 |
+
"""Query indices stratified over store depth: each stratum gets Q/strata
|
| 488 |
+
queries drawn from pairs stored at that depth fraction of the sequence."""
|
| 489 |
+
g = torch.Generator().manual_seed(seed)
|
| 490 |
+
per = Q // strata
|
| 491 |
+
out = []
|
| 492 |
+
bounds = torch.linspace(0, P, strata + 1).long()
|
| 493 |
+
for s in range(strata):
|
| 494 |
+
lo, hi = int(bounds[s]), int(bounds[s + 1])
|
| 495 |
+
out.append(lo + torch.randperm(hi - lo, generator=g)[:per])
|
| 496 |
+
return torch.cat(out)
|
src/mulattice/sparse_scan.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Batched, differentiable μLattice lattice scan.
|
| 3 |
+
|
| 4 |
+
Same published math as mulattice.lattice.LatticeMemory, but the sequential
|
| 5 |
+
recurrence is executed with tensor ops over the whole batch instead of a Python
|
| 6 |
+
loop over (token x 9 cells), so the synthetic MQAR mixers can be trained.
|
| 7 |
+
|
| 8 |
+
Sparsity is preserved: cells are keyed by (sequence, z_x, z_y) via
|
| 9 |
+
torch.unique, and only the keys that actually occur are allocated. No dense
|
| 10 |
+
grid over the address bounding box is ever materialised. Cell count is
|
| 11 |
+
unbounded -- it is the number of distinct addresses written.
|
| 12 |
+
|
| 13 |
+
Semantics identical to the reference implementation:
|
| 14 |
+
phi from the published bump kernel, exactly 9 cells per token,
|
| 15 |
+
v_bar = alpha * W_c kappa ; r = v - v_bar ; W_c <- alpha W_c + beta r kappa^T
|
| 16 |
+
read = sum over the 3x3 neighbourhood of phi_c * (W_c q2), empty cells 0.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from .kernel import MAX_CELLS_PER_TOKEN, phi_2d
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def compact_ids(keys: torch.Tensor) -> tuple[torch.Tensor, int]:
|
| 27 |
+
"""Map arbitrary int64 keys to dense contiguous ids, via sort.
|
| 28 |
+
|
| 29 |
+
Uses sort + run detection instead of torch.unique: on MPS, torch.unique corrupts int64
|
| 30 |
+
values outside the int32 range (measured: 4959 distinct keys reported as 2789,
|
| 31 |
+
with returned values like -30933022 instead of 549724880885). That scrambled
|
| 32 |
+
the cell ids, collapsed the lattice onto a few cells, and made training
|
| 33 |
+
diverge to inf gradients on MPS while CPU was fine. Sort + run detection is
|
| 34 |
+
exact on every backend.
|
| 35 |
+
"""
|
| 36 |
+
if keys.numel() == 0:
|
| 37 |
+
return keys.clone(), 0
|
| 38 |
+
order = torch.argsort(keys)
|
| 39 |
+
ks = keys[order]
|
| 40 |
+
first = torch.ones_like(ks, dtype=torch.bool)
|
| 41 |
+
first[1:] = ks[1:] != ks[:-1]
|
| 42 |
+
ids_sorted = torch.cumsum(first.to(torch.int64), 0) - 1
|
| 43 |
+
ids = torch.empty_like(ids_sorted)
|
| 44 |
+
ids[order] = ids_sorted
|
| 45 |
+
return ids, int(first.sum())
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _encode_keys(coords: torch.Tensor, n_seq: int, size: int = 1 << 20) -> torch.Tensor:
|
| 49 |
+
"""coords (B,T,9,2) int64 -> flat int64 keys, collision-free for |z| < size/2."""
|
| 50 |
+
z = coords + (size // 2)
|
| 51 |
+
b = torch.arange(n_seq, device=coords.device, dtype=torch.int64).view(n_seq, 1, 1)
|
| 52 |
+
return (b * (size * size)) + z[..., 0] * size + z[..., 1]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SparseLatticeScan(torch.nn.Module):
|
| 56 |
+
def __init__(self, d_k: int, d_v: int, n_heads: int, size: int = 1 << 20,
|
| 57 |
+
weighted_write: bool = True):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.d_k, self.d_v, self.n_heads, self.size = d_k, d_v, n_heads, size
|
| 60 |
+
self.weighted_write = weighted_write
|
| 61 |
+
self.last_n_cells = 0
|
| 62 |
+
|
| 63 |
+
def forward(
|
| 64 |
+
self,
|
| 65 |
+
q_addr: torch.Tensor, # (B,T,2) real address of the query
|
| 66 |
+
k_addr: torch.Tensor, # (B,T,2) real address of the key
|
| 67 |
+
q2: torch.Tensor, # (B,T,H,d_k) content query
|
| 68 |
+
kappa: torch.Tensor, # (B,T,H,d_k) content key
|
| 69 |
+
v: torch.Tensor, # (B,T,H,d_v) value
|
| 70 |
+
alpha: torch.Tensor, # (B,T,H,1) decay in (0,1)
|
| 71 |
+
beta: torch.Tensor, # (B,T,H,1) write gate in (0,1)
|
| 72 |
+
read_mode: str = "last", # "last" | "all" | "none"
|
| 73 |
+
causal_read: bool = True,
|
| 74 |
+
):
|
| 75 |
+
B, T, H = kappa.shape[0], kappa.shape[1], self.n_heads
|
| 76 |
+
dev, dt = kappa.device, kappa.dtype
|
| 77 |
+
|
| 78 |
+
wk, zk = phi_2d(k_addr) # (B,T,3,3), (B,T,3,3,2)
|
| 79 |
+
wq, zq = phi_2d(q_addr)
|
| 80 |
+
wk = wk.reshape(B, T, MAX_CELLS_PER_TOKEN)
|
| 81 |
+
wq = wq.reshape(B, T, MAX_CELLS_PER_TOKEN)
|
| 82 |
+
zk = zk.reshape(B, T, MAX_CELLS_PER_TOKEN, 2)
|
| 83 |
+
zq = zq.reshape(B, T, MAX_CELLS_PER_TOKEN, 2)
|
| 84 |
+
|
| 85 |
+
need_q = read_mode != "none"
|
| 86 |
+
keys_w = _encode_keys(zk, B, self.size).reshape(-1)
|
| 87 |
+
keys_q = _encode_keys(zq, B, self.size).reshape(-1) if need_q else keys_w[:0]
|
| 88 |
+
all_keys = torch.cat([keys_w, keys_q]) if need_q else keys_w
|
| 89 |
+
inv, n_cells = compact_ids(all_keys)
|
| 90 |
+
self.last_n_cells = int(n_cells)
|
| 91 |
+
inv_w = inv[: keys_w.numel()].reshape(B, T, MAX_CELLS_PER_TOKEN)
|
| 92 |
+
inv_q = (
|
| 93 |
+
inv[keys_w.numel():].reshape(B, T, MAX_CELLS_PER_TOKEN) if need_q else None
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# cells allocated lazily: only distinct keys that occur, zero-initialised
|
| 97 |
+
cells = torch.zeros(n_cells, H, self.d_v, self.d_k, device=dev, dtype=dt)
|
| 98 |
+
|
| 99 |
+
outs = []
|
| 100 |
+
for t in range(T):
|
| 101 |
+
idx = inv_w[:, t] # (B,9)
|
| 102 |
+
W = cells.index_select(0, idx.reshape(-1)).reshape(B, MAX_CELLS_PER_TOKEN, H, self.d_v, self.d_k)
|
| 103 |
+
kap = kappa[:, t].unsqueeze(1) # (B,1,H,dk)
|
| 104 |
+
a = alpha[:, t].unsqueeze(1) # (B,1,H,1)
|
| 105 |
+
b = beta[:, t].unsqueeze(1)
|
| 106 |
+
v_bar = a * (W @ kap.unsqueeze(-1)).squeeze(-1) # (B,9,H,dv)
|
| 107 |
+
r = v[:, t].unsqueeze(1) - v_bar
|
| 108 |
+
gate = b * wk[:, t].unsqueeze(-1).unsqueeze(-1) if self.weighted_write else b
|
| 109 |
+
W = a.unsqueeze(-1) * W + gate.unsqueeze(-1) * (r.unsqueeze(-1) * kap.unsqueeze(-2))
|
| 110 |
+
cells.index_put_((idx.reshape(-1),), W.reshape(-1, H, self.d_v, self.d_k))
|
| 111 |
+
|
| 112 |
+
if read_mode == "all":
|
| 113 |
+
qi = inv_q[:, t] if causal_read else None
|
| 114 |
+
if qi is None: # non-causal: after full seq
|
| 115 |
+
outs.append(None)
|
| 116 |
+
else:
|
| 117 |
+
Wq = cells.index_select(0, qi.reshape(-1)).reshape(
|
| 118 |
+
B, MAX_CELLS_PER_TOKEN, H, self.d_v, self.d_k)
|
| 119 |
+
rq = (Wq @ q2[:, t].unsqueeze(1).unsqueeze(-1)).squeeze(-1) # (B,9,H,dv)
|
| 120 |
+
outs.append((wq[:, t].unsqueeze(-1).unsqueeze(-1) * rq).sum(1))
|
| 121 |
+
|
| 122 |
+
if read_mode == "last":
|
| 123 |
+
qi = inv_q[:, T - 1] # (B,9)
|
| 124 |
+
Wq = cells.index_select(0, qi.reshape(-1)).reshape(
|
| 125 |
+
B, MAX_CELLS_PER_TOKEN, H, self.d_v, self.d_k)
|
| 126 |
+
rq = (Wq @ q2[:, T - 1].unsqueeze(1).unsqueeze(-1)).squeeze(-1)
|
| 127 |
+
out = (wq[:, T - 1].unsqueeze(-1).unsqueeze(-1) * rq).sum(1) # (B,H,dv)
|
| 128 |
+
return out, n_cells
|
| 129 |
+
if read_mode == "all":
|
| 130 |
+
return torch.stack(outs, dim=1), n_cells # (B,T,H,dv)
|
| 131 |
+
return None, n_cells
|