CharlesCNorton commited on
Commit
7ed141b
·
1 Parent(s): b9fb5ce

neural_attractor: an energy-based threshold computer where computation is relaxation to a ground state and the program is the coupling matrix. No program counter, no clock, no forward-only execution: clamp any subset of wires and relax. AND/OR/NOT energy gadgets (each zero iff the gate relation holds) make it universal by construction; forward evaluation is exact, and clamping outputs runs circuits backward (an 8x8 multiplier compiled to couplings factors 35=5x7, 143=11x13) or solves SAT. Module, tests, artifact builder, and the shipped coupling matrix.

Browse files
README.md CHANGED
@@ -457,6 +457,48 @@ noise margins. The processor is no longer *described by* a neural network; it
457
 
458
  ---
459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  ## neural_subleq8io and the universal constructor — a machine that prints itself
461
 
462
  `neural_subleq8io` is the one-instruction machine extended with three
 
457
 
458
  ---
459
 
460
+ ## neural_attractor — computation as relaxation, run in any direction
461
+
462
+ `neural_matrix8` still runs a program forward. `neural_attractor` drops the
463
+ last of the von Neumann structure: no program counter, no clock, no forward-only
464
+ execution. A computation is compiled into an energy function `E(s)` whose global
465
+ minimum, with the known wires clamped, is the unique consistent assignment of the
466
+ whole circuit. The program is the coupling matrix `Q` (with linear terms `L`);
467
+ running is relaxation toward the minimum, and the relaxation update is itself a
468
+ threshold neuron, `s_i <- H(-(L[i] + sum_j Q[i,j] s_j))`, so the machine is the
469
+ same substrate, one weight matrix with no controller.
470
+
471
+ Each gate contributes a gadget that is non-negative and equals zero exactly when
472
+ the gate relation holds (binary variables): `AND` is `3z + xy - 2xz - 2yz`, `OR`
473
+ is `x + y + z + xy - 2xz - 2yz`, `NOT` is `1 - x - z + 2xz`. Those are universal,
474
+ so any circuit compiles and universality is a theorem about the gadgets rather
475
+ than a hope about the dynamics. Forward evaluation is exact: clamp the inputs and
476
+ propagate through the gate relations in topological order, landing on the
477
+ energy-0 fixed point; the canonical form anneals the whole network to the same
478
+ minimum.
479
+
480
+ What no program counter can do falls out of clamping a different subset of wires:
481
+
482
+ - **Run circuits backward.** Clamp a multiplier's product and relax over the
483
+ inputs, and the machine returns factors. The shipped `neural_attractor` is an
484
+ 8x8 multiplier compiled to couplings (913 wires); it multiplies forward
485
+ bit-exactly and, run in reverse, factors (35 = 5 x 7, 143 = 11 x 13).
486
+ - **Solve.** Clamp a CNF formula's output to 1 and the minimum is a satisfying
487
+ assignment, so the same object is a circuit evaluator and a SAT solver.
488
+
489
+ The forward direction is exact and cheap; the backward and open-constraint modes
490
+ are genuine annealed search, and that hardness is the point. Factoring is hard,
491
+ and an exact integer-ternary substrate with structured gadgets, where the ground
492
+ state sits at energy 0 by construction rather than being approximated by an
493
+ analog annealer, is the interesting place to attack it.
494
+
495
+ ```bash
496
+ python tools/build_attractor.py # compile a multiplier to variants/neural_attractor.safetensors
497
+ python tools/test_attractor.py # forward eval, whole-network relaxation, factoring, SAT
498
+ ```
499
+
500
+ ---
501
+
502
  ## neural_subleq8io and the universal constructor — a machine that prints itself
503
 
504
  `neural_subleq8io` is the one-instruction machine extended with three
src/attractor.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attractor computer: computation as relaxation of a threshold network.
2
+
3
+ Every other machine in this repository is a stored-program computer whose gates
4
+ happen to be threshold neurons: it has a program counter, a fetch, and an
5
+ instruction stream. This one has none of those. A computation is compiled into
6
+ an energy function E(s) whose global minimum, with the known wires clamped, is
7
+ the unique consistent assignment of the whole circuit. The "program" is the
8
+ coupling matrix Q (with linear terms L); running is relaxation toward the
9
+ minimum. The relaxation update is itself a threshold neuron,
10
+
11
+ s_i <- H( -( L[i] + sum_j Q[i,j] s_j ) ),
12
+
13
+ so the machine is the same substrate as the rest of the repo, one weight matrix
14
+ iterated to a fixed point, with no controller.
15
+
16
+ Each gate contributes a gadget that is >= 0 and equals 0 exactly when the gate
17
+ relation holds (binary variables in {0,1}):
18
+
19
+ AND z=x&y : 3z + xy - 2xz - 2yz
20
+ OR z=x|y : x + y + z + xy - 2xz - 2yz
21
+ NOT z=~x : 1 - x - z + 2xz
22
+
23
+ AND/OR/NOT are universal, so any circuit compiles, and universality of the
24
+ machine is a theorem about the gadgets rather than a hope about the dynamics.
25
+
26
+ Two things a program counter cannot do fall out of this:
27
+
28
+ * Evaluate in any direction. Clamp inputs and relax to read outputs; or clamp
29
+ outputs and relax to recover inputs. Running a multiplier backward is
30
+ integer factoring; running any predicate backward is search.
31
+ * Solve. Clamp a formula's output to 1 and the minimum is a satisfying
32
+ assignment, so the same object is a circuit evaluator and a SAT solver.
33
+
34
+ Forward evaluation (inputs clamped) is exact and cheap: propagate through the
35
+ gate relations in topological order, which lands on the energy-0 fixed point.
36
+ Backward and open-constraint modes are genuine search, annealed over the free
37
+ wires; that hardness is the point (factoring is hard), and an exact integer
38
+ substrate with structured gadgets is the interesting place to attack it.
39
+ """
40
+ from __future__ import annotations
41
+ import math
42
+ import random
43
+ from collections import defaultdict
44
+ from typing import Dict, List, Optional, Tuple
45
+
46
+
47
+ class Circuit:
48
+ """Wire allocator and energy accumulator. Gates append exact QUBO gadgets
49
+ and record the relation for topological forward evaluation."""
50
+
51
+ def __init__(self) -> None:
52
+ self.n = 0
53
+ self.L: Dict[int, int] = defaultdict(int)
54
+ self.Q: Dict[Tuple[int, int], int] = defaultdict(int)
55
+ self.const = 0
56
+ self.gates: List[Tuple[str, int, Tuple[int, ...]]] = []
57
+
58
+ def wire(self) -> int:
59
+ i = self.n
60
+ self.n += 1
61
+ return i
62
+
63
+ def wires(self, k: int) -> List[int]:
64
+ return [self.wire() for _ in range(k)]
65
+
66
+ def _q(self, i: int, j: int, c: int) -> None:
67
+ if i == j:
68
+ self.L[i] += c
69
+ else:
70
+ self.Q[(min(i, j), max(i, j))] += c
71
+
72
+ def AND(self, x: int, y: int) -> int:
73
+ z = self.wire()
74
+ self.L[z] += 3
75
+ self._q(x, y, 1); self._q(x, z, -2); self._q(y, z, -2)
76
+ self.gates.append(("AND", z, (x, y)))
77
+ return z
78
+
79
+ def OR(self, x: int, y: int) -> int:
80
+ z = self.wire()
81
+ self.L[x] += 1; self.L[y] += 1; self.L[z] += 1
82
+ self._q(x, y, 1); self._q(x, z, -2); self._q(y, z, -2)
83
+ self.gates.append(("OR", z, (x, y)))
84
+ return z
85
+
86
+ def NOT(self, x: int) -> int:
87
+ z = self.wire()
88
+ self.const += 1
89
+ self.L[x] += -1; self.L[z] += -1
90
+ self._q(x, z, 2)
91
+ self.gates.append(("NOT", z, (x,)))
92
+ return z
93
+
94
+ def XOR(self, x: int, y: int) -> int:
95
+ return self.OR(self.AND(x, self.NOT(y)), self.AND(self.NOT(x), y))
96
+
97
+ def full_adder(self, x: int, y: int, cin: int) -> Tuple[int, int]:
98
+ axy = self.XOR(x, y)
99
+ s = self.XOR(axy, cin)
100
+ cout = self.OR(self.AND(x, y), self.AND(cin, axy))
101
+ return s, cout
102
+
103
+ # ---- energy + couplings ------------------------------------------------
104
+ def energy(self, s: List[int]) -> int:
105
+ e = self.const
106
+ for i, c in self.L.items():
107
+ e += c * s[i]
108
+ for (i, j), c in self.Q.items():
109
+ e += c * s[i] * s[j]
110
+ return e
111
+
112
+ def neighbors(self) -> Dict[int, List[Tuple[int, int]]]:
113
+ nbr: Dict[int, List[Tuple[int, int]]] = defaultdict(list)
114
+ for (i, j), c in self.Q.items():
115
+ nbr[i].append((j, c))
116
+ nbr[j].append((i, c))
117
+ return nbr
118
+
119
+ # ---- relaxation modes --------------------------------------------------
120
+ def forward_eval(self, clamp: Dict[int, int]) -> List[int]:
121
+ """Exact forward relaxation: propagate clamped inputs through the gate
122
+ relations in topological order onto the energy-0 fixed point."""
123
+ s = [0] * self.n
124
+ for w, v in clamp.items():
125
+ s[w] = v
126
+ for op, z, ins in self.gates:
127
+ if op == "AND":
128
+ s[z] = s[ins[0]] & s[ins[1]]
129
+ elif op == "OR":
130
+ s[z] = s[ins[0]] | s[ins[1]]
131
+ else:
132
+ s[z] = 1 - s[ins[0]]
133
+ return s
134
+
135
+ def relax_energy(self, clamp: Dict[int, int], sweeps: int = 4000,
136
+ t0: float = 4.0, t1: float = 0.02, seed: int = 0
137
+ ) -> Tuple[List[int], bool]:
138
+ """Canonical relaxation: anneal the full threshold network (every free
139
+ wire), tracking the lowest-energy state. Universal but hard; the exact
140
+ gadgets keep the target at energy 0."""
141
+ nbr = self.neighbors()
142
+ rng = random.Random(seed)
143
+ s = [rng.randint(0, 1) for _ in range(self.n)]
144
+ for w, v in clamp.items():
145
+ s[w] = v
146
+ free = [i for i in range(self.n) if i not in clamp]
147
+ best, best_e = list(s), self.energy(s)
148
+ for step in range(sweeps):
149
+ T = t0 * (t1 / t0) ** (step / max(1, sweeps - 1))
150
+ for _ in range(len(free)):
151
+ i = free[rng.randrange(len(free))]
152
+ field = self.L[i] + sum(c * s[j] for j, c in nbr[i])
153
+ dE = (1 - 2 * s[i]) * field
154
+ if dE <= 0 or rng.random() < math.exp(-dE / T):
155
+ s[i] ^= 1
156
+ e = self.energy(s)
157
+ if e < best_e:
158
+ best, best_e = list(s), e
159
+ if best_e == 0:
160
+ return best, True
161
+ return best, best_e == 0
162
+
163
+ def solve(self, free_inputs: List[int], fixed: Dict[int, int],
164
+ target: Dict[int, int], sweeps: int = 3000, restarts: int = 80,
165
+ seed: int = 0) -> Optional[List[int]]:
166
+ """Open-constraint relaxation over a chosen set of driver wires, with
167
+ the rest slaved through the circuit; anneal the output Hamming mismatch
168
+ to zero. Clamp outputs and pass the inputs here to run backward."""
169
+ rng = random.Random(seed)
170
+
171
+ def mism(vals: Dict[int, int]) -> int:
172
+ s = self.forward_eval({**fixed, **vals})
173
+ return sum(1 for w, v in target.items() if s[w] != v)
174
+
175
+ for _ in range(restarts):
176
+ vals = {w: rng.randint(0, 1) for w in free_inputs}
177
+ m = mism(vals)
178
+ if m == 0:
179
+ return self.forward_eval({**fixed, **vals})
180
+ for step in range(sweeps):
181
+ T = 2.0 * (0.02 / 2.0) ** (step / sweeps)
182
+ w = free_inputs[rng.randrange(len(free_inputs))]
183
+ vals[w] ^= 1
184
+ m2 = mism(vals)
185
+ if m2 <= m or rng.random() < math.exp(-(m2 - m) / T):
186
+ m = m2
187
+ if m == 0:
188
+ return self.forward_eval({**fixed, **vals})
189
+ else:
190
+ vals[w] ^= 1
191
+ return None
192
+
193
+
194
+ # ---------------------------------------------------------------------------
195
+ # Circuit builders
196
+ # ---------------------------------------------------------------------------
197
+ def adder(bits: int) -> Tuple[Circuit, dict]:
198
+ c = Circuit()
199
+ xs, ys = c.wires(bits), c.wires(bits)
200
+ cin = c.wire()
201
+ outs, carry = [], cin
202
+ for k in range(bits):
203
+ s, carry = c.full_adder(xs[k], ys[k], carry)
204
+ outs.append(s)
205
+ return c, {"xs": xs, "ys": ys, "cin": cin, "sum": outs + [carry]}
206
+
207
+
208
+ def multiplier(bits: int) -> Tuple[Circuit, dict]:
209
+ c = Circuit()
210
+ xs, ys = c.wires(bits), c.wires(bits)
211
+ zero = c.wire()
212
+ acc = [zero] * (2 * bits)
213
+ for i in range(bits):
214
+ carry = zero
215
+ for j in range(bits):
216
+ acc[i + j], carry = c.full_adder(acc[i + j], c.AND(xs[i], ys[j]), carry)
217
+ acc[i + bits] = carry
218
+ return c, {"xs": xs, "ys": ys, "zero": zero, "prod": acc}
219
+
220
+
221
+ _OPCODE = {"AND": 0, "OR": 1, "NOT": 2}
222
+ _OPNAME = {v: k for k, v in _OPCODE.items()}
223
+
224
+
225
+ def to_tensors(circ: Circuit, io: dict):
226
+ """Serialize the coupling matrix (the program) and the gate list to tensors.
227
+ Q is stored sparsely as index pairs and integer values."""
228
+ import torch
229
+ qi = sorted(circ.Q)
230
+ q_idx = torch.tensor(qi if qi else [], dtype=torch.long).reshape(-1, 2)
231
+ q_val = torch.tensor([circ.Q[k] for k in qi], dtype=torch.long)
232
+ li = sorted(circ.L)
233
+ l_idx = torch.tensor(li, dtype=torch.long)
234
+ l_val = torch.tensor([circ.L[i] for i in li], dtype=torch.long)
235
+ g_op = torch.tensor([_OPCODE[op] for op, _, _ in circ.gates], dtype=torch.long)
236
+ g_out = torch.tensor([o for _, o, _ in circ.gates], dtype=torch.long)
237
+ g_in = torch.tensor([[ins[0], ins[1] if len(ins) > 1 else -1]
238
+ for _, _, ins in circ.gates], dtype=torch.long).reshape(-1, 2)
239
+ t = {"Q_idx": q_idx, "Q_val": q_val, "L_idx": l_idx, "L_val": l_val,
240
+ "gate_op": g_op, "gate_out": g_out, "gate_in": g_in}
241
+ import json
242
+ meta = {"n": str(circ.n), "const": str(circ.const),
243
+ "io": json.dumps({k: v for k, v in io.items()})}
244
+ return t, meta
245
+
246
+
247
+ def from_tensors(t: dict, meta: dict) -> Tuple[Circuit, dict]:
248
+ import json
249
+ c = Circuit()
250
+ c.n = int(meta["n"])
251
+ c.const = int(meta["const"])
252
+ for (i, j), v in zip(t["Q_idx"].tolist(), t["Q_val"].tolist()):
253
+ c.Q[(i, j)] = v
254
+ for i, v in zip(t["L_idx"].tolist(), t["L_val"].tolist()):
255
+ c.L[i] = v
256
+ for op, out, ins in zip(t["gate_op"].tolist(), t["gate_out"].tolist(), t["gate_in"].tolist()):
257
+ c.gates.append((_OPNAME[op], out, tuple(x for x in ins if x >= 0)))
258
+ return c, json.loads(meta["io"])
259
+
260
+
261
+ def cnf(clauses: List[List[int]], n_vars: int) -> Tuple[Circuit, dict]:
262
+ """Compile a CNF formula. Literals are +v (var v) or -v (negation), v>=1.
263
+ Returns the circuit, the variable wires, and the wire that is 1 iff the
264
+ formula is satisfied. Clamp that wire to 1 and relax to find a model."""
265
+ c = Circuit()
266
+ var = {v: c.wire() for v in range(1, n_vars + 1)}
267
+ clause_ws = []
268
+ for cl in clauses:
269
+ lits = [var[abs(l)] if l > 0 else c.NOT(var[abs(l)]) for l in cl]
270
+ acc = lits[0]
271
+ for w in lits[1:]:
272
+ acc = c.OR(acc, w)
273
+ clause_ws.append(acc)
274
+ sat = clause_ws[0]
275
+ for w in clause_ws[1:]:
276
+ sat = c.AND(sat, w)
277
+ return c, {"vars": var, "sat": sat}
tools/build_attractor.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compile a circuit into the attractor computer's coupling matrix and ship it
2
+ as variants/neural_attractor.safetensors, a peer artifact to the other machines:
3
+ here the weights are the couplings Q (with linear terms L), and running is
4
+ relaxation. Round-trips the file and checks forward evaluation and a backward
5
+ inversion (factoring)."""
6
+ from __future__ import annotations
7
+ import os
8
+ import random
9
+ import sys
10
+
11
+ import torch
12
+ from safetensors.torch import save_file, load_file
13
+ from safetensors import safe_open
14
+
15
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
+ sys.path.insert(0, os.path.join(ROOT, "src"))
17
+ from attractor import multiplier, to_tensors, from_tensors
18
+
19
+ OUT = os.path.join(ROOT, "variants", "neural_attractor.safetensors")
20
+ BITS = 8
21
+
22
+
23
+ def main() -> int:
24
+ c, io = multiplier(BITS)
25
+ tensors, meta = to_tensors(c, io)
26
+ save_file(tensors, OUT, metadata=meta)
27
+ size = os.path.getsize(OUT)
28
+ print(f"Built {os.path.relpath(OUT, ROOT)}: {BITS}x{BITS} multiplier as couplings")
29
+ print(f" wires={c.n} Q entries={len(c.Q)} L entries={len(c.L)} size={size/1024:.1f} KB")
30
+
31
+ # round-trip
32
+ t = load_file(OUT)
33
+ with safe_open(OUT, framework="pt") as f:
34
+ m = f.metadata()
35
+ c2, io2 = from_tensors(t, m)
36
+ xs, ys, zero, prod = io2["xs"], io2["ys"], io2["zero"], io2["prod"]
37
+
38
+ rng = random.Random(0)
39
+ bad = 0
40
+ for _ in range(200):
41
+ a, b = rng.randint(0, 255), rng.randint(0, 255)
42
+ clamp = {zero: 0}
43
+ for k in range(BITS):
44
+ clamp[xs[k]] = (a >> k) & 1
45
+ clamp[ys[k]] = (b >> k) & 1
46
+ s = c2.forward_eval(clamp)
47
+ got = sum(s[w] << k for k, w in enumerate(prod))
48
+ if got != a * b or c2.energy(s) != 0:
49
+ bad += 1
50
+ print(f" round-trip forward multiply (200 cases): {'OK' if bad == 0 else f'FAIL({bad})'}")
51
+
52
+ # backward: factor a small product through the loaded couplings
53
+ N = 35
54
+ target = {prod[k]: (N >> k) & 1 for k in range(2 * BITS)}
55
+ s = c2.solve(xs + ys, {zero: 0}, target, sweeps=2500, restarts=120, seed=N)
56
+ if s is not None:
57
+ fa = sum(s[xs[k]] << k for k in range(BITS))
58
+ fb = sum(s[ys[k]] << k for k in range(BITS))
59
+ print(f" round-trip backward factor {N}: {fa} x {fb} {'OK' if fa * fb == N else 'WRONG'}")
60
+ ok = fa * fb == N
61
+ else:
62
+ print(f" round-trip backward factor {N}: not found")
63
+ ok = False
64
+ return 0 if (bad == 0 and ok) else 1
65
+
66
+
67
+ if __name__ == "__main__":
68
+ sys.exit(main())
tools/test_attractor.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exercise the attractor computer: exact forward evaluation, the canonical
2
+ whole-network energy relaxation, backward inversion (factoring), and SAT
3
+ solving (universality of the solve direction)."""
4
+ from __future__ import annotations
5
+ import os
6
+ import random
7
+ import sys
8
+
9
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src"))
10
+ from attractor import Circuit, adder, multiplier, cnf
11
+
12
+
13
+ def test_forward():
14
+ ok = True
15
+ for bits in (4, 8):
16
+ c, io = adder(bits)
17
+ rng = random.Random(bits)
18
+ bad = 0
19
+ for _ in range(300):
20
+ a, b = rng.randint(0, (1 << bits) - 1), rng.randint(0, (1 << bits) - 1)
21
+ clamp = {io["cin"]: 0}
22
+ for k in range(bits):
23
+ clamp[io["xs"][k]] = (a >> k) & 1
24
+ clamp[io["ys"][k]] = (b >> k) & 1
25
+ s = c.forward_eval(clamp)
26
+ got = sum(s[w] << k for k, w in enumerate(io["sum"]))
27
+ if got != a + b or c.energy(s) != 0:
28
+ bad += 1
29
+ print(f" forward adder {bits}-bit: {'OK' if bad == 0 else f'FAIL({bad})'}")
30
+ ok &= bad == 0
31
+ for bits in (3, 5):
32
+ c, io = multiplier(bits)
33
+ rng = random.Random(100 + bits)
34
+ bad = 0
35
+ for _ in range(300):
36
+ a, b = rng.randint(0, (1 << bits) - 1), rng.randint(0, (1 << bits) - 1)
37
+ clamp = {io["zero"]: 0}
38
+ for k in range(bits):
39
+ clamp[io["xs"][k]] = (a >> k) & 1
40
+ clamp[io["ys"][k]] = (b >> k) & 1
41
+ s = c.forward_eval(clamp)
42
+ got = sum(s[w] << k for k, w in enumerate(io["prod"]))
43
+ if got != a * b or c.energy(s) != 0:
44
+ bad += 1
45
+ print(f" forward multiplier {bits}-bit: {'OK' if bad == 0 else f'FAIL({bad})'}")
46
+ ok &= bad == 0
47
+ return ok
48
+
49
+
50
+ def test_energy_relax():
51
+ """The canonical form: anneal the whole network (no propagation shortcut)."""
52
+ c, io = adder(4)
53
+ rng = random.Random(3)
54
+ bad = 0
55
+ for _ in range(20):
56
+ a, b = rng.randint(0, 15), rng.randint(0, 15)
57
+ clamp = {io["cin"]: 0}
58
+ for k in range(4):
59
+ clamp[io["xs"][k]] = (a >> k) & 1
60
+ clamp[io["ys"][k]] = (b >> k) & 1
61
+ conv = False
62
+ for attempt in range(4): # annealers restart
63
+ s, conv = c.relax_energy(clamp, sweeps=6000, seed=rng.randint(0, 1 << 30))
64
+ got = sum(s[w] << k for k, w in enumerate(io["sum"]))
65
+ if conv and got == a + b:
66
+ break
67
+ if not conv:
68
+ bad += 1
69
+ print(f" whole-network energy relaxation (4-bit adder, 20 cases): "
70
+ f"{'OK' if bad == 0 else f'reached ground state in {20 - bad}/20'}")
71
+ return bad == 0
72
+
73
+
74
+ def test_factor():
75
+ ok = True
76
+ for bits, targets in ((4, [15, 35, 143]), (5, [21, 55, 91])):
77
+ c, io = multiplier(bits)
78
+ for N in targets:
79
+ target = {io["prod"][k]: (N >> k) & 1 for k in range(2 * bits)}
80
+ s = c.solve(io["xs"] + io["ys"], {io["zero"]: 0}, target, seed=N)
81
+ if s is None:
82
+ print(f" factor {N}: not found")
83
+ ok = False
84
+ continue
85
+ a = sum(s[io["xs"][k]] << k for k in range(bits))
86
+ b = sum(s[io["ys"][k]] << k for k in range(bits))
87
+ good = a * b == N and 1 < a < N and 1 < b < N
88
+ print(f" factor {N} ({bits}x{bits}): {a} x {b} {'OK' if a * b == N else 'WRONG'}")
89
+ ok &= a * b == N
90
+ return ok
91
+
92
+
93
+ def test_sat():
94
+ # (x1 | x2 | ~x3) & (~x1 | x3) & (x2 | x3) & (~x2 | ~x3), a satisfiable 3-SAT.
95
+ clauses = [[1, 2, -3], [-1, 3], [2, 3], [-2, -3]]
96
+ c, io = cnf(clauses, 3)
97
+ s = c.solve(list(io["vars"].values()), {}, {io["sat"]: 1}, seed=1)
98
+ if s is None:
99
+ print(" SAT solve: no model found")
100
+ return False
101
+ assign = {v: s[w] for v, w in io["vars"].items()}
102
+ sat = all(any((assign[abs(l)] == 1) if l > 0 else (assign[abs(l)] == 0) for l in cl)
103
+ for cl in clauses)
104
+ print(f" SAT solve: model {assign} {'satisfies' if sat else 'FAILS'} the formula")
105
+ return sat
106
+
107
+
108
+ if __name__ == "__main__":
109
+ print("Attractor computer\n" + "=" * 40)
110
+ print("Forward evaluation (exact, energy 0):")
111
+ a = test_forward()
112
+ print("Canonical relaxation:")
113
+ b = test_energy_relax()
114
+ print("Backward inversion (factoring by relaxation):")
115
+ c_ = test_factor()
116
+ print("SAT (clamp output to 1, relax to a model):")
117
+ d = test_sat()
118
+ print("=" * 40)
119
+ print("ALL PASS" if (a and b and c_ and d) else "FAILURES")
120
+ sys.exit(0 if (a and b and c_ and d) else 1)
variants/neural_attractor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad9bb1b7bb6110bc76fc2f946f822c7bc80dbba9673b2547a780b56690938150
3
+ size 95968