zeechimp commited on
Commit
fc6814c
·
verified ·
1 Parent(s): 35a68af

Create holo_working.py

Browse files
Files changed (1) hide show
  1. holo_working.py +724 -0
holo_working.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ holo-working
3
+ ============
4
+ A working memory substrate: fast buffer, slow long-term store, and
5
+ rehearsal between them.
6
+
7
+ Biological working memory has two components. A small, fast-decaying
8
+ buffer holds what is currently in mind. A wide, slow long-term store
9
+ holds everything that was ever processed. Consolidation between the
10
+ two is what turns a momentary experience into a persistent memory.
11
+
12
+ This engine implements:
13
+
14
+ - buffer trace fast decay, small capacity
15
+ - long-term trace slow decay, unbounded
16
+ - consolidation transfer from buffer to long-term each step
17
+ - attention spotlight a small set of items held in focus
18
+ - chunking bind multiple items into one buffer slot
19
+
20
+ Every readout can be taken from the buffer, the long-term store, or
21
+ the two combined. Three combined readouts are offered: sum, max, and
22
+ weighted. The choice of readout determines the shape of the resulting
23
+ recall curve.
24
+
25
+ Usage
26
+ -----
27
+
28
+ from holo_working import WorkingMemory
29
+
30
+ mem = WorkingMemory(d=2048)
31
+ for label in ["alpha", "beta", "gamma", "delta"]:
32
+ mem.present(label)
33
+ mem.step()
34
+ mem.query("alpha")
35
+
36
+ # Serial position test
37
+ scores = mem.serial_position_test(
38
+ ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
39
+ )
40
+
41
+ CLI
42
+ ---
43
+
44
+ python holo_working.py
45
+
46
+ Requires: numpy.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import argparse
52
+ import json
53
+ import os
54
+ import zlib
55
+ from dataclasses import dataclass, field, asdict
56
+ from typing import Any, Dict, List, Optional, Tuple
57
+
58
+ import numpy as np
59
+
60
+
61
+ D_DEFAULT = 2048
62
+
63
+
64
+ # ============================================================
65
+ # Primitives
66
+ # ============================================================
67
+ def rvec(seed: int, d: int = D_DEFAULT) -> np.ndarray:
68
+ r = np.random.default_rng(seed)
69
+ return np.exp(1j * r.uniform(0, 2 * np.pi, d))
70
+
71
+
72
+ def povec(seed: int, d: int = D_DEFAULT) -> np.ndarray:
73
+ v = rvec(seed, d)
74
+ F = np.fft.fft(v)
75
+ return np.fft.ifft(F / np.abs(F))
76
+
77
+
78
+ def bind(a: np.ndarray, b: np.ndarray) -> np.ndarray:
79
+ return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b))
80
+
81
+
82
+ def unbind(a: np.ndarray, c: np.ndarray) -> np.ndarray:
83
+ return np.fft.ifft(np.fft.fft(c) * np.conj(np.fft.fft(a)))
84
+
85
+
86
+ def norm(v: np.ndarray) -> np.ndarray:
87
+ F = np.fft.fft(v)
88
+ return np.fft.ifft(F / (np.abs(F) + 1e-12))
89
+
90
+
91
+ def cos(a: np.ndarray, b: np.ndarray) -> float:
92
+ na = np.linalg.norm(a)
93
+ nb = np.linalg.norm(b)
94
+ if na < 1e-12 or nb < 1e-12:
95
+ return 0.0
96
+ return float(np.real(np.vdot(a, b)) / (na * nb))
97
+
98
+
99
+ def project(u: np.ndarray, v: np.ndarray) -> float:
100
+ nv2 = float(np.real(np.vdot(v, v)))
101
+ if nv2 < 1e-12:
102
+ return 0.0
103
+ return float(np.real(np.vdot(u, v)) / nv2)
104
+
105
+
106
+ def make_vector(label: str, d: int) -> np.ndarray:
107
+ return povec(zlib.crc32(f"_::{label}".encode()) & 0xffffffff, d)
108
+
109
+
110
+ # ============================================================
111
+ # WorkingMemory
112
+ # ============================================================
113
+ class WorkingMemory:
114
+ """
115
+ A dual-store memory with fast buffer and slow long-term trace.
116
+
117
+ The buffer holds recent items with exponential decay. The long-term
118
+ trace accumulates the buffer's contents over time. Consolidation
119
+ happens at each step: a fraction of the current buffer is added to
120
+ long-term.
121
+
122
+ Attention: a small set of labels can be held in focus. Focused
123
+ items are re-added to the buffer at each step, offsetting decay.
124
+ This is a rehearsal mechanism.
125
+
126
+ Chunks: a chunk is a bound bundle of items that occupies one
127
+ buffer slot but retrieves as a unit.
128
+ """
129
+
130
+ def __init__(self,
131
+ d: int = D_DEFAULT,
132
+ buffer_decay: float = 0.85,
133
+ ltm_decay: float = 1.0,
134
+ consolidation_rate: float = 0.2,
135
+ focus_weight: float = 0.5,
136
+ threshold: float = 0.05,
137
+ max_focus: int = 4,
138
+ seed: int = 0):
139
+ self.d = d
140
+ self.buffer_decay = buffer_decay
141
+ self.ltm_decay = ltm_decay
142
+ self.consolidation_rate = consolidation_rate
143
+ self.focus_weight = focus_weight
144
+ self.threshold = threshold
145
+ self.max_focus = max_focus
146
+ self.seed = seed
147
+
148
+ self.buffer = np.zeros(d, dtype=complex)
149
+ self.ltm = np.zeros(d, dtype=complex)
150
+ self.items: Dict[str, np.ndarray] = {}
151
+ self.presented: List[str] = []
152
+ self.focused: List[str] = []
153
+ self._counter = 1
154
+ self._tick = 0
155
+
156
+ # --------------------------------------------------------
157
+ # Item access
158
+ # --------------------------------------------------------
159
+ def _vec(self, label: str) -> np.ndarray:
160
+ if label not in self.items:
161
+ v = make_vector(label, self.d)
162
+ self.items[label] = v
163
+ return self.items[label]
164
+
165
+ # --------------------------------------------------------
166
+ # Buffer mechanics
167
+ # --------------------------------------------------------
168
+ def _consolidate(self) -> None:
169
+ """Transfer a fraction of the buffer into long-term."""
170
+ self.ltm += self.consolidation_rate * self.buffer
171
+
172
+ def _decay_buffer(self) -> None:
173
+ self.buffer *= self.buffer_decay
174
+ self.ltm *= self.ltm_decay
175
+
176
+ def _rehearse_focused(self) -> None:
177
+ """Re-add focused items to the buffer at focus_weight."""
178
+ for lbl in self.focused:
179
+ v = self.items[lbl]
180
+ self.buffer += self.focus_weight * bind(v, v)
181
+
182
+ def present(self, label: str, weight: float = 1.0) -> None:
183
+ """
184
+ Present a new item. Consolidate, decay, add to buffer, and
185
+ rehearse the focus set.
186
+ """
187
+ self._tick += 1
188
+ self._consolidate()
189
+ self._decay_buffer()
190
+ v = self._vec(label)
191
+ self.buffer += weight * bind(v, v)
192
+ self._rehearse_focused()
193
+ self.presented.append(label)
194
+
195
+ def step(self) -> None:
196
+ """
197
+ Advance time without presenting a new item. Consolidate,
198
+ decay, rehearse.
199
+ """
200
+ self._tick += 1
201
+ self._consolidate()
202
+ self._decay_buffer()
203
+ self._rehearse_focused()
204
+
205
+ # --------------------------------------------------------
206
+ # Focus / attention
207
+ # --------------------------------------------------------
208
+ def focus(self, label: str) -> bool:
209
+ if label not in self.focused and len(self.focused) < self.max_focus:
210
+ self.focused.append(label)
211
+ self._vec(label) # ensure exists
212
+ return True
213
+ return False
214
+
215
+ def unfocus(self, label: str) -> None:
216
+ if label in self.focused:
217
+ self.focused.remove(label)
218
+
219
+ def clear_focus(self) -> None:
220
+ self.focused = []
221
+
222
+ # --------------------------------------------------------
223
+ # Chunking
224
+ # --------------------------------------------------------
225
+ def chunk(self, labels: List[str], name: str) -> None:
226
+ """
227
+ Bind several items into a single chunk vector. The chunk lives
228
+ in the item codebook under `name` and can be presented as one
229
+ unit. Unbinding the chunk with a role recovers the parts if a
230
+ role structure is provided; here the chunk is just a bundle,
231
+ so unbinding returns a superposition.
232
+ """
233
+ vecs = [self._vec(lb) for lb in labels]
234
+ v_chunk = norm(np.sum(vecs, axis=0))
235
+ self.items[name] = v_chunk
236
+
237
+ # --------------------------------------------------------
238
+ # Query
239
+ # --------------------------------------------------------
240
+ def query(self, label: str, source: str = "max") -> Dict:
241
+ """
242
+ Query a label against buffer and long-term.
243
+
244
+ source: "buffer", "ltm", "sum", "max", "weighted", or "auto".
245
+ auto returns the higher of the two.
246
+ """
247
+ if label not in self.items:
248
+ return {
249
+ "label": label,
250
+ "buffer_raw": 0.0,
251
+ "ltm_raw": 0.0,
252
+ "combined": 0.0,
253
+ "source": "missing",
254
+ "verdict": "UNKNOWN",
255
+ }
256
+ v = self.items[label]
257
+ buf_u = unbind(v, self.buffer)
258
+ ltm_u = unbind(v, self.ltm)
259
+ buf_raw = project(buf_u, v)
260
+ ltm_raw = project(ltm_u, v)
261
+
262
+ if source == "buffer":
263
+ combined = buf_raw
264
+ elif source == "ltm":
265
+ combined = ltm_raw
266
+ elif source == "sum":
267
+ combined = buf_raw + ltm_raw
268
+ elif source == "max":
269
+ combined = max(buf_raw, ltm_raw)
270
+ elif source == "weighted":
271
+ combined = 0.5 * buf_raw + 0.5 * ltm_raw
272
+ elif source == "auto":
273
+ if buf_raw >= self.threshold:
274
+ combined = buf_raw
275
+ source = "buffer"
276
+ else:
277
+ combined = ltm_raw
278
+ source = "ltm"
279
+ else:
280
+ combined = max(buf_raw, ltm_raw)
281
+ source = "max"
282
+
283
+ verdict = "YES" if combined >= self.threshold else "UNKNOWN"
284
+ return {
285
+ "label": label,
286
+ "buffer_raw": float(buf_raw),
287
+ "ltm_raw": float(ltm_raw),
288
+ "combined": float(combined),
289
+ "source": source,
290
+ "verdict": verdict,
291
+ }
292
+
293
+ def recall_scores(self, labels: List[str],
294
+ source: str = "max") -> List[Dict]:
295
+ return [self.query(lb, source=source) for lb in labels]
296
+
297
+ # --------------------------------------------------------
298
+ # Serial position test
299
+ # --------------------------------------------------------
300
+ def serial_position_test(self, sequence: List[str],
301
+ retention_steps: int = 0,
302
+ source: str = "max") -> Dict:
303
+ """
304
+ Present each item in sequence one at a time. Optionally run
305
+ retention steps. Then query every item and return scores by
306
+ position.
307
+ """
308
+ for lb in sequence:
309
+ self.present(lb)
310
+ for _ in range(retention_steps):
311
+ self.step()
312
+
313
+ results = []
314
+ for pos, lb in enumerate(sequence):
315
+ r = self.query(lb, source=source)
316
+ results.append({
317
+ "position": pos,
318
+ "label": lb,
319
+ "buffer_raw": r["buffer_raw"],
320
+ "ltm_raw": r["ltm_raw"],
321
+ "combined": r["combined"],
322
+ "verdict": r["verdict"],
323
+ })
324
+ return {
325
+ "sequence": list(sequence),
326
+ "retention_steps": retention_steps,
327
+ "source": source,
328
+ "results": results,
329
+ }
330
+
331
+ def print_position_curve(self, report: Dict,
332
+ width: int = 60) -> None:
333
+ results = report["results"]
334
+ max_val = max(abs(r["combined"]) for r in results) or 1.0
335
+ print(f" serial position curve "
336
+ f"(source={report['source']}, "
337
+ f"retention={report['retention_steps']}):")
338
+ print(f" {'pos':>4} {'label':>10} "
339
+ f"{'buffer':>9} {'ltm':>9} {'combined':>9} "
340
+ f"{'':>4}")
341
+ for r in results:
342
+ bar_len = int((abs(r["combined"]) / max_val) * width)
343
+ bar = "#" * bar_len
344
+ print(f" {r['position']:>4} {r['label']:>10} "
345
+ f"{r['buffer_raw']:>+9.4f} {r['ltm_raw']:>+9.4f} "
346
+ f"{r['combined']:>+9.4f} "
347
+ f"{bar}")
348
+
349
+ # --------------------------------------------------------
350
+ # Diagnostics
351
+ # --------------------------------------------------------
352
+ def stats(self) -> Dict:
353
+ return {
354
+ "d": self.d,
355
+ "buffer_decay": self.buffer_decay,
356
+ "ltm_decay": self.ltm_decay,
357
+ "consolidation_rate": self.consolidation_rate,
358
+ "n_items": len(self.items),
359
+ "n_presented": len(self.presented),
360
+ "n_focused": len(self.focused),
361
+ "focused": list(self.focused),
362
+ "tick": self._tick,
363
+ "buffer_magnitude": float(np.linalg.norm(self.buffer)),
364
+ "ltm_magnitude": float(np.linalg.norm(self.ltm)),
365
+ }
366
+
367
+ def save_json(self, path: str) -> None:
368
+ out = self.stats()
369
+ out["presented"] = list(self.presented[-200:])
370
+ out["items"] = list(self.items.keys())
371
+ with open(path, "w") as f:
372
+ json.dump(out, f, indent=2)
373
+ print(f" saved: {path}")
374
+
375
+ def reset(self) -> None:
376
+ self.buffer = np.zeros(self.d, dtype=complex)
377
+ self.ltm = np.zeros(self.d, dtype=complex)
378
+ self.items = {}
379
+ self.presented = []
380
+ self.focused = []
381
+ self._counter = 1
382
+ self._tick = 0
383
+
384
+
385
+ # ============================================================
386
+ # Helpers
387
+ # ============================================================
388
+ def section(title: str) -> None:
389
+ print()
390
+ print("=" * 78)
391
+ print(title)
392
+ print("=" * 78)
393
+
394
+
395
+ def self_test() -> bool:
396
+ print(" self-test:")
397
+ d = 2048
398
+ a = povec(1, d)
399
+ b = povec(2, d)
400
+ ok1 = cos(unbind(a, bind(a, b)), b) > 0.99
401
+ print(f" bind/unbind identity: {'PASS' if ok1 else 'FAIL'}")
402
+
403
+ bb = 0.7 * bind(a, a)
404
+ rec = project(unbind(a, bb), a)
405
+ ok2 = abs(rec - 0.7) < 0.02
406
+ print(f" raw projection: {'PASS' if ok2 else 'FAIL'}")
407
+
408
+ mem = WorkingMemory(d=d)
409
+ mem.present("alpha")
410
+ r = mem.query("alpha", source="buffer")
411
+ ok3 = r["buffer_raw"] > 0.5
412
+ print(f" buffer holds presented: {'PASS' if ok3 else 'FAIL'}")
413
+
414
+ # After decay the buffer should be lower, LTM should hold the item
415
+ for _ in range(10):
416
+ mem.step()
417
+ r2 = mem.query("alpha")
418
+ ok4 = r2["ltm_raw"] > 0.1
419
+ print(f" LTM holds after decay: {'PASS' if ok4 else 'FAIL'}")
420
+ return ok1 and ok2 and ok3 and ok4
421
+
422
+
423
+ # ============================================================
424
+ # DEMO 1. Buffer vs long-term after presentation
425
+ # ============================================================
426
+ def demo_buffer_ltm():
427
+ section("DEMO 1. BUFFER vs LONG-TERM")
428
+ mem = WorkingMemory(d=2048)
429
+ mem.present("alpha")
430
+ mem.present("beta")
431
+ mem.present("gamma")
432
+
433
+ print(" immediate query (no steps):")
434
+ for lb in ["alpha", "beta", "gamma"]:
435
+ r = mem.query(lb, source="buffer")
436
+ print(f" {lb:>6} buffer={r['buffer_raw']:+.4f}")
437
+
438
+ print()
439
+ print(" after 8 steps:")
440
+ for _ in range(8):
441
+ mem.step()
442
+ for lb in ["alpha", "beta", "gamma"]:
443
+ r = mem.query(lb)
444
+ print(f" {lb:>6} buffer={r['buffer_raw']:+.4f} "
445
+ f"ltm={r['ltm_raw']:+.4f} max={r['combined']:+.4f}")
446
+
447
+
448
+ # ============================================================
449
+ # DEMO 2. Buffer decay over time
450
+ # ============================================================
451
+ def demo_decay():
452
+ section("DEMO 2. BUFFER DECAY OVER TIME")
453
+ mem = WorkingMemory(d=2048)
454
+ mem.present("only_item")
455
+ print(f" {'steps':>6} {'buffer':>10} {'ltm':>10}")
456
+ for step in range(16):
457
+ r = mem.query("only_item")
458
+ print(f" {step:>6} {r['buffer_raw']:>10.4f} "
459
+ f"{r['ltm_raw']:>10.4f}")
460
+ mem.step()
461
+
462
+
463
+ # ============================================================
464
+ # DEMO 3. Serial position — max readout
465
+ # ============================================================
466
+ def demo_serial_max():
467
+ section("DEMO 3. SERIAL POSITION — max readout")
468
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
469
+ consolidation_rate=0.2)
470
+ seq = ["a", "b", "c", "d", "e", "f",
471
+ "g", "h", "i", "j", "k", "l"]
472
+ report = mem.serial_position_test(seq, retention_steps=0,
473
+ source="max")
474
+ mem.print_position_curve(report)
475
+
476
+
477
+ # ============================================================
478
+ # DEMO 4. Serial position — sum vs buffer vs ltm
479
+ # ============================================================
480
+ def demo_serial_readouts():
481
+ section("DEMO 4. SERIAL POSITION — sum vs buffer vs ltm")
482
+ seq = ["a", "b", "c", "d", "e", "f",
483
+ "g", "h", "i", "j", "k", "l"]
484
+ for source in ["buffer", "ltm", "sum", "max"]:
485
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
486
+ consolidation_rate=0.2)
487
+ report = mem.serial_position_test(seq, retention_steps=0,
488
+ source=source)
489
+ print(f" readout = {source}")
490
+ print(f" position: ", end="")
491
+ for r in report["results"]:
492
+ print(f"{r['position']:>6}", end="")
493
+ print()
494
+ print(f" score: ", end="")
495
+ for r in report["results"]:
496
+ print(f"{r['combined']:>6.3f}", end="")
497
+ print("\n")
498
+
499
+
500
+ # ============================================================
501
+ # DEMO 5. Retention interval effect
502
+ # ============================================================
503
+ def demo_retention():
504
+ section("DEMO 5. RETENTION INTERVAL EFFECT")
505
+ seq = ["a", "b", "c", "d", "e", "f",
506
+ "g", "h", "i", "j", "k", "l"]
507
+ print(f" {'retention':>10} recency ratio (last/mean) "
508
+ f"primacy ratio (first/mean)")
509
+ for retention in [0, 3, 10]:
510
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
511
+ consolidation_rate=0.2)
512
+ report = mem.serial_position_test(seq,
513
+ retention_steps=retention,
514
+ source="max")
515
+ scores = [r["combined"] for r in report["results"]]
516
+ mean_s = np.mean(scores) + 1e-9
517
+ recency = scores[-1] / mean_s
518
+ primacy = scores[0] / mean_s
519
+ print(f" {retention:>10} {recency:>24.3f} "
520
+ f"{primacy:>22.3f}")
521
+
522
+
523
+ # ============================================================
524
+ # DEMO 6. Buffer decay parameter
525
+ # ============================================================
526
+ def demo_decay_param():
527
+ section("DEMO 6. BUFFER DECAY PARAMETER")
528
+ seq = ["a", "b", "c", "d", "e", "f",
529
+ "g", "h", "i", "j", "k", "l"]
530
+ print(f" {'decay':>6} {'recency/mean':>14} "
531
+ f"{'middle/mean':>13} {'primacy/mean':>14}")
532
+ for decay in [0.6, 0.75, 0.85, 0.92, 0.98]:
533
+ mem = WorkingMemory(d=2048, buffer_decay=decay,
534
+ consolidation_rate=0.2)
535
+ report = mem.serial_position_test(seq, source="max")
536
+ scores = np.array([r["combined"] for r in report["results"]])
537
+ mean_s = scores.mean() + 1e-9
538
+ print(f" {decay:>6.2f} "
539
+ f"{scores[-1] / mean_s:>14.3f} "
540
+ f"{scores[len(scores) // 2] / mean_s:>13.3f} "
541
+ f"{scores[0] / mean_s:>14.3f}")
542
+
543
+
544
+ # ============================================================
545
+ # DEMO 7. Consolidation rate parameter
546
+ # ============================================================
547
+ def demo_consolidation_param():
548
+ section("DEMO 7. CONSOLIDATION RATE PARAMETER")
549
+ seq = ["a", "b", "c", "d", "e", "f",
550
+ "g", "h", "i", "j", "k", "l"]
551
+ print(f" {'consol':>6} {'recency/mean':>14} "
552
+ f"{'middle/mean':>13} {'primacy/mean':>14}")
553
+ for consol in [0.02, 0.05, 0.1, 0.2, 0.4]:
554
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
555
+ consolidation_rate=consol)
556
+ report = mem.serial_position_test(seq, source="max")
557
+ scores = np.array([r["combined"] for r in report["results"]])
558
+ mean_s = scores.mean() + 1e-9
559
+ print(f" {consol:>6.2f} "
560
+ f"{scores[-1] / mean_s:>14.3f} "
561
+ f"{scores[len(scores) // 2] / mean_s:>13.3f} "
562
+ f"{scores[0] / mean_s:>14.3f}")
563
+
564
+
565
+ # ============================================================
566
+ # DEMO 8. Attention spotlight
567
+ # ============================================================
568
+ def demo_attention():
569
+ section("DEMO 8. ATTENTION SPOTLIGHT")
570
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
571
+ consolidation_rate=0.2)
572
+ seq = ["a", "b", "c", "d", "e", "f",
573
+ "g", "h", "i", "j", "k", "l"]
574
+ # Hold c and j in focus through the sequence
575
+ mem.focus("c")
576
+ mem.focus("j")
577
+
578
+ report = mem.serial_position_test(seq, source="max")
579
+ print(" focused: c (pos 2) and j (pos 9)")
580
+ mem.print_position_curve(report)
581
+
582
+ print()
583
+ print(" focused items keep high scores at their positions")
584
+ print(" compared to neighbors without focus.")
585
+
586
+
587
+ # ============================================================
588
+ # DEMO 9. Chunking
589
+ # ============================================================
590
+ def demo_chunking():
591
+ section("DEMO 9. CHUNKING")
592
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
593
+ consolidation_rate=0.2)
594
+ # Without chunking: 8 items in a row
595
+ for lb in ["a1", "a2", "a3", "a4", "b1", "b2", "b3", "b4"]:
596
+ mem.present(lb)
597
+ print(" without chunking, buffer scores for positions 0 and 4:")
598
+ for lb in ["a1", "b1"]:
599
+ r = mem.query(lb)
600
+ print(f" {lb}: buffer={r['buffer_raw']:+.4f} "
601
+ f"ltm={r['ltm_raw']:+.4f}")
602
+
603
+ print()
604
+ # With chunking: bind a1..a4 into a chunk, present chunk instead
605
+ mem2 = WorkingMemory(d=2048, buffer_decay=0.85,
606
+ consolidation_rate=0.2)
607
+ mem2.chunk(["a1", "a2", "a3", "a4"], "chunk_A")
608
+ mem2.chunk(["b1", "b2", "b3", "b4"], "chunk_B")
609
+ for lb in ["chunk_A", "chunk_B"]:
610
+ mem2.present(lb)
611
+ print(" with chunking, buffer scores for chunks:")
612
+ for lb in ["chunk_A", "chunk_B"]:
613
+ r = mem2.query(lb)
614
+ print(f" {lb}: buffer={r['buffer_raw']:+.4f} "
615
+ f"ltm={r['ltm_raw']:+.4f}")
616
+ print()
617
+ print(" chunking lets 8 items fit in 2 buffer slots at full strength.")
618
+
619
+
620
+ # ============================================================
621
+ # DEMO 10. Two buffers in one substrate
622
+ # ============================================================
623
+ def demo_two_streams():
624
+ section("DEMO 10. TWO INTERLEAVED STREAMS")
625
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
626
+ consolidation_rate=0.2)
627
+ # Present two streams interleaved
628
+ for i in range(6):
629
+ mem.present(f"L_{i}")
630
+ mem.present(f"R_{i}")
631
+ # Query both streams
632
+ print(f" {'label':>6} {'buffer':>10} {'ltm':>10} {'max':>10}")
633
+ for i in range(6):
634
+ for side in ["L", "R"]:
635
+ r = mem.query(f"{side}_{i}")
636
+ print(f" {side}_{i}: {r['buffer_raw']:>+10.4f} "
637
+ f"{r['ltm_raw']:>+10.4f} "
638
+ f"{r['combined']:>+10.4f}")
639
+ print()
640
+ print(" interleaving two streams shows how the buffer treats")
641
+ print(" items from both sources evenly by recency.")
642
+
643
+
644
+ # ============================================================
645
+ # Main
646
+ # ============================================================
647
+ def run_all_demos(output_dir: str = "holo_working_out") -> None:
648
+ os.makedirs(output_dir, exist_ok=True)
649
+ print("=" * 78)
650
+ print("HOLO-WORKING")
651
+ print("A working memory substrate: fast buffer, slow long-term,")
652
+ print("and rehearsal between them.")
653
+ print("=" * 78)
654
+
655
+ demos = [
656
+ demo_buffer_ltm,
657
+ demo_decay,
658
+ demo_serial_max,
659
+ demo_serial_readouts,
660
+ demo_retention,
661
+ demo_decay_param,
662
+ demo_consolidation_param,
663
+ demo_attention,
664
+ demo_chunking,
665
+ demo_two_streams,
666
+ ]
667
+ for d in demos:
668
+ try:
669
+ d()
670
+ except Exception as e:
671
+ print(f" EXCEPTION in {d.__name__}: {e}")
672
+
673
+ section("OUTPUT")
674
+ mem = WorkingMemory(d=2048)
675
+ for i in range(10):
676
+ mem.present(f"item_{i}")
677
+ mem.focus("item_3")
678
+ mem.step()
679
+ mem.save_json(os.path.join(output_dir, "state.json"))
680
+
681
+ print()
682
+ print("=" * 78)
683
+ print(f"All outputs saved to: {output_dir}/")
684
+ print("=" * 78)
685
+
686
+
687
+ def main() -> None:
688
+ parser = argparse.ArgumentParser(
689
+ description="A working memory substrate with buffer and "
690
+ "long-term stores.",
691
+ formatter_class=argparse.RawDescriptionHelpFormatter,
692
+ epilog="""
693
+ Library usage:
694
+
695
+ from holo_working import WorkingMemory
696
+
697
+ mem = WorkingMemory(d=2048, buffer_decay=0.85,
698
+ consolidation_rate=0.2)
699
+ mem.present("alpha")
700
+ mem.present("beta")
701
+ mem.step()
702
+ print(mem.query("alpha"))
703
+
704
+ # Serial position
705
+ report = mem.serial_position_test(
706
+ ["a", "b", "c", "d", "e", "f", "g", "h"]
707
+ )
708
+ mem.print_position_curve(report)
709
+ """)
710
+ parser.add_argument("--output", default="holo_working_out",
711
+ help="output directory (default: holo_working_out)")
712
+ args = parser.parse_args()
713
+
714
+ print("=" * 78)
715
+ print("SELF-TEST")
716
+ print("=" * 78)
717
+ if not self_test():
718
+ print(" primitive test failed; continuing anyway")
719
+
720
+ run_all_demos(output_dir=args.output)
721
+
722
+
723
+ if __name__ == "__main__":
724
+ main()