PowerMachine commited on
Commit
8c5423e
·
verified ·
1 Parent(s): 6910d1b

HAKO upload: hako/core/ghsom.py

Browse files
Files changed (1) hide show
  1. hako/core/ghsom.py +207 -0
hako/core/ghsom.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GHSOM -- Growing Hierarchical Self-Organizing Map (structural spine of L3).
2
+
3
+ Theorem T-GHSOM (winner existence and finite growth depth).
4
+ (1) Winner existence: for any input z, the map j -> ||z - W_j|| is continuous
5
+ on the finite neuron set of a grid, hence attains a minimum:
6
+ c(z) = argmin_j ||z - W_j|| exists (Weierstrass on a finite set).
7
+ (2) Hierarchical descent preserves the global winner along the searched path:
8
+ each child grid refines the Voronoi cell of its parent neuron (child
9
+ weights are initialized inside the parent cell and only updated by points
10
+ routed there), so by induction on levels the leaf winner minimizes the
11
+ distance among all neurons on the path; the search cost is
12
+ O(sum_levels grid_size) = O(|path|) << O(|tree|).
13
+ (3) Finite depth: a leaf grows iff QE_leaf > tau_G * QE_parent with
14
+ tau_G in (0,1). Consequently QE after L levels obeys
15
+ QE_L <= tau_G^L * QE_root,
16
+ and growth must stop once QE <= QE_min (the smallest resolvable
17
+ quantization error at float32 precision, > 0). Solving
18
+ tau_G^L QE_root <= QE_min gives the guaranteed stopping depth
19
+ L_max = ceil( log_{1/tau_G} (QE_root / QE_min) ).
20
+ Since Z is bounded (||z|| <= C), QE_root <= 4 C^2 (2x2 root) is finite,
21
+ so L_max is finite: the tree growth terminates. QED.
22
+
23
+ Growth mechanics (per arch.pdf 5.1): when a leaf's QE exceeds tau_G*QE_parent,
24
+ insert one row or column (alternating) into its grid; new neurons are
25
+ initialized as the average of their nearest existing neighbors (bilinear
26
+ interpolation of the grid), and head weights (V, U) for the new neurons are
27
+ projected copies of the parent's cell mean (handled by heads.attach).
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import math
32
+ from typing import Dict, List, Optional, Tuple
33
+
34
+ import numpy as np
35
+ import torch
36
+
37
+
38
+ class GHSOMNode:
39
+ __slots__ = ("nid", "parent", "parent_idx", "level", "rows", "cols",
40
+ "W", "children", "qe", "grow_parity")
41
+
42
+ def __init__(self, nid: int, parent: Optional[int], parent_idx: Optional[int],
43
+ level: int, W: torch.Tensor) -> None:
44
+ self.nid = nid
45
+ self.parent = parent
46
+ self.parent_idx = parent_idx
47
+ self.level = level
48
+ self.rows, self.cols = W.shape[0], W.shape[1]
49
+ self.W = W # (rows, cols, N) torch float32, no grad
50
+ self.children: Dict[int, int] = {} # neuron flat idx -> child nid
51
+ self.qe = float("inf")
52
+ self.grow_parity = 0
53
+
54
+
55
+ class GHSOM:
56
+ def __init__(self, N_dim: int, tau_G: float = 0.55,
57
+ root_grid: Tuple[int, int] = (2, 2),
58
+ sigma0: float = 1.2, eta0: float = 0.35,
59
+ qe_min: float = 1e-6, seed: int = 7) -> None:
60
+ self.N = N_dim
61
+ self.tau_G = tau_G
62
+ self.sigma0 = sigma0
63
+ self.eta0 = eta0
64
+ self.qe_min = qe_min
65
+ self.rng = np.random.default_rng(seed)
66
+ self.next_id = 0
67
+ w0 = torch.randn(root_grid[0], root_grid[1], N_dim) * 0.05
68
+ root = GHSOMNode(self._new_id(), None, None, 0, w0)
69
+ self.nodes: Dict[int, GHSOMNode] = {root.nid: root}
70
+ self.root_id = root.nid
71
+ self.growth_events = 0
72
+
73
+ def _new_id(self) -> int:
74
+ i = self.next_id
75
+ self.next_id += 1
76
+ return i
77
+
78
+ # ------------------------------------------------------------- geometry
79
+ def L_max(self) -> int:
80
+ root = self.nodes[self.root_id]
81
+ qe_root = max(root.qe if math.isfinite(root.qe) else 1.0, self.qe_min * 4)
82
+ ratio = qe_root / self.qe_min
83
+ return max(1, int(math.ceil(math.log(ratio) / math.log(1.0 / self.tau_G))))
84
+
85
+ @staticmethod
86
+ def _flat_winner(W: torch.Tensor, z: torch.Tensor) -> Tuple[int, float]:
87
+ d2 = ((W.reshape(-1, W.shape[-1]) - z) ** 2).sum(-1)
88
+ idx = int(d2.argmin().item())
89
+ return idx, float(d2.min().item())
90
+
91
+ def search(self, z: torch.Tensor) -> Tuple[List[Tuple[int, int]], float]:
92
+ """Hierarchical winner search. Returns (path, QE).
93
+
94
+ path = [(nid, flat_idx), ...] from root to the deepest winner.
95
+ By T-GHSOM(2) the leaf winner is the path-global winner.
96
+ """
97
+ path: List[Tuple[int, int]] = []
98
+ nid = self.root_id
99
+ while True:
100
+ node = self.nodes[nid]
101
+ idx, d2 = self._flat_winner(node.W, z)
102
+ path.append((nid, idx))
103
+ child_id = node.children.get(idx)
104
+ if child_id is None:
105
+ break
106
+ nid = child_id
107
+ leaf_nid, leaf_idx = path[-1]
108
+ qe = math.sqrt(max(0.0, self.nodes[leaf_nid].W.reshape(-1, self.N)[leaf_idx]
109
+ .sub(z).pow(2).sum().item()))
110
+ return path, qe
111
+
112
+ def neighborhood(self, nid: int, flat_idx: int, sigma: float) -> torch.Tensor:
113
+ node = self.nodes[nid]
114
+ r, c = divmod(flat_idx, node.cols)
115
+ rr = torch.arange(node.rows, dtype=torch.float32).view(-1, 1)
116
+ cc = torch.arange(node.cols, dtype=torch.float32).view(1, -1)
117
+ d2 = (rr - r) ** 2 + (cc - c) ** 2
118
+ return torch.exp(-d2 / (2 * max(sigma, 1e-4) ** 2)) # (rows, cols)
119
+
120
+ def kohonen_update(self, z: torch.Tensor, path: List[Tuple[int, int]],
121
+ lr: float, sigma: float) -> None:
122
+ """SOM update along the winner path (with torch, detached)."""
123
+ with torch.no_grad():
124
+ for lvl, (nid, idx) in enumerate(path):
125
+ node = self.nodes[nid]
126
+ h = self.neighborhood(nid, idx, sigma).unsqueeze(-1)
127
+ node.W += lr * h * (z.view(1, 1, -1) - node.W)
128
+
129
+ # --------------------------------------------------------------- growth
130
+ def leaf_qe_report(self, Z: torch.Tensor) -> Dict[int, float]:
131
+ """Accumulate per-leaf QE over a batch of inputs."""
132
+ acc: Dict[int, List[float]] = {}
133
+ for z in Z:
134
+ path, qe = self.search(z.unsqueeze(0).view(-1))
135
+ leaf = path[-1][0]
136
+ acc.setdefault(leaf, []).append(qe)
137
+ return {k: float(np.mean(v)) for k, v in acc.items()}
138
+
139
+ def maybe_grow(self, leaf_qe: Dict[int, float], parent_qe: float) -> List[int]:
140
+ """Grow leaves violating QE_leaf > tau_G * QE_parent, respecting L_max.
141
+
142
+ Returns the flat list of new neuron ids (per grow_leaf) for attach.
143
+ """
144
+ Lmax = self.L_max()
145
+ created: List[int] = []
146
+ for leaf_nid, qe in leaf_qe.items():
147
+ node = self.nodes[leaf_nid]
148
+ pqe = parent_qe if math.isfinite(parent_qe) else qe * 2.0
149
+ if qe > self.tau_G * pqe and node.level < Lmax:
150
+ created.extend(self.grow_leaf(leaf_nid))
151
+ return created
152
+
153
+ @staticmethod
154
+ def _safe_mean(t: torch.Tensor, fallback: torch.Tensor) -> torch.Tensor:
155
+ """Mean over a possibly-empty slice (guards NaN from empty .mean())."""
156
+ if t.numel() == 0:
157
+ return fallback
158
+ return t.mean(0) if t.dim() == 2 else t.mean()
159
+
160
+ def grow_leaf(self, nid: int) -> List[int]:
161
+ """Public API used by the trainer: grow and return new neuron ids.
162
+
163
+ New-neuron initialization is the bilinear average of the existing
164
+ neighbors on the inserted line; empty-neighbor sides fall back to the
165
+ grid mean (never NaN -- the P-MEM/T-GHSOM contract requires finite
166
+ weights).
167
+ """
168
+ node = self.nodes[nid]
169
+ with torch.no_grad():
170
+ grid_mean = node.W.reshape(-1, self.N).mean(0)
171
+ if node.grow_parity == 0:
172
+ r_ins = int(node.W.pow(2).sum(-1).sum(-1).argmax().item()) + 1
173
+ newW = torch.zeros(node.rows + 1, node.cols, self.N)
174
+ newW[:r_ins] = node.W[:r_ins]
175
+ newW[r_ins + 1:] = node.W[r_ins:]
176
+ above = node.W[max(0, r_ins - 1):r_ins]
177
+ below = node.W[r_ins:min(node.rows, r_ins + 1)]
178
+ a = self._safe_mean(above, grid_mean)
179
+ b = self._safe_mean(below, grid_mean)
180
+ newW[r_ins] = 0.5 * (a + b)
181
+ node.rows += 1
182
+ new_flat = [r_ins * node.cols + c for c in range(node.cols)]
183
+ else:
184
+ c_ins = int(node.W.pow(2).sum(-1).sum(0).argmax().item()) + 1
185
+ newW = torch.zeros(node.rows, node.cols + 1, self.N)
186
+ newW[:, :c_ins] = node.W[:, :c_ins]
187
+ newW[:, c_ins + 1:] = node.W[:, c_ins:]
188
+ left = node.W[:, max(0, c_ins - 1):c_ins]
189
+ right = node.W[:, c_ins:min(node.cols, c_ins + 1)]
190
+ a = self._safe_mean(left, grid_mean)
191
+ b = self._safe_mean(right, grid_mean)
192
+ newW[:, c_ins] = 0.5 * (a + b)
193
+ node.cols += 1
194
+ new_flat = [r * node.cols + c_ins for r in range(node.rows)]
195
+ node.grow_parity ^= 1
196
+ node.W = newW.contiguous()
197
+ node.children = {} # child mapping reset (flat indices changed)
198
+ self.growth_events += 1
199
+ return new_flat
200
+
201
+ # ------------------------------------------------------------- monitoring
202
+ def stats(self) -> Dict[str, float]:
203
+ n_neurons = sum(n.rows * n.cols for n in self.nodes.values())
204
+ depth = max((n.level for n in self.nodes.values()), default=0)
205
+ return {"n_nodes": len(self.nodes), "n_neurons": n_neurons,
206
+ "depth": depth, "growth_events": self.growth_events,
207
+ "L_max_bound": self.L_max()}