AbstractPhil commited on
Commit
bf36780
·
verified ·
1 Parent(s): df5e25f

mirror governor.py from geolip 0.7.0 @a63a29b (MIRROR law; n_const=1 bit-identical)

Browse files
Files changed (1) hide show
  1. governor.py +126 -0
governor.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The anchor governor — min-separation projection (ROUND 5f, 2026-08-25).
2
+
3
+ Measured law (claude-mind, canon/splat_aleph_battery.md ROUND 5e/5f): anchors
4
+ crowded past the separation floor flutter under the positional sweep (the
5
+ static logit gap is quadratic in separation, the oscillation linear), and the
6
+ crowding tail tracks seed fragility. The governor holds the space open FROM
7
+ BIRTH — the projection is preventive, not curative (exact lemma: separating an
8
+ already-crowded book leaves its flip pattern bit-identical for content already
9
+ associated with it).
10
+
11
+ Form: a post-optimizer-step PROJECTION, never an auxiliary loss — this repo's
12
+ standing law ("no balance machinery; pressure stays out of the task gradient",
13
+ model/bank.py) is respected because the governor never touches the gradient.
14
+ Hub and head codebooks live natively in their own D-dim address space, so the
15
+ plain projective form applies (|cos| on RP^(D-1): the read is exactly
16
+ invariant under a -> -a). Identity when slack: the batched check is one
17
+ matmul per codebook and nothing is written unless a pair violates.
18
+
19
+ Verified properties (2026-08-25, gov25m rung): fires only when needed
20
+ (bit-identical runs when slack), census tail cut 5.4x, fragile-seed function
21
+ +.007, stable-seed +.002 — zero cost, no parameters.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import math
26
+
27
+ import torch
28
+
29
+ from .address import AlephAddress
30
+
31
+ __all__ = ["minsep_project_", "govern_model"]
32
+
33
+
34
+ @torch.no_grad()
35
+ def minsep_project_(codebook: torch.nn.Parameter, theta_min_deg: float,
36
+ max_iters: int = 8) -> int:
37
+ """Projective min-separation on one (K, D) codebook, in place.
38
+
39
+ Bound: |cos(a_i, a_j)| <= cos(theta_min) for every pair. Exact symmetric
40
+ geodesic push-apart, largest violation first, projected to theta_min +
41
+ 0.5 deg (the exact-bound push converges asymptotically under fp32 and
42
+ can land ~1e-4 over). Returns the number of pair-pushes performed —
43
+ 0 means the call was a pure read (identity, zero writes).
44
+ """
45
+ c_max = math.cos(math.radians(theta_min_deg))
46
+ A = torch.nn.functional.normalize(codebook.data.float(), dim=-1)
47
+ hits = 0
48
+ changed = False
49
+ for _ in range(max_iters):
50
+ G = A @ A.T
51
+ G.fill_diagonal_(0)
52
+ viol = (G.abs() > c_max).nonzero()
53
+ viol = viol[viol[:, 0] < viol[:, 1]]
54
+ if not len(viol):
55
+ break
56
+ order = G.abs()[viol[:, 0], viol[:, 1]].argsort(descending=True)
57
+ for i, j in viol[order].tolist():
58
+ g = float(A[i] @ A[j])
59
+ if abs(g) <= c_max:
60
+ continue
61
+ s = 1.0 if g >= 0 else -1.0
62
+ b = s * A[j]
63
+ gam = math.acos(max(-1.0, min(1.0, float(A[i] @ b))))
64
+ if gam < 1e-6: # exact duplicate: nudge first
65
+ b = torch.nn.functional.normalize(
66
+ b + 1e-3 * torch.randn_like(b), dim=-1)
67
+ gam = math.acos(max(-1.0, min(1.0, float(A[i] @ b))))
68
+ delta = (math.radians(theta_min_deg + 0.5) - gam) / 2
69
+ ai = A[i].clone()
70
+ ti = (b - math.cos(gam) * ai) / math.sin(gam)
71
+ tj = (ai - math.cos(gam) * b) / math.sin(gam)
72
+ A[i] = torch.nn.functional.normalize(
73
+ math.cos(delta) * ai - math.sin(delta) * ti, dim=-1)
74
+ A[j] = s * torch.nn.functional.normalize(
75
+ math.cos(delta) * b - math.sin(delta) * tj, dim=-1)
76
+ hits += 1
77
+ changed = True
78
+ if changed:
79
+ codebook.data.copy_(A.to(codebook.dtype))
80
+ return hits
81
+
82
+
83
+ def _hub_addresses(attn):
84
+ """Every AlephAddress a hub carries (single- or multi-constellation)."""
85
+ if hasattr(attn, "consts"):
86
+ return [c.addr for c in attn.consts]
87
+ addr = getattr(attn, "addr", None)
88
+ return [addr] if isinstance(addr, AlephAddress) else []
89
+
90
+
91
+ @torch.no_grad()
92
+ def govern_model(model, theta_min_deg: float,
93
+ include: tuple = ("hub", "head")) -> int:
94
+ """Batched slack check + projection across a model's governed codebooks.
95
+
96
+ Slack path costs one small matmul per codebook and writes nothing.
97
+ Wrapper-aware (amoe BlockWithAdapter moves the block to .block).
98
+ `include`: "hub" = attention codebooks, "head" = DualHead, "bank" =
99
+ dispatch anchors (K=experts in d_model — never crowds in practice, off
100
+ by default).
101
+ """
102
+ c_max = math.cos(math.radians(theta_min_deg))
103
+ books: list[torch.nn.Parameter] = []
104
+ if "hub" in include:
105
+ for wrap in getattr(model, "blocks", []):
106
+ blk = getattr(wrap, "block", wrap)
107
+ if getattr(blk, "is_hub", False):
108
+ books += [a.codebook for a in _hub_addresses(blk.attn)]
109
+ if "head" in include and hasattr(model, "head"):
110
+ addr = getattr(model.head, "addr", None)
111
+ if isinstance(addr, AlephAddress):
112
+ books.append(addr.codebook)
113
+ if "bank" in include:
114
+ for wrap in getattr(model, "blocks", []):
115
+ blk = getattr(wrap, "block", wrap)
116
+ addr = getattr(getattr(blk, "bank", None), "addr", None)
117
+ if isinstance(addr, AlephAddress):
118
+ books.append(addr.codebook)
119
+ hits = 0
120
+ for cb in books:
121
+ A = torch.nn.functional.normalize(cb.data.float(), dim=-1)
122
+ G = (A @ A.T).abs()
123
+ G.fill_diagonal_(0)
124
+ if float(G.max()) > c_max: # slack check: one matmul
125
+ hits += minsep_project_(cb, theta_min_deg)
126
+ return hits