CharlesCNorton commited on
Commit
6e3b69a
·
1 Parent(s): 3615a51

Add CPU program suite and fix CALL / V-flag handling

Browse files

cpu_programs.py provides a small assembler and seven programs that
exercise the ISA end-to-end: iterative Fibonacci, sum 1..N (Z-flag
termination), self-modifying JMP (STORE into a JMP's address word),
all eight conditional jumps, CALL stack semantics, bubble sort, and
MUL cross-checked against repeated ADD.

test_cpu.py runs the suite against any variant. All seven programs
pass on every memory profile from 256 B (scratchpad) through 64 KB
(canonical), 32-bit data path included.

eval_all.py: GenericThresholdCPU previously treated CALL (opcode 0xE)
as a NOP because the case fell through the dispatch table. Added the
push-return-PC + SP behavior and SP support in the state dict.

eval_all.py: ADD / SUB / CMP now set the V (overflow) flag correctly
using the standard two's-complement signed-overflow tests; previously
V was always zero, so JV / JNV could never take.

Files changed (4) hide show
  1. README.md +13 -1
  2. cpu_programs.py +518 -0
  3. eval_all.py +16 -2
  4. test_cpu.py +138 -0
README.md CHANGED
@@ -72,6 +72,16 @@ python play.py # 1 KB demo, runs in s
72
  python play.py --model neural_computer.safetensors # 64 KB, slower
73
  ```
74
 
 
 
 
 
 
 
 
 
 
 
75
  ---
76
 
77
  ## Execution model
@@ -429,7 +439,9 @@ variants/ 18 prebuilt configurations
429
  build.py generator (one safetensors per invocation)
430
  build_all.py builds and verifies every named profile
431
  eval.py gate-level fitness suite + reference CPU runtime
432
- eval_all.py variant-agnostic harness (recommended)
 
 
433
  play.py interactive demo
434
  prune_weights.py GPU-batched weight reduction with conflict resolution
435
  llm_integration/ SmolLM2 extractor + circuit wrapper + training code
 
72
  python play.py --model neural_computer.safetensors # 64 KB, slower
73
  ```
74
 
75
+ For end-to-end CPU validation (Fibonacci, sum 1..N, bubble sort, self-modifying JMP, all eight conditional jumps, CALL stack semantics, MUL cross-checked against repeated ADD):
76
+
77
+ ```bash
78
+ python test_cpu.py # default: 1 KB, ~2 s
79
+ python test_cpu.py --model neural_computer.safetensors # 64 KB canonical, ~100 s
80
+ python test_cpu.py --only fib,sum_n # subset of suite
81
+ ```
82
+
83
+ Each program is assembled by a small Python assembler (`cpu_programs.py`) and run through the threshold-gated CPU; the driver verifies expected memory contents at HALT.
84
+
85
  ---
86
 
87
  ## Execution model
 
439
  build.py generator (one safetensors per invocation)
440
  build_all.py builds and verifies every named profile
441
  eval.py gate-level fitness suite + reference CPU runtime
442
+ eval_all.py variant-agnostic gate-level harness
443
+ cpu_programs.py assembler + program suite for CPU-level validation
444
+ test_cpu.py runs the program suite against a chosen variant
445
  play.py interactive demo
446
  prune_weights.py GPU-batched weight reduction with conflict resolution
447
  llm_integration/ SmolLM2 extractor + circuit wrapper + training code
cpu_programs.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CPU validation programs for the threshold computer.
3
+
4
+ A small assembler and a suite of programs that exercise the ISA end-to-end:
5
+ arithmetic, control flow, memory access, self-modifying code, all eight
6
+ conditional jumps, the call mechanism, and a sort.
7
+
8
+ Each program returns (mem, expected, max_cycles, description) where:
9
+ mem : list[int] -- complete memory image
10
+ expected : dict[int, int] -- {address: expected_value} verified at HALT
11
+ max_cycles : int -- cycle budget (an infinite loop will hit this)
12
+ description: str -- short human-readable summary
13
+
14
+ Programs target the 1 KB profile (addr_bits=10) by default but use only the
15
+ low 256 bytes so they also run on scratchpad and larger profiles.
16
+
17
+ All programs assume the CPU starts with PC=0, SP defaulting to addr_mask
18
+ (highest address; CALL pre-decrements before writing).
19
+ """
20
+
21
+ from __future__ import annotations
22
+ from typing import Dict, List, Tuple
23
+
24
+
25
+ # ----------------------------------------------------------------------------
26
+ # Mini assembler
27
+ # ----------------------------------------------------------------------------
28
+
29
+ _OPCODE_NAMES = {
30
+ "add": 0x0, "sub": 0x1, "and": 0x2, "or": 0x3, "xor": 0x4,
31
+ "shl": 0x5, "shr": 0x6, "mul": 0x7, "div": 0x8, "cmp": 0x9,
32
+ "load": 0xA, "store": 0xB, "jmp": 0xC, "jcc": 0xD,
33
+ "call": 0xE, "halt": 0xF,
34
+ }
35
+
36
+ _COND = {"jz": 0, "jnz": 1, "jc": 2, "jnc": 3,
37
+ "jn": 4, "jp": 5, "jv": 6, "jnv": 7}
38
+
39
+
40
+ def _enc(opcode: int, rd: int = 0, rs: int = 0, imm: int = 0) -> int:
41
+ return ((opcode & 0xF) << 12) | ((rd & 0x3) << 10) | ((rs & 0x3) << 8) | (imm & 0xFF)
42
+
43
+
44
+ class Asm:
45
+ """Tiny assembler for the threshold-computer ISA.
46
+
47
+ Usage:
48
+ a = Asm(size=256)
49
+ a.org(0)
50
+ a.label("start")
51
+ a.load(0, "data")
52
+ a.halt()
53
+ a.org(0x80); a.label("data"); a.db(42)
54
+ mem = a.assemble()
55
+ """
56
+
57
+ def __init__(self, size: int):
58
+ self.mem: List[int] = [0] * size
59
+ self.pc: int = 0
60
+ self.labels: Dict[str, int] = {}
61
+ self.fixups: List[Tuple[int, str]] = []
62
+
63
+ def org(self, addr: int) -> None:
64
+ self.pc = addr
65
+
66
+ def label(self, name: str) -> None:
67
+ if name in self.labels:
68
+ raise ValueError(f"duplicate label: {name}")
69
+ self.labels[name] = self.pc
70
+
71
+ def db(self, *values: int) -> None:
72
+ for v in values:
73
+ self.mem[self.pc] = v & 0xFF
74
+ self.pc += 1
75
+
76
+ def dw(self, value: int) -> None:
77
+ self.mem[self.pc] = (value >> 8) & 0xFF
78
+ self.mem[self.pc + 1] = value & 0xFF
79
+ self.pc += 2
80
+
81
+ def daddr(self, label: str) -> None:
82
+ self.fixups.append((self.pc, label))
83
+ self.dw(0)
84
+
85
+ # --- ALU ops (no immediate) ---
86
+ def _alu(self, op: int, rd: int, rs: int) -> None:
87
+ self.dw(_enc(op, rd, rs))
88
+
89
+ def add(self, rd: int, rs: int) -> None: self._alu(0x0, rd, rs)
90
+ def sub(self, rd: int, rs: int) -> None: self._alu(0x1, rd, rs)
91
+ def and_(self, rd: int, rs: int) -> None: self._alu(0x2, rd, rs)
92
+ def or_(self, rd: int, rs: int) -> None: self._alu(0x3, rd, rs)
93
+ def xor(self, rd: int, rs: int) -> None: self._alu(0x4, rd, rs)
94
+ def shl(self, rd: int) -> None: self._alu(0x5, rd, 0)
95
+ def shr(self, rd: int) -> None: self._alu(0x6, rd, 0)
96
+ def mul(self, rd: int, rs: int) -> None: self._alu(0x7, rd, rs)
97
+ def cmp(self, rd: int, rs: int) -> None: self._alu(0x9, rd, rs)
98
+
99
+ # --- Memory + control (address-extended) ---
100
+ def load(self, rd: int, label: str) -> None:
101
+ self.dw(_enc(0xA, rd, 0)); self.daddr(label)
102
+
103
+ def store(self, rs: int, label: str) -> None:
104
+ self.dw(_enc(0xB, 0, rs)); self.daddr(label)
105
+
106
+ def jmp(self, label: str) -> None:
107
+ self.dw(_enc(0xC)); self.daddr(label)
108
+
109
+ def jcc(self, cond: str, label: str) -> None:
110
+ self.dw(_enc(0xD, 0, 0, _COND[cond])); self.daddr(label)
111
+
112
+ def jz(self, label: str) -> None: self.jcc("jz", label)
113
+ def jnz(self, label: str) -> None: self.jcc("jnz", label)
114
+ def jc(self, label: str) -> None: self.jcc("jc", label)
115
+ def jnc(self, label: str) -> None: self.jcc("jnc", label)
116
+ def jn(self, label: str) -> None: self.jcc("jn", label)
117
+ def jp(self, label: str) -> None: self.jcc("jp", label)
118
+ def jv(self, label: str) -> None: self.jcc("jv", label)
119
+ def jnv(self, label: str) -> None: self.jcc("jnv", label)
120
+
121
+ def call(self, label: str) -> None:
122
+ self.dw(_enc(0xE)); self.daddr(label)
123
+
124
+ def halt(self) -> None:
125
+ self.dw(_enc(0xF))
126
+
127
+ def assemble(self) -> List[int]:
128
+ for offset, label in self.fixups:
129
+ if label not in self.labels:
130
+ raise ValueError(f"undefined label: {label}")
131
+ target = self.labels[label]
132
+ self.mem[offset] = (target >> 8) & 0xFF
133
+ self.mem[offset + 1] = target & 0xFF
134
+ return self.mem
135
+
136
+
137
+ # ----------------------------------------------------------------------------
138
+ # Programs
139
+ # ----------------------------------------------------------------------------
140
+
141
+ ProgramResult = Tuple[List[int], Dict[int, int], int, str]
142
+
143
+
144
+ def fib(n: int = 11, mem_size: int = 256) -> ProgramResult:
145
+ """Iterative Fibonacci F(N), 8-bit wrap.
146
+
147
+ F(11) = 89. F(13) = 233 still fits in 8 bits; F(14) = 377 overflows.
148
+
149
+ Algorithm: maintain (a, b) = (F(k), F(k+1)); after N steps a = F(N).
150
+ Per iteration: temp=b, b=a+b, a=temp; n--.
151
+ """
152
+ a = Asm(mem_size)
153
+
154
+ a.org(0)
155
+ a.load(2, "n_addr") # R2 = n
156
+ a.load(0, "zero_addr") # R0 = 0 = F(0)
157
+ a.load(1, "one_addr") # R1 = 1 = F(1)
158
+ a.label("loop")
159
+ a.load(3, "zero_addr") # R3 = 0
160
+ a.cmp(2, 3) # n == 0?
161
+ a.jz("done")
162
+ a.load(3, "zero_addr") # R3 = 0
163
+ a.add(3, 1) # R3 = b (saved old b)
164
+ a.add(1, 0) # R1 = a + b (new b)
165
+ a.load(0, "zero_addr") # R0 = 0
166
+ a.add(0, 3) # R0 = old b (new a)
167
+ a.load(3, "one_addr") # R3 = 1
168
+ a.sub(2, 3) # n--
169
+ a.jmp("loop")
170
+ a.label("done")
171
+ a.store(0, "out") # OUT = a
172
+ a.halt()
173
+
174
+ a.org(0x80)
175
+ a.label("zero_addr"); a.db(0)
176
+ a.label("one_addr"); a.db(1)
177
+ a.label("n_addr"); a.db(n)
178
+ a.label("out"); a.db(0)
179
+
180
+ mem = a.assemble()
181
+ expected_a = 0
182
+ aa, bb = 0, 1
183
+ for _ in range(n):
184
+ aa, bb = bb, (aa + bb) & 0xFF
185
+ expected_a = aa
186
+ return mem, {a.labels["out"]: expected_a}, 16 * (n + 2), f"Fibonacci F({n}) = {expected_a}"
187
+
188
+
189
+ def sum_n(n: int = 10, mem_size: int = 256) -> ProgramResult:
190
+ """Compute 1 + 2 + ... + N using the Z flag from SUB to terminate.
191
+
192
+ No explicit zero register required; SUB sets Z when its result is zero.
193
+ R0 = accumulator, R1 = counter (n down to 1), R2 = 1.
194
+ """
195
+ a = Asm(mem_size)
196
+
197
+ a.org(0)
198
+ a.load(0, "zero_addr") # acc = 0
199
+ a.load(1, "n_addr") # i = n
200
+ a.load(2, "one_addr") # 1
201
+ a.label("loop")
202
+ a.add(0, 1) # acc += i
203
+ a.sub(1, 2) # i-- (Z set when i becomes 0)
204
+ a.jnz("loop")
205
+ a.store(0, "out")
206
+ a.halt()
207
+
208
+ a.org(0x80)
209
+ a.label("zero_addr"); a.db(0)
210
+ a.label("one_addr"); a.db(1)
211
+ a.label("n_addr"); a.db(n)
212
+ a.label("out"); a.db(0)
213
+
214
+ mem = a.assemble()
215
+ expected = (n * (n + 1) // 2) & 0xFF
216
+ return mem, {a.labels["out"]: expected}, 4 + 4 * n, f"sum 1..{n} = {expected}"
217
+
218
+
219
+ def self_mod_jmp(mem_size: int = 256) -> ProgramResult:
220
+ """Self-modifying code: writes the JMP target's low byte at runtime.
221
+
222
+ Initial JMP target is path_a (writes 0xAA to OUT). The code first
223
+ overwrites the JMP's address-word LSB so it points to path_b
224
+ (writes 0xBB). Successful execution lands at path_b, so OUT = 0xBB.
225
+ """
226
+ a = Asm(mem_size)
227
+
228
+ a.org(0)
229
+ a.label("start")
230
+
231
+ # Forward-declare the_jmp's LSB address. The first two instructions are
232
+ # each 4 bytes; the_jmp follows them, so the_jmp = pc + 8 from start.
233
+ # The JMP's address word is at the_jmp + 2; the LSB byte is at the_jmp + 3.
234
+ a.labels["jmp_target_lsb"] = a.pc + 8 + 3
235
+
236
+ a.load(0, "new_lsb") # R0 = LSB of path_b address (4 bytes)
237
+ a.store(0, "jmp_target_lsb") # patch the JMP's LSB (4 bytes)
238
+ a.label("the_jmp")
239
+ a.jmp("path_a") # initially -> path_a; after patch -> path_b
240
+ a.label("path_a")
241
+ a.load(1, "val_a"); a.store(1, "out"); a.halt()
242
+ a.label("path_b")
243
+ a.load(1, "val_b"); a.store(1, "out"); a.halt()
244
+
245
+ a.org(0x80)
246
+ a.label("val_a"); a.db(0xAA)
247
+ a.label("val_b"); a.db(0xBB)
248
+ # new_lsb_word stores path_b's full 16-bit address; new_lsb labels the LSB byte.
249
+ a.label("new_lsb_word"); a.daddr("path_b")
250
+ a.labels["new_lsb"] = a.labels["new_lsb_word"] + 1
251
+ a.label("out"); a.db(0)
252
+
253
+ mem = a.assemble()
254
+ return mem, {a.labels["out"]: 0xBB}, 30, "self-modifying JMP target"
255
+
256
+
257
+ def all_branches(mem_size: int = 256) -> ProgramResult:
258
+ """Drive all eight conditional jumps; each path writes a unique marker.
259
+
260
+ Test plan (each step sets flags, then a Jcc; the branch takes when
261
+ expected and the corresponding marker is written):
262
+
263
+ JZ: CMP equal -> Z=1 -> taken -> M[OUT0] = 0xA0
264
+ JNZ: CMP unequal -> Z=0 -> taken -> M[OUT1] = 0xA1
265
+ JC: ADD overflow (255+1) -> C=1 -> taken -> M[OUT2] = 0xA2
266
+ JNC: ADD no overflow -> C=0 -> taken -> M[OUT3] = 0xA3
267
+ JN: SUB result 0xFF (n=1) -> N=1 -> taken -> M[OUT4] = 0xA4
268
+ JP: ADD result 1 -> N=0 -> taken -> M[OUT5] = 0xA5
269
+ JV: ADD signed overflow (127+1=128) -> V=1 -> taken -> M[OUT6] = 0xA6
270
+ JNV: ADD no signed overflow (1+1=2) -> V=0 -> taken -> M[OUT7] = 0xA7
271
+
272
+ A failure on any branch causes the wrong (or no) marker to be written.
273
+ """
274
+ a = Asm(mem_size)
275
+
276
+ a.org(0)
277
+ # ----- JZ: equal compare -> Z=1 -----
278
+ a.load(0, "v5"); a.load(1, "v5"); a.cmp(0, 1); a.jz("ok_jz"); a.jmp("fail")
279
+ a.label("ok_jz"); a.load(2, "m_a0"); a.store(2, "out0")
280
+
281
+ # ----- JNZ: unequal compare -> Z=0 -----
282
+ a.load(0, "v5"); a.load(1, "v3"); a.cmp(0, 1); a.jnz("ok_jnz"); a.jmp("fail")
283
+ a.label("ok_jnz"); a.load(2, "m_a1"); a.store(2, "out1")
284
+
285
+ # ----- JC: 255+1 = 0 with carry -----
286
+ a.load(0, "v255"); a.load(1, "v1"); a.add(0, 1); a.jc("ok_jc"); a.jmp("fail")
287
+ a.label("ok_jc"); a.load(2, "m_a2"); a.store(2, "out2")
288
+
289
+ # ----- JNC: 1+1 = 2, no carry -----
290
+ a.load(0, "v1"); a.load(1, "v1"); a.add(0, 1); a.jnc("ok_jnc"); a.jmp("fail")
291
+ a.label("ok_jnc"); a.load(2, "m_a3"); a.store(2, "out3")
292
+
293
+ # ----- JN: 0 - 1 = 0xFF, MSB set -----
294
+ a.load(0, "v0"); a.load(1, "v1"); a.sub(0, 1); a.jn("ok_jn"); a.jmp("fail")
295
+ a.label("ok_jn"); a.load(2, "m_a4"); a.store(2, "out4")
296
+
297
+ # ----- JP: 0 + 1 = 1, MSB clear -----
298
+ a.load(0, "v0"); a.load(1, "v1"); a.add(0, 1); a.jp("ok_jp"); a.jmp("fail")
299
+ a.label("ok_jp"); a.load(2, "m_a5"); a.store(2, "out5")
300
+
301
+ # ----- JV: 127 + 1 = 128, signed overflow -----
302
+ a.load(0, "v127"); a.load(1, "v1"); a.add(0, 1); a.jv("ok_jv"); a.jmp("fail")
303
+ a.label("ok_jv"); a.load(2, "m_a6"); a.store(2, "out6")
304
+
305
+ # ----- JNV: 1 + 1 = 2, no signed overflow -----
306
+ a.load(0, "v1"); a.load(1, "v1"); a.add(0, 1); a.jnv("ok_jnv"); a.jmp("fail")
307
+ a.label("ok_jnv"); a.load(2, "m_a7"); a.store(2, "out7")
308
+
309
+ a.jmp("end")
310
+ a.label("fail")
311
+ a.load(2, "v_fail"); a.store(2, "fail_addr"); a.halt()
312
+ a.label("end")
313
+ a.halt()
314
+
315
+ # Code runs to ~0xDF; data starts safely after that.
316
+ a.org(0xE0)
317
+ a.label("v0"); a.db(0)
318
+ a.label("v1"); a.db(1)
319
+ a.label("v3"); a.db(3)
320
+ a.label("v5"); a.db(5)
321
+ a.label("v127"); a.db(127)
322
+ a.label("v255"); a.db(255)
323
+ a.label("m_a0"); a.db(0xA0)
324
+ a.label("m_a1"); a.db(0xA1)
325
+ a.label("m_a2"); a.db(0xA2)
326
+ a.label("m_a3"); a.db(0xA3)
327
+ a.label("m_a4"); a.db(0xA4)
328
+ a.label("m_a5"); a.db(0xA5)
329
+ a.label("m_a6"); a.db(0xA6)
330
+ a.label("m_a7"); a.db(0xA7)
331
+ a.label("v_fail"); a.db(0xEE)
332
+ a.label("out0"); a.db(0)
333
+ a.label("out1"); a.db(0)
334
+ a.label("out2"); a.db(0)
335
+ a.label("out3"); a.db(0)
336
+ a.label("out4"); a.db(0)
337
+ a.label("out5"); a.db(0)
338
+ a.label("out6"); a.db(0)
339
+ a.label("out7"); a.db(0)
340
+ a.label("fail_addr"); a.db(0)
341
+
342
+ mem = a.assemble()
343
+ expected = {
344
+ a.labels["out0"]: 0xA0,
345
+ a.labels["out1"]: 0xA1,
346
+ a.labels["out2"]: 0xA2,
347
+ a.labels["out3"]: 0xA3,
348
+ a.labels["out4"]: 0xA4,
349
+ a.labels["out5"]: 0xA5,
350
+ a.labels["out6"]: 0xA6,
351
+ a.labels["out7"]: 0xA7,
352
+ a.labels["fail_addr"]: 0, # must remain zero
353
+ }
354
+ return mem, expected, 200, "all 8 conditional jumps (JZ/JNZ/JC/JNC/JN/JP/JV/JNV)"
355
+
356
+
357
+ def call_pushes_pc(mem_size: int = 256) -> ProgramResult:
358
+ """Verify CALL pushes the return address (next-instruction PC) onto the stack.
359
+
360
+ SP starts at addr_mask (mem_size - 1). CALL decrements SP and writes the
361
+ return-address high byte, decrements again and writes the low byte. After
362
+ HALT we expect:
363
+ - mem[addr_mask - 2] = low byte of the return address
364
+ - mem[addr_mask - 1] = high byte of the return address
365
+ - the no-return code path was NOT taken
366
+ - the callee was reached
367
+ """
368
+ a = Asm(mem_size)
369
+
370
+ a.org(0)
371
+ a.label("caller")
372
+ a.load(0, "marker_val")
373
+ a.store(0, "marker_addr") # write before CALL
374
+ a.label("call_site")
375
+ a.call("callee")
376
+ # If CALL did not transfer control, this fallthrough store would write 0xDD:
377
+ a.load(0, "noret_val")
378
+ a.store(0, "noret_addr")
379
+ a.halt()
380
+
381
+ a.label("callee")
382
+ a.load(0, "callee_val")
383
+ a.store(0, "callee_addr")
384
+ a.halt()
385
+
386
+ a.org(0x40)
387
+ a.label("marker_val"); a.db(0x11)
388
+ a.label("marker_addr"); a.db(0)
389
+ a.label("noret_val"); a.db(0xDD)
390
+ a.label("noret_addr"); a.db(0)
391
+ a.label("callee_val"); a.db(0x22)
392
+ a.label("callee_addr"); a.db(0)
393
+
394
+ mem = a.assemble()
395
+ addr_mask = mem_size - 1
396
+ return_addr = a.labels["call_site"] + 4 # 4-byte CALL instruction
397
+ expected = {
398
+ a.labels["marker_addr"]: 0x11, # pre-CALL store ran
399
+ a.labels["callee_addr"]: 0x22, # callee reached
400
+ a.labels["noret_addr"]: 0, # fallthrough did not run
401
+ (addr_mask - 2) & addr_mask: return_addr & 0xFF, # ret LSB on stack
402
+ (addr_mask - 1) & addr_mask: (return_addr >> 8) & 0xFF, # ret MSB
403
+ }
404
+ return mem, expected, 30, "CALL pushes return PC onto stack"
405
+
406
+
407
+ def bubble_sort_4(mem_size: int = 256) -> ProgramResult:
408
+ """Sort a 4-byte array using unrolled compare-swap (3 passes of 3 compares).
409
+
410
+ Algorithm: bubble sort, fully unrolled (no inner loops). Each compare-swap
411
+ is 8 instructions; 3 outer passes x 3 inner positions = 9 swaps -> ~72 instrs.
412
+
413
+ For each position i in (0,1,2):
414
+ if A[i] > A[i+1]:
415
+ tmp = A[i]; A[i] = A[i+1]; A[i+1] = tmp
416
+ Repeat 3 times -> sorted ascending.
417
+ """
418
+ a = Asm(mem_size)
419
+
420
+ addrs = ["a0", "a1", "a2", "a3"]
421
+
422
+ a.org(0)
423
+ for _outer in range(3):
424
+ for i in range(3):
425
+ x, y = addrs[i], addrs[i + 1]
426
+ # Load pair
427
+ a.load(0, x) # R0 = A[i]
428
+ a.load(1, y) # R1 = A[i+1]
429
+ a.cmp(0, 1) # compare A[i] - A[i+1]
430
+ # If A[i] <= A[i+1] (Z=1 or C=0 from sub-style cmp), skip swap
431
+ # SUB sets carry when no borrow (a >= b). So:
432
+ # a > b iff Z=0 and a >= b -> Z=0 and C=1 (the sub didn't borrow)
433
+ # We want to swap when a > b. JNC (no carry / borrow) means a < b -> skip swap.
434
+ # If a == b (Z=1) we also skip. So: jump-skip when JZ OR JNC.
435
+ # Easier: compute (a > b) by checking C=1 AND Z=0. Use JZ to skip on equal,
436
+ # then JNC to skip on a < b. Otherwise fall through to swap.
437
+ skip_lbl = f"skip_{_outer}_{i}"
438
+ a.jz(skip_lbl) # equal -> skip
439
+ a.jnc(skip_lbl) # a < b (sub borrowed) -> skip
440
+ # swap: store R0 -> y, R1 -> x
441
+ a.store(1, x)
442
+ a.store(0, y)
443
+ a.label(skip_lbl)
444
+ a.halt()
445
+
446
+ # Initial unsorted array; code runs to ~0xEC, so data starts at 0xF0.
447
+ initial = [42, 7, 200, 19]
448
+ a.org(0xF0)
449
+ for name, val in zip(addrs, initial):
450
+ a.label(name); a.db(val)
451
+
452
+ mem = a.assemble()
453
+ sorted_vals = sorted(initial)
454
+ expected = {a.labels[name]: v for name, v in zip(addrs, sorted_vals)}
455
+ return mem, expected, 800, f"bubble sort {initial} -> {sorted_vals}"
456
+
457
+
458
+ def cross_check_mul(mem_size: int = 256) -> ProgramResult:
459
+ """Cross-check the threshold MUL circuit against repeated ADD.
460
+
461
+ Multiplies A * B two ways:
462
+ 1. R0 = A; ADD R0, B repeatedly B times. Stored at OUT_ADD.
463
+ Wait that gives A*(B+1) actually... let me rewrite.
464
+
465
+ Use:
466
+ acc = 0; for i in 0..B-1: acc += A; -> acc = A*B
467
+ direct: R0 = A; MUL R0, R1 (R1 = B); -> R0 = A*B
468
+ Compare both at OUT.
469
+ """
470
+ a = Asm(mem_size)
471
+ A_VAL = 17
472
+ B_VAL = 9
473
+ expected_product = (A_VAL * B_VAL) & 0xFF
474
+
475
+ a.org(0)
476
+ # --- direct multiply ---
477
+ a.load(0, "A")
478
+ a.load(1, "B")
479
+ a.mul(0, 1)
480
+ a.store(0, "out_mul")
481
+ # --- repeated-add multiply ---
482
+ a.load(0, "zero") # acc = 0
483
+ a.load(1, "A") # addend
484
+ a.load(2, "B") # counter
485
+ a.load(3, "one") # 1
486
+ a.label("rep_loop")
487
+ a.add(0, 1) # acc += A
488
+ a.sub(2, 3) # B--
489
+ a.jnz("rep_loop")
490
+ a.store(0, "out_add")
491
+ a.halt()
492
+
493
+ a.org(0x80)
494
+ a.label("A"); a.db(A_VAL)
495
+ a.label("B"); a.db(B_VAL)
496
+ a.label("zero"); a.db(0)
497
+ a.label("one"); a.db(1)
498
+ a.label("out_mul"); a.db(0)
499
+ a.label("out_add"); a.db(0)
500
+
501
+ mem = a.assemble()
502
+ expected = {
503
+ a.labels["out_mul"]: expected_product,
504
+ a.labels["out_add"]: expected_product,
505
+ }
506
+ return mem, expected, 80, f"MUL vs repeated ADD: {A_VAL} * {B_VAL} = {expected_product}"
507
+
508
+
509
+ SUITE = [
510
+ ("fib", lambda mem_size: fib(11, mem_size)),
511
+ ("sum_n", lambda mem_size: sum_n(10, mem_size)),
512
+ ("self_mod_jmp", lambda mem_size: self_mod_jmp(mem_size)),
513
+ ("all_branches", lambda mem_size: all_branches(mem_size)),
514
+ ("call_pushes_pc", lambda mem_size: call_pushes_pc(mem_size)),
515
+ ("bubble_sort_4", lambda mem_size: bubble_sort_4(mem_size)),
516
+ ("cross_check_mul", lambda mem_size: cross_check_mul(mem_size)),
517
+ ]
518
+
eval_all.py CHANGED
@@ -322,18 +322,22 @@ class GenericThresholdCPU:
322
  b = s["regs"][rs]
323
  result = a
324
  carry = 0
 
325
  write_result = True
326
  if opcode == 0x0:
327
  result, carry = self.alu.add8(a, b)
 
328
  elif opcode == 0x1:
329
  result, carry = self.alu.sub8(a, b)
 
330
  elif opcode == 0x7:
331
  result = self.alu.mul8(a, b)
332
  elif opcode == 0x9:
333
  r2, carry = self.alu.sub8(a, b)
334
  z = 1 if r2 == 0 else 0
335
  n = 1 if (r2 & 0x80) else 0
336
- s["flags"] = [z, n, carry, 0]
 
337
  write_result = False
338
  elif opcode == 0xA:
339
  result = self.mem_read(s["mem"], addr)
@@ -350,6 +354,16 @@ class GenericThresholdCPU:
350
  n == 1, n == 0, v == 1, v == 0][cond]
351
  s["pc"] = addr if take else next_pc
352
  return s
 
 
 
 
 
 
 
 
 
 
353
  elif opcode == 0xF:
354
  s["halted"] = True
355
  return s
@@ -359,7 +373,7 @@ class GenericThresholdCPU:
359
  if opcode in (0x0, 0x1, 0x7):
360
  z = 1 if (result & 0xFF) == 0 else 0
361
  n = 1 if (result & 0x80) else 0
362
- s["flags"] = [z, n, carry, 0]
363
  s["pc"] = next_pc
364
  return s
365
 
 
322
  b = s["regs"][rs]
323
  result = a
324
  carry = 0
325
+ overflow = 0
326
  write_result = True
327
  if opcode == 0x0:
328
  result, carry = self.alu.add8(a, b)
329
+ overflow = 1 if (((a ^ result) & (b ^ result)) & 0x80) else 0
330
  elif opcode == 0x1:
331
  result, carry = self.alu.sub8(a, b)
332
+ overflow = 1 if (((a ^ b) & (a ^ result)) & 0x80) else 0
333
  elif opcode == 0x7:
334
  result = self.alu.mul8(a, b)
335
  elif opcode == 0x9:
336
  r2, carry = self.alu.sub8(a, b)
337
  z = 1 if r2 == 0 else 0
338
  n = 1 if (r2 & 0x80) else 0
339
+ v = 1 if (((a ^ b) & (a ^ r2)) & 0x80) else 0
340
+ s["flags"] = [z, n, carry, v]
341
  write_result = False
342
  elif opcode == 0xA:
343
  result = self.mem_read(s["mem"], addr)
 
354
  n == 1, n == 0, v == 1, v == 0][cond]
355
  s["pc"] = addr if take else next_pc
356
  return s
357
+ elif opcode == 0xE: # CALL: push return address (next_pc), set PC = addr
358
+ ret_addr = next_pc & 0xFFFF
359
+ sp = s.get("sp", addr_mask)
360
+ sp = (sp - 1) & addr_mask
361
+ s["mem"] = self.mem_write(s["mem"], sp, (ret_addr >> 8) & 0xFF)
362
+ sp = (sp - 1) & addr_mask
363
+ s["mem"] = self.mem_write(s["mem"], sp, ret_addr & 0xFF)
364
+ s["sp"] = sp
365
+ s["pc"] = addr
366
+ return s
367
  elif opcode == 0xF:
368
  s["halted"] = True
369
  return s
 
373
  if opcode in (0x0, 0x1, 0x7):
374
  z = 1 if (result & 0xFF) == 0 else 0
375
  n = 1 if (result & 0x80) else 0
376
+ s["flags"] = [z, n, carry, overflow]
377
  s["pc"] = next_pc
378
  return s
379
 
test_cpu.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Run the CPU program suite against a threshold-computer variant.
3
+
4
+ Loads weights, instantiates GenericThresholdCPU, runs each program from
5
+ cpu_programs.SUITE, and verifies expected memory contents at HALT.
6
+
7
+ Usage:
8
+ python test_cpu.py # default: 1KB variant, fast
9
+ python test_cpu.py --model neural_computer.safetensors # 64KB canonical, slow
10
+ python test_cpu.py --only fib,sum_n # subset of suite
11
+ """
12
+
13
+ from __future__ import annotations
14
+ import argparse
15
+ import os
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import torch
21
+ from safetensors import safe_open
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ from eval_all import GenericThresholdCPU, get_manifest
25
+ from cpu_programs import SUITE
26
+
27
+
28
+ def load_tensors(path: Path):
29
+ out = {}
30
+ with safe_open(str(path), framework="pt") as f:
31
+ for name in f.keys():
32
+ out[name] = f.get_tensor(name).float()
33
+ return out
34
+
35
+
36
+ def run_program(cpu: GenericThresholdCPU, mem, max_cycles: int):
37
+ addr_mask = (1 << cpu.addr_bits) - 1
38
+ state = {
39
+ "pc": 0,
40
+ "regs": [0] * 4,
41
+ "flags": [0] * 4,
42
+ "mem": list(mem),
43
+ "halted": False,
44
+ "sp": addr_mask,
45
+ }
46
+ t0 = time.perf_counter()
47
+ final, cycles = cpu.run(state, max_cycles=max_cycles)
48
+ return final, cycles, time.perf_counter() - t0
49
+
50
+
51
+ def check_expected(final, expected: dict) -> tuple[bool, list[str]]:
52
+ failures = []
53
+ for addr, want in expected.items():
54
+ got = final["mem"][addr]
55
+ if got != want:
56
+ failures.append(f"M[0x{addr:04X}] = {got} (expected {want})")
57
+ return (len(failures) == 0), failures
58
+
59
+
60
+ def main() -> int:
61
+ parser = argparse.ArgumentParser(description="Run the CPU program suite")
62
+ parser.add_argument(
63
+ "--model", type=str,
64
+ default=os.path.join(os.path.dirname(__file__),
65
+ "variants", "neural_computer8_small.safetensors"),
66
+ help="Path to .safetensors variant",
67
+ )
68
+ parser.add_argument(
69
+ "--only", type=str, default="",
70
+ help="Comma-separated subset of program names to run",
71
+ )
72
+ args = parser.parse_args()
73
+
74
+ print(f"Loading {args.model}")
75
+ tensors = load_tensors(Path(args.model))
76
+ manifest = get_manifest(tensors)
77
+ print(f"Manifest: data={manifest['data_bits']}-bit, addr={manifest['addr_bits']}-bit, "
78
+ f"mem={manifest['memory_bytes']}B")
79
+
80
+ if manifest["memory_bytes"] < 256:
81
+ print(f"ERROR: variant has {manifest['memory_bytes']}B memory; "
82
+ f"the suite needs at least 256B (scratchpad).")
83
+ return 2
84
+
85
+ cpu = GenericThresholdCPU(tensors)
86
+ only = set(s.strip() for s in args.only.split(",") if s.strip())
87
+
88
+ print()
89
+ print("=" * 80)
90
+ print(f" CPU PROGRAM SUITE ({manifest['memory_bytes']}B mem, {manifest['data_bits']}-bit ALU)")
91
+ print("=" * 80)
92
+
93
+ pass_count = 0
94
+ fail_count = 0
95
+ skip_count = 0
96
+
97
+ for name, builder in SUITE:
98
+ if only and name not in only:
99
+ skip_count += 1
100
+ continue
101
+ try:
102
+ mem, expected, max_cycles, desc = builder(manifest["memory_bytes"])
103
+ except Exception as e:
104
+ print(f" {name:18} BUILD ERROR: {e}")
105
+ fail_count += 1
106
+ continue
107
+
108
+ if len(mem) != manifest["memory_bytes"]:
109
+ print(f" {name:18} SKIP (program built {len(mem)}B, "
110
+ f"variant has {manifest['memory_bytes']}B)")
111
+ skip_count += 1
112
+ continue
113
+
114
+ final, cycles, elapsed = run_program(cpu, mem, max_cycles)
115
+ ok, failures = check_expected(final, expected)
116
+ if ok and not final["halted"]:
117
+ ok = False
118
+ failures.append(f"did not HALT within {max_cycles} cycles")
119
+
120
+ status = "PASS" if ok else "FAIL"
121
+ if ok:
122
+ pass_count += 1
123
+ else:
124
+ fail_count += 1
125
+ print(f" {name:18} {status} ({cycles:>3} cyc, {elapsed:>5.2f}s) {desc}")
126
+ if not ok:
127
+ for f in failures[:6]:
128
+ print(f" - {f}")
129
+
130
+ print()
131
+ print("=" * 80)
132
+ total = pass_count + fail_count
133
+ print(f" PASS: {pass_count}/{total} FAIL: {fail_count}/{total} SKIP: {skip_count}")
134
+ return 0 if fail_count == 0 else 1
135
+
136
+
137
+ if __name__ == "__main__":
138
+ sys.exit(main())