Associative Memory with Hopfield Networks

File: Hopfield.lean

A Hopfield network stores patterns of +1 and -1 values and can recover a stored pattern from a damaged copy. Training sets the weight between two units from how often they agree across the patterns:

math

Recall updates one unit at a time to the sign of its weighted input:

math

Each update keeps or lowers the energy of the network, so recall stops at a low-energy state:

math

The Code

 1 -- lean --run Hopfield.lean   (Hopfield associative neural network)
 2 
 3 abbrev Pattern := Array Int
 4 abbrev Weights := Array (Array Int)
 5 
 6 -- Hebbian learning: w[i][j] sums p[i] * p[j] over all patterns,
 7 -- with a zero diagonal.
 8 def train (patterns : List Pattern) (size : Nat) : Weights :=
 9   Array.ofFn (n := size) fun i =>
10     Array.ofFn (n := size) fun j =>
11       if i.val = j.val then 0
12       else patterns.foldl (fun acc p => acc + p[i.val]! * p[j.val]!) 0
13 
14 -- Asynchronous update: each unit takes the sign of its weighted input.
15 def hopfieldRecall (w : Weights) (input : Pattern) (steps : Nat := 5) :
16     Pattern := Id.run do
17   let n := input.size
18   let mut state := input
19   for _ in [0:steps] do
20     for i in [0:n] do
21       let sum := (List.range n).foldl
22         (fun acc j => acc + w[i]![j]! * state[j]!) 0
23       state := state.set! i (if sum ≥ 0 then 1 else -1)
24   return state
25 
26 def energy (w : Weights) (state : Pattern) : Float :=
27   let n := state.size
28   let sum := (List.range n).foldl (init := (0 : Int)) fun acc i =>
29     (List.range n).foldl (init := acc) fun acc j =>
30       acc + w[i]![j]! * state[i]! * state[j]!
31   Float.ofInt sum * -0.5
32 
33 def fixed (x : Float) (d : Nat := 1) : String :=
34   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
35   let frac := toString (n % 10 ^ d)
36   let pad := "".pushn '0' (d - frac.length)
37   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
38 
39 def showPattern (pat : Pattern) (width : Nat := 4) : IO Unit := do
40   for i in [0:pat.size] do
41     IO.print (if pat[i]! == 1 then "# " else ". ")
42     if (i + 1) % width == 0 then IO.println ""
43 
44 def patternX : Pattern := #[ 1, -1, -1,  1,
45                             -1,  1,  1, -1,
46                             -1,  1,  1, -1,
47                              1, -1, -1,  1]
48 
49 def patternO : Pattern := #[ 1,  1,  1,  1,
50                              1, -1, -1,  1,
51                              1, -1, -1,  1,
52                              1,  1,  1,  1]
53 
54 def weights : Weights := train [patternX, patternO] 16
55 
56 -- patternX with bits 0, 5 and 10 flipped
57 def noisy : Pattern :=
58   [0, 5, 10].foldl (fun p i => p.set! i (-p[i]!)) patternX
59 
60 -- Checked when the file compiles: the network recovers the pattern.
61 example : hopfieldRecall weights noisy = patternX := by native_decide
62 
63 def main : IO Unit := do
64   let recalled := hopfieldRecall weights noisy
65   let e (p : Pattern) := fixed (energy weights p)
66   IO.println s!"Original Pattern 'X' (Energy: {e patternX}):"
67   showPattern patternX
68   IO.println s!"\nNoisy Pattern with 3 bit-flips (Energy: {e noisy}):"
69   showPattern noisy
70   IO.println s!"\nRecalled Associative Memory (Energy: {e recalled}):"
71   showPattern recalled
72   IO.println s!"\nRecovered perfectly? {recalled == patternX}"

How It Works

  • Patterns and weights hold Int values, so all the arithmetic in training and recall is exact.
  • Array.ofFn (n := size) fun i => ... builds an array of size elements from a function of the index. The index i has type Fin size, a natural number that is less than size. i.val gives the plain number.
  • hopfieldRecall is a pure function written as loops. let mut state declares a local variable, and state.set! i v returns the array with one element replaced. I first named this function recall, but recall is a reserved word in Lean.
  • energy ends with Float.ofInt sum * -0.5. I first wrote -0.5 * Float.ofInt sum on that line. Lean read the leading minus as a subtraction from the expression on the line above and reported a syntax error.
  • The example line states that recall from the noisy pattern returns patternX. native_decide runs the code at compile time to check it. If you change the weights or the noise so that recall fails, the file does not compile.

The classical estimate for a network of N units is about 0.138 N stored patterns. Sixteen units hold about 2.2 patterns, so two patterns fit and three is at the limit. The update rule uses sum ≥ 0, so a zero weighted input picks +1. Asynchronous updates change one unit at a time and guarantee that the energy does not increase; synchronous updates can flip back and forth between two states.

State Energy, two patterns
patternX -144.0
noisy -52.0
recalled -144.0

The noisy pattern has higher energy than the stored pattern. Recall returns to the stored pattern and its energy. A damaged state that lands in another minimum can have the same energy as a stored pattern, which is why energy alone does not prove recovery.

Lean 4 Notes

Three ways to index an array. Lean has three forms, and they differ in what happens when the index is out of range.

1 #eval #[1, 2, 3][1]?   -- some 2
2 #eval #[1, 2, 3][9]?   -- none
3 
4 def first (a : Array Nat) (h : 0 < a.size) : Nat := a[0]

a[i]? returns an Option. a[i]! stops the program if the index is out of range. Plain a[i] has no run-time failure: Lean accepts it only when it can prove that the index is in range. In first, the parameter h is that proof, and each caller must supply it. This program uses ! because the proofs would hide the algorithm.

Fin. Array.ofFn (n := size) f calls f with each index from 0 to size - 1. The index has type Fin size, which is a Nat together with a proof that it is less than size. .val reads the number.

Loops in a pure function. hopfieldRecall uses let mut, for, and assignment, and it is still a pure function. The do block is syntax. Lean rewrites the loop as a function that takes the current state and returns the next one. Nothing outside the function can see the changes. state.set! i v follows the rule from the summarizer chapter: the loop holds the only reference to the array, so Lean changes it in place.

Ranges. [0:n] is the range 0, 1, up to n - 1. for _ in [0:steps] repeats a block and ignores the counter.

Top-level values. patternX, weights, and noisy are defs with no parameters. I put them outside main so that the example line can refer to them.

decide and native_decide. Both prove a statement by computing it. decide computes inside the proof checker. native_decide compiles the test to machine code and runs it. I tried decide on this line, and Lean reported that it failed to reduce the call to hopfieldRecall. native_decide checks the line in under a second. The cost: a proof by native_decide is only as sound as the Lean compiler.

Running It

 1 $ lean --run Hopfield.lean
 2 Original Pattern 'X' (Energy: -144.0):
 3 # . . # 
 4 . # # . 
 5 . # # . 
 6 # . . # 
 7 
 8 Noisy Pattern with 3 bit-flips (Energy: -52.0):
 9 . . . # 
10 . . # . 
11 . # . . 
12 # . . # 
13 
14 Recalled Associative Memory (Energy: -144.0):
15 # . . # 
16 . # # . 
17 . # # . 
18 # . . # 
19 
20 Recovered perfectly? true

The table above lists the same three energies. Recall returns to the stored pattern and its energy.

Testing Recall

The hard-coded noisy pattern is one case. A check over every 3-bit flip shows how many damaged copies recall can repair:

 1 def bitFlips (p : Pattern) (bits : List Nat) : Pattern :=
 2   bits.foldl (fun q i => q.set! i (-q[i]!)) p
 3 
 4 def allThreeFlips (p : Pattern) : List Pattern :=
 5   ((List.range p.size).flatMap fun i =>
 6     (List.range p.size).flatMap fun j =>
 7       (List.range p.size).map fun k => (i, j, k)).filterMap
 8     fun (i, j, k) =>
 9       if i < j && j < k then some (bitFlips p [i, j, k]) else none
10 
11 example : (allThreeFlips patternX).length = 560 := by native_decide
12 example : ((allThreeFlips patternX).filter
13     fun p => hopfieldRecall weights p == patternX).length = 520 := by
14   native_decide

Forty of the 560 three-bit flips do not recover patternX. The case in main recovers, but not every case at that distance does.

To see crosstalk, add a third pattern and train again:

1 def patternY : Pattern := #[ 1, -1, -1, -1,
2                              1, -1, -1, -1,
3                              1,  1, -1, -1,
4                              1, -1, -1, -1]
5 
6 def weights3 : Weights := train [patternX, patternO, patternY] 16

With weights3, recall from the same noisy pattern returns a state two bits from patternX with energy -138.0, equal to the energy of patternX, so Recovered perfectly? prints false. A vertical third pattern (patternI) recovers patternX in the same setup. The outcome depends on the pattern, not on a hard capacity limit.

1 Recalled Associative Memory (Energy: -138.0):
2 # . . .
3 . # # .
4 . # # .
5 # . . .
6 Recovered perfectly? false

The last column of the first and last rows flipped, so the state is two bits from patternX.

Using It

Flip more bits in noisy and see when recall fails. The example line will stop the build, so comment it out to see the output. Add a third pattern and check how many patterns 16 units can hold. To use larger patterns, change showPattern to a wider grid.