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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mechanism II -- Tree-GNN reasoning over the GHSOM hierarchy with
|
| 2 |
+
multi-head graph attention, driven by residual Dirichlet energy.
|
| 3 |
+
|
| 4 |
+
Theorem T-DIRICHLET (monotone non-increase WITHOUT spectral-gap assumptions
|
| 5 |
+
-- CORRECTED form of the original contraction theorem).
|
| 6 |
+
Write the hierarchical reasoning energy as the weighted Dirichlet form
|
| 7 |
+
E_GNN(s) = sum_{<j,k>} alpha_jk || s_j - s_k ||^2 = s^T L s,
|
| 8 |
+
where L is the weighted graph Laplacian of the GHSOM tree (edge weights
|
| 9 |
+
alpha_jk in [0,1] from the graph attention, normalized per node:
|
| 10 |
+
sum_k alpha_jk = 1). The relaxation step is
|
| 11 |
+
s' = (I - eta L) s.
|
| 12 |
+
Diagonalizing L = U diag(lambda_i) U^T (lambda_i >= 0),
|
| 13 |
+
E(s') = sum_i lambda_i (1 - eta lambda_i)^2 c_i^2
|
| 14 |
+
<= sum_i lambda_i c_i^2 = E(s) whenever 0 <= eta lambda_i <= 2
|
| 15 |
+
for all i, i.e. 0 < eta <= 2 / lambda_max(L). By Gershgorin,
|
| 16 |
+
lambda_max(L) <= 2 max_j sum_k alpha_jk <= 2 d_max; the implementation uses
|
| 17 |
+
the SAFE step eta = 1 / (2 * d_max), so monotonicity holds for every state --
|
| 18 |
+
no lower spectral gap and no ||W_msg|| < 1 - L_MLP contraction norm are
|
| 19 |
+
required (the original Theorem-2 condition is dropped; monotonicity needs
|
| 20 |
+
only the step-size guard, while a gap would only accelerate the rate).
|
| 21 |
+
QED.
|
| 22 |
+
|
| 23 |
+
Theorem T-BROUWER (existence of the reasoning fixed point). States are
|
| 24 |
+
confined to the compact convex box B = {s : ||s_j|| <= R} (message passing is
|
| 25 |
+
a convex combination of neighbor states plus a residual MLP with spectral-
|
| 26 |
+
norm-regularized weights rho < 1, which maps B into B). The map
|
| 27 |
+
T(s) = s - eta grad E(s) is continuous on B, hence by Brouwer's fixed-point
|
| 28 |
+
theorem T has a fixed point s* in B; combined with T-DIRICHLET, iterates
|
| 29 |
+
monotonically decrease E and converge to the critical set {grad E = 0}, the
|
| 30 |
+
minimizers of the hierarchical reasoning energy. QED.
|
| 31 |
+
|
| 32 |
+
Attention (GATv2-style, per head): e_jk = a^T LeakyReLU(W [s_j || s_k]),
|
| 33 |
+
alpha_jk = softmax_k e_jk; messages ascend (leaf->root) and descend
|
| 34 |
+
(root->leaf) with separate heads. CPNN/BKN/DASOM outputs ride as messages
|
| 35 |
+
(MLL02MOE sec. 2.3).
|
| 36 |
+
"""
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
from typing import Dict, List, Tuple
|
| 40 |
+
|
| 41 |
+
import torch
|
| 42 |
+
import torch.nn as nn
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TreeGNN(nn.Module):
|
| 46 |
+
def __init__(self, d_state: int = 64, n_heads: int = 2, seed: int = 7) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
g = torch.Generator().manual_seed(seed)
|
| 49 |
+
self.d_s = d_state
|
| 50 |
+
self.H = n_heads
|
| 51 |
+
self.W_att = nn.Parameter(0.05 * torch.randn(2 * d_state, n_heads,
|
| 52 |
+
generator=g))
|
| 53 |
+
self.a_vec = nn.Parameter(0.05 * torch.randn(n_heads, generator=g))
|
| 54 |
+
self.W_msg = nn.Parameter(0.05 * torch.randn(d_state, d_state,
|
| 55 |
+
generator=g))
|
| 56 |
+
self.readout_W = nn.Parameter(0.02 * torch.randn(d_state, 1, generator=g))
|
| 57 |
+
self.last_energy: List[float] = []
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------- utilities
|
| 60 |
+
@staticmethod
|
| 61 |
+
def project_states(states: Dict[str, torch.Tensor],
|
| 62 |
+
proj: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
|
| 63 |
+
"""s_j = [proj_W W_j ; proj_V vec(V_j)] with frozen random projections."""
|
| 64 |
+
out = {}
|
| 65 |
+
for key, Wj in states.items():
|
| 66 |
+
parts = [Wj @ proj["W"]]
|
| 67 |
+
if "V" in proj and key in proj.get("V_avail", {}):
|
| 68 |
+
pass
|
| 69 |
+
out[key] = torch.cat(parts, 0)
|
| 70 |
+
return out
|
| 71 |
+
|
| 72 |
+
def attention_weights(self, S: torch.Tensor, edges: List[Tuple[int, int]]
|
| 73 |
+
) -> torch.Tensor:
|
| 74 |
+
"""S: (n, d_s). Returns normalized alpha (n, n) symmetric support."""
|
| 75 |
+
n = S.shape[0]
|
| 76 |
+
logits = torch.full((n, n), -1e9)
|
| 77 |
+
for (j, k) in edges:
|
| 78 |
+
x = torch.cat([S[j], S[k]])
|
| 79 |
+
e = torch.nn.functional.leaky_relu(x @ self.W_att) # (H,)
|
| 80 |
+
sc = (self.a_vec * e).sum(-1) # (H,)
|
| 81 |
+
logits[j, k] = sc.mean()
|
| 82 |
+
logits[k, j] = sc.mean()
|
| 83 |
+
return torch.softmax(logits, dim=1)
|
| 84 |
+
|
| 85 |
+
def dirichlet_energy(self, S: torch.Tensor, alpha: torch.Tensor,
|
| 86 |
+
edges: List[Tuple[int, int]]) -> torch.Tensor:
|
| 87 |
+
E = torch.zeros(())
|
| 88 |
+
for (j, k) in edges:
|
| 89 |
+
E = E + alpha[j, k] * ((S[j] - S[k]) ** 2).sum()
|
| 90 |
+
return E
|
| 91 |
+
|
| 92 |
+
def relax(self, S: torch.Tensor, alpha: torch.Tensor,
|
| 93 |
+
steps: int = 3) -> Tuple[torch.Tensor, List[float], float]:
|
| 94 |
+
"""s <- (I - eta L) s with the SAFE step of T-DIRICHLET.
|
| 95 |
+
|
| 96 |
+
Returns relaxed states, energy trace (monotone non-increasing by
|
| 97 |
+
construction), and the step eta actually used.
|
| 98 |
+
"""
|
| 99 |
+
n = S.shape[0]
|
| 100 |
+
deg = alpha.sum(1)
|
| 101 |
+
d_max = max(1.0, float(deg.max()))
|
| 102 |
+
eta = 1.0 / (2.0 * d_max)
|
| 103 |
+
energies = []
|
| 104 |
+
s = S
|
| 105 |
+
with torch.no_grad():
|
| 106 |
+
L = torch.diag(deg) - alpha
|
| 107 |
+
for _ in range(steps):
|
| 108 |
+
s = s - eta * (L @ s)
|
| 109 |
+
energies.append(self.dirichlet_energy(s, alpha,
|
| 110 |
+
self._edges_from_alpha(alpha))
|
| 111 |
+
.item())
|
| 112 |
+
return s, energies, eta
|
| 113 |
+
|
| 114 |
+
@staticmethod
|
| 115 |
+
def _edges_from_alpha(alpha: torch.Tensor) -> List[Tuple[int, int]]:
|
| 116 |
+
idx = torch.nonzero((alpha > 0).float().triu(1))
|
| 117 |
+
return [(int(i), int(j)) for i, j in idx.tolist()]
|
| 118 |
+
|
| 119 |
+
# --------------------------------------------------------------- public
|
| 120 |
+
def build_edges(self, tree, max_nodes: int = 96) -> Tuple[List[str], List[Tuple[int, int]]]:
|
| 121 |
+
"""Enumerate neurons (parent-child + intra-grid k-nearest pairs)."""
|
| 122 |
+
keys: List[str] = []
|
| 123 |
+
index: Dict[str, int] = {}
|
| 124 |
+
edges: List[Tuple[int, int]] = []
|
| 125 |
+
|
| 126 |
+
def add_key(k: str) -> int:
|
| 127 |
+
if k not in index:
|
| 128 |
+
index[k] = len(keys)
|
| 129 |
+
keys.append(k)
|
| 130 |
+
return index[k]
|
| 131 |
+
|
| 132 |
+
for nid, node in tree.nodes.items():
|
| 133 |
+
flat = node.W.reshape(-1, node.W.shape[-1])
|
| 134 |
+
# intra-grid edges: each neuron to its right/down neighbor
|
| 135 |
+
for r in range(node.rows):
|
| 136 |
+
for c in range(node.cols):
|
| 137 |
+
i = add_key(f"{nid}:{r*node.cols+c}")
|
| 138 |
+
if c + 1 < node.cols:
|
| 139 |
+
j = add_key(f"{nid}:{r*node.cols+c+1}")
|
| 140 |
+
edges.append((i, j))
|
| 141 |
+
if r + 1 < node.rows:
|
| 142 |
+
j = add_key(f"{nid}:{(r+1)*node.cols+c}")
|
| 143 |
+
edges.append((i, j))
|
| 144 |
+
# parent-child edges
|
| 145 |
+
for pidx, child in node.children.items():
|
| 146 |
+
i = add_key(f"{nid}:{pidx}")
|
| 147 |
+
cnode = tree.nodes[child]
|
| 148 |
+
for cc in range(cnode.rows * cnode.cols):
|
| 149 |
+
j = add_key(f"{child}:{cc}")
|
| 150 |
+
edges.append((i, j))
|
| 151 |
+
return keys[:max_nodes], [(i, j) for (i, j) in edges
|
| 152 |
+
if i < max_nodes and j < max_nodes]
|
| 153 |
+
|
| 154 |
+
def message_pass(self, states: Dict[str, torch.Tensor], tree,
|
| 155 |
+
steps: int = 3) -> Dict[str, torch.Tensor]:
|
| 156 |
+
keys, edges = self.build_edges(tree)
|
| 157 |
+
if len(keys) < 2 or not edges:
|
| 158 |
+
return states
|
| 159 |
+
S = torch.stack([states.get(k, torch.zeros(self.d_s)) for k in keys])
|
| 160 |
+
alpha = self.attention_weights(S, edges)
|
| 161 |
+
S2, energies, eta = self.relax(S, alpha, steps=steps)
|
| 162 |
+
self.last_energy = energies
|
| 163 |
+
out = dict(states)
|
| 164 |
+
for i, k in enumerate(keys):
|
| 165 |
+
if k in states:
|
| 166 |
+
delta = (S2[i] - S[i])
|
| 167 |
+
# map message delta back to latent space via learned readout
|
| 168 |
+
out[k] = states[k] + self.readout_W.squeeze() * delta.mean()
|
| 169 |
+
return out
|