ARotting commited on
Commit
da8c244
·
verified ·
1 Parent(s): 735e375

Publish Temporary key-value binding benchmark

Browse files
Files changed (7) hide show
  1. README.md +47 -0
  2. binding_test.npz +3 -0
  3. source/app.py +86 -0
  4. source/data.py +50 -0
  5. source/model.py +84 -0
  6. source/requirements.txt +5 -0
  7. source/train.py +202 -0
README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - fast-weights
5
+ - associative-memory
6
+ - meta-learning
7
+ - sequence-modeling
8
+ - gradio
9
+ ---
10
+
11
+ # Fast-Weight Time Machine
12
+
13
+ Fast-Weight Time Machine tests temporary variable binding with an explicit,
14
+ sequence-local weight matrix. A controller receives key/value writes, produces a
15
+ write strength, and accumulates outer products in a fast memory. A later query key
16
+ reads the memory in one matrix-vector operation. The learned parameters stay fixed
17
+ between examples; only the fast matrix changes inside each sequence.
18
+
19
+ The historical anchor is Schmidhuber's 1992
20
+ [Learning to Control Fast-Weight Memories](https://doi.org/10.1162/NECO.1992.4.1.131),
21
+ which described feedforward controllers producing context-dependent weight changes
22
+ and included adaptive temporary-variable binding. This project is a modern
23
+ outer-product interpretation tested against a similarly sized GRU. It does not
24
+ claim to reproduce the original implementation or experiments exactly.
25
+
26
+ ## Verified results
27
+
28
+ The models trained on 16,000 sequences containing four writes and 12 distractors.
29
+ Each held-out condition contained 4,000 new sequences.
30
+
31
+ | Condition | Fast weights, 2,508 params | GRU, 3,050 params |
32
+ | --- | ---: | ---: |
33
+ | 4 bindings, 12 distractors | 100.00% | 37.40% |
34
+ | 8 bindings, 12 distractors | 100.00% | 27.03% |
35
+ | 4 bindings, 64 distractors | 100.00% | 31.15% |
36
+ | 8 bindings, 64 distractors | 99.98% | 23.83% |
37
+
38
+ This task is intentionally aligned with the fast-weight architecture: an explicit
39
+ outer-product matrix can bind a key and value, while the GRU must compress all
40
+ bindings into one recurrent vector. The comparison demonstrates the inductive bias;
41
+ it is not a general claim that fast weights outperform GRUs on arbitrary sequences.
42
+
43
+ ## Reproduce
44
+
45
+ ```powershell
46
+ uv run python projects/fast-weight-time-machine/train.py
47
+ ```
binding_test.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17403706f00b394b26ebdbfc928de40c1a65ab1b65ff4eb7167cecd3a0fd9099
3
+ size 127296
source/app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import gradio as gr
6
+ import plotly.graph_objects as go
7
+ import torch
8
+ from data import VALUES, generate_bindings
9
+ from model import FastWeightProgrammer
10
+ from safetensors.torch import load_file
11
+
12
+ ARTIFACT_DIR = (
13
+ Path(__file__).resolve().parent / "artifacts" / "fast-weight-time-machine"
14
+ )
15
+ MODEL = FastWeightProgrammer()
16
+ MODEL.load_state_dict(load_file(ARTIFACT_DIR / "fast_weight.safetensors"))
17
+ MODEL.eval()
18
+
19
+
20
+ def inspect_binding(
21
+ seed: int, pairs: int, distractors: int
22
+ ) -> tuple[go.Figure, dict]:
23
+ keys, values, writes, targets = generate_bindings(
24
+ 1, int(pairs), int(distractors), int(seed)
25
+ )
26
+ with torch.inference_mode():
27
+ logits, strengths, contributions = MODEL(
28
+ torch.from_numpy(keys),
29
+ torch.from_numpy(values),
30
+ torch.from_numpy(writes),
31
+ return_trace=True,
32
+ )
33
+ probabilities = torch.softmax(logits, dim=1).numpy()[0]
34
+ contribution = contributions.numpy()[0]
35
+ labels = [
36
+ f"K{key}:V{value}" if value < VALUES else f"QUERY K{key}"
37
+ for key, value in zip(keys[0], values[0], strict=True)
38
+ ]
39
+ colors = ["#f59e0b" if write else "#334155" for write in writes[0]]
40
+ figure = go.Figure(
41
+ go.Bar(
42
+ x=list(range(len(labels))),
43
+ y=contribution,
44
+ marker_color=colors,
45
+ customdata=labels,
46
+ hovertemplate="%{customdata}<br>read contribution=%{y:.3f}",
47
+ )
48
+ )
49
+ figure.update_layout(
50
+ title="Query-key contribution to the fast weight matrix",
51
+ xaxis_title="Sequence event",
52
+ yaxis_title="Contribution",
53
+ template="plotly_dark",
54
+ )
55
+ prediction = int(probabilities.argmax())
56
+ return figure, {
57
+ "query": labels[-1],
58
+ "target_value": int(targets[0]),
59
+ "predicted_value": prediction,
60
+ "correct": prediction == int(targets[0]),
61
+ "confidence": round(float(probabilities[prediction]), 4),
62
+ "mean_active_write_strength": round(
63
+ float(strengths.numpy()[0][writes[0] == 1].mean()), 4
64
+ ),
65
+ }
66
+
67
+
68
+ with gr.Blocks(title="Fast-Weight Time Machine") as demo:
69
+ gr.Markdown(
70
+ "# Fast-Weight Time Machine\n"
71
+ "Watch a learned controller write temporary key/value bindings into a "
72
+ "sequence-local weight matrix, then retrieve one binding."
73
+ )
74
+ with gr.Row():
75
+ seed = gr.Number(2043, precision=0, label="Sequence seed")
76
+ pairs = gr.Slider(2, 12, 4, step=1, label="Stored bindings")
77
+ distractors = gr.Slider(0, 64, 12, step=4, label="Distractors")
78
+ run = gr.Button("Program fast memory", variant="primary")
79
+ trace = gr.Plot()
80
+ result = gr.JSON()
81
+ run.click(inspect_binding, [seed, pairs, distractors], [trace, result])
82
+ demo.load(inspect_binding, [seed, pairs, distractors], [trace, result])
83
+
84
+
85
+ if __name__ == "__main__":
86
+ demo.launch()
source/data.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ KEYS = 16
6
+ VALUES = 10
7
+ VALUE_SENTINEL = VALUES
8
+
9
+
10
+ def generate_bindings(
11
+ samples: int,
12
+ pairs: int,
13
+ distractors: int,
14
+ seed: int,
15
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
16
+ if pairs > KEYS:
17
+ raise ValueError("Pairs cannot exceed the unique key vocabulary.")
18
+ rng = np.random.default_rng(seed)
19
+ length = pairs + distractors + 1
20
+ keys = np.zeros((samples, length), dtype=np.int64)
21
+ values = np.zeros((samples, length), dtype=np.int64)
22
+ writes = np.zeros((samples, length), dtype=np.float32)
23
+ targets = np.zeros(samples, dtype=np.int64)
24
+ for row in range(samples):
25
+ bound_keys = rng.choice(KEYS, pairs, replace=False)
26
+ bound_values = rng.integers(0, VALUES, size=pairs)
27
+ events = [
28
+ (int(key), int(value), 1.0)
29
+ for key, value in zip(bound_keys, bound_values, strict=True)
30
+ ]
31
+ events.extend(
32
+ [
33
+ (
34
+ int(rng.integers(0, KEYS)),
35
+ int(rng.integers(0, VALUES)),
36
+ 0.0,
37
+ )
38
+ for _ in range(distractors)
39
+ ]
40
+ )
41
+ rng.shuffle(events)
42
+ for step, (key, value, write) in enumerate(events):
43
+ keys[row, step] = key
44
+ values[row, step] = value
45
+ writes[row, step] = write
46
+ query = int(rng.integers(0, pairs))
47
+ keys[row, -1] = bound_keys[query]
48
+ values[row, -1] = VALUE_SENTINEL
49
+ targets[row] = bound_values[query]
50
+ return keys, values, writes, targets
source/model.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ class FastWeightProgrammer(nn.Module):
9
+ def __init__(
10
+ self,
11
+ key_vocab: int = 16,
12
+ value_vocab: int = 11,
13
+ values: int = 10,
14
+ dimension: int = 64,
15
+ ) -> None:
16
+ super().__init__()
17
+ self.key_embedding = nn.Embedding(key_vocab, dimension)
18
+ self.value_embedding = nn.Embedding(value_vocab, dimension)
19
+ self.write_controller = nn.Linear(2 * dimension + 1, 1)
20
+ self.readout = nn.Linear(dimension, values)
21
+
22
+ def forward(
23
+ self,
24
+ keys: torch.Tensor,
25
+ values: torch.Tensor,
26
+ writes: torch.Tensor,
27
+ *,
28
+ return_trace: bool = False,
29
+ ):
30
+ key_vectors = F.normalize(self.key_embedding(keys), dim=-1)
31
+ value_vectors = self.value_embedding(values)
32
+ controller_input = torch.cat(
33
+ [key_vectors, value_vectors, writes.unsqueeze(-1)], dim=-1
34
+ )
35
+ strengths = torch.sigmoid(self.write_controller(controller_input))
36
+ strengths = strengths.squeeze(-1) * writes
37
+ memory = torch.einsum(
38
+ "bt,btd,bte->bde",
39
+ strengths,
40
+ key_vectors,
41
+ value_vectors,
42
+ )
43
+ query = key_vectors[:, -1]
44
+ retrieved = torch.einsum("bd,bde->be", query, memory)
45
+ logits = self.readout(retrieved)
46
+ if return_trace:
47
+ contributions = (
48
+ torch.einsum("btd,bd->bt", key_vectors, query) * strengths
49
+ )
50
+ return logits, strengths, contributions
51
+ return logits
52
+
53
+
54
+ class GRUControl(nn.Module):
55
+ def __init__(
56
+ self,
57
+ key_vocab: int = 16,
58
+ value_vocab: int = 11,
59
+ values: int = 10,
60
+ dimension: int = 16,
61
+ ) -> None:
62
+ super().__init__()
63
+ self.key_embedding = nn.Embedding(key_vocab, dimension)
64
+ self.value_embedding = nn.Embedding(value_vocab, dimension)
65
+ self.recurrent = nn.GRU(2 * dimension + 1, dimension, batch_first=True)
66
+ self.readout = nn.Linear(dimension, values)
67
+
68
+ def forward(
69
+ self, keys: torch.Tensor, values: torch.Tensor, writes: torch.Tensor
70
+ ) -> torch.Tensor:
71
+ inputs = torch.cat(
72
+ [
73
+ self.key_embedding(keys),
74
+ self.value_embedding(values),
75
+ writes.unsqueeze(-1),
76
+ ],
77
+ dim=-1,
78
+ )
79
+ hidden, _ = self.recurrent(inputs)
80
+ return self.readout(hidden[:, -1])
81
+
82
+
83
+ def parameter_count(module: nn.Module) -> int:
84
+ return sum(parameter.numel() for parameter in module.parameters())
source/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=5,<7
2
+ numpy>=2,<3
3
+ plotly>=6,<7
4
+ safetensors>=0.6,<1
5
+ torch>=2.7,<3
source/train.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ import trackio
10
+ from data import generate_bindings
11
+ from model import FastWeightProgrammer, GRUControl, parameter_count
12
+ from safetensors.torch import save_file
13
+ from torch import nn
14
+ from torch.utils.data import DataLoader, TensorDataset
15
+
16
+ PROJECT_DIR = Path(__file__).resolve().parent
17
+ ARTIFACT_DIR = PROJECT_DIR / "artifacts" / "fast-weight-time-machine"
18
+ DATA_DIR = PROJECT_DIR / "data"
19
+
20
+
21
+ def seed_everything(seed: int) -> None:
22
+ np.random.seed(seed)
23
+ torch.manual_seed(seed)
24
+ torch.set_num_threads(1)
25
+
26
+
27
+ def make_loader(
28
+ dataset: tuple[np.ndarray, ...],
29
+ *,
30
+ shuffle: bool,
31
+ seed: int,
32
+ ) -> DataLoader:
33
+ keys, values, writes, targets = dataset
34
+ return DataLoader(
35
+ TensorDataset(
36
+ torch.from_numpy(keys),
37
+ torch.from_numpy(values),
38
+ torch.from_numpy(writes),
39
+ torch.from_numpy(targets),
40
+ ),
41
+ batch_size=256,
42
+ shuffle=shuffle,
43
+ generator=torch.Generator().manual_seed(seed),
44
+ )
45
+
46
+
47
+ @torch.inference_mode()
48
+ def evaluate(model: nn.Module, loader: DataLoader) -> dict:
49
+ model.eval()
50
+ correct = 0
51
+ total = 0
52
+ losses = []
53
+ for keys, values, writes, targets in loader:
54
+ logits = model(keys, values, writes)
55
+ losses.append(float(nn.functional.cross_entropy(logits, targets)))
56
+ correct += int((logits.argmax(1) == targets).sum())
57
+ total += len(targets)
58
+ return {"accuracy": correct / total, "cross_entropy": float(np.mean(losses))}
59
+
60
+
61
+ def train_variant(
62
+ name: str,
63
+ model: nn.Module,
64
+ train_loader: DataLoader,
65
+ validation_loader: DataLoader,
66
+ ) -> tuple[nn.Module, list[dict]]:
67
+ optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-5)
68
+ best = copy.deepcopy(model.state_dict())
69
+ best_accuracy = 0.0
70
+ stale = 0
71
+ history = []
72
+ for epoch in range(1, 61):
73
+ model.train()
74
+ losses = []
75
+ for keys, values, writes, targets in train_loader:
76
+ logits = model(keys, values, writes)
77
+ loss = nn.functional.cross_entropy(logits, targets)
78
+ optimizer.zero_grad()
79
+ loss.backward()
80
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
81
+ optimizer.step()
82
+ losses.append(float(loss.detach()))
83
+ validation = evaluate(model, validation_loader)
84
+ record = {
85
+ "variant": name,
86
+ "epoch": epoch,
87
+ "training_loss": float(np.mean(losses)),
88
+ "validation_accuracy": validation["accuracy"],
89
+ }
90
+ history.append(record)
91
+ if epoch % 5 == 0:
92
+ trackio.log(record)
93
+ if validation["accuracy"] > best_accuracy + 1e-4:
94
+ best_accuracy = validation["accuracy"]
95
+ best = copy.deepcopy(model.state_dict())
96
+ stale = 0
97
+ else:
98
+ stale += 1
99
+ if stale >= 10 and epoch >= 20:
100
+ break
101
+ model.load_state_dict(best)
102
+ return model, history
103
+
104
+
105
+ def main() -> None:
106
+ seed_everything(2043)
107
+ train_data = generate_bindings(16_000, pairs=4, distractors=12, seed=2043)
108
+ validation_data = generate_bindings(
109
+ 2_000, pairs=4, distractors=12, seed=3043
110
+ )
111
+ evaluation_data = {
112
+ "four_pairs_12_distractors": generate_bindings(
113
+ 4_000, 4, 12, seed=4043
114
+ ),
115
+ "eight_pairs_12_distractors": generate_bindings(
116
+ 4_000, 8, 12, seed=5043
117
+ ),
118
+ "four_pairs_64_distractors": generate_bindings(
119
+ 4_000, 4, 64, seed=6043
120
+ ),
121
+ "eight_pairs_64_distractors": generate_bindings(
122
+ 4_000, 8, 64, seed=7043
123
+ ),
124
+ }
125
+ train_loader = make_loader(train_data, shuffle=True, seed=2043)
126
+ validation_loader = make_loader(
127
+ validation_data, shuffle=False, seed=3043
128
+ )
129
+ variants = {
130
+ "fast_weight": FastWeightProgrammer(),
131
+ "gru": GRUControl(),
132
+ }
133
+ trackio.init(
134
+ project="fast-weight-time-machine",
135
+ name="temporary-variable-binding-v1",
136
+ config={
137
+ "training_examples": len(train_data[0]),
138
+ "training_pairs": 4,
139
+ "training_distractors": 12,
140
+ "parameters": {
141
+ name: parameter_count(model) for name, model in variants.items()
142
+ },
143
+ },
144
+ )
145
+ ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
146
+ results = {}
147
+ histories = {}
148
+ for name, model in variants.items():
149
+ trained, history = train_variant(
150
+ name, model, train_loader, validation_loader
151
+ )
152
+ histories[name] = history
153
+ results[name] = {
154
+ "parameters": parameter_count(trained),
155
+ "training_epochs": len(history),
156
+ **{
157
+ condition: evaluate(
158
+ trained, make_loader(dataset, shuffle=False, seed=8043)
159
+ )
160
+ for condition, dataset in evaluation_data.items()
161
+ },
162
+ }
163
+ save_file(trained.state_dict(), ARTIFACT_DIR / f"{name}.safetensors")
164
+ report = {
165
+ "benchmark": "Temporary variable binding",
166
+ "training_examples": len(train_data[0]),
167
+ "results": results,
168
+ "training_history": histories,
169
+ }
170
+ (ARTIFACT_DIR / "evaluation.json").write_text(
171
+ json.dumps(report, indent=2), encoding="utf-8"
172
+ )
173
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
174
+ np.savez_compressed(
175
+ DATA_DIR / "binding_test.npz",
176
+ keys=evaluation_data["four_pairs_12_distractors"][0],
177
+ values=evaluation_data["four_pairs_12_distractors"][1],
178
+ writes=evaluation_data["four_pairs_12_distractors"][2],
179
+ targets=evaluation_data["four_pairs_12_distractors"][3],
180
+ )
181
+ trackio.log(
182
+ {
183
+ "fast_weight_accuracy": results["fast_weight"][
184
+ "four_pairs_12_distractors"
185
+ ]["accuracy"],
186
+ "gru_accuracy": results["gru"]["four_pairs_12_distractors"][
187
+ "accuracy"
188
+ ],
189
+ "fast_weight_long_accuracy": results["fast_weight"][
190
+ "eight_pairs_64_distractors"
191
+ ]["accuracy"],
192
+ "gru_long_accuracy": results["gru"][
193
+ "eight_pairs_64_distractors"
194
+ ]["accuracy"],
195
+ }
196
+ )
197
+ trackio.finish()
198
+ print(json.dumps(report, indent=2))
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()