AbstractPhil commited on
Commit
d995873
·
verified ·
1 Parent(s): 33e89d6

0.2.2: needs_bands marker on RelayPatch2D (host dispatch)

Browse files
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "amoe-lora"
7
- version = "0.2.1"
8
  description = "Aleph mixture-of-experts adapters: train, attach, align, detach — with the honesty diagnostics built in. 0.2 adds the diffusion subsystem (amoe.diffusion) and safetensors I/O."
9
  readme = "README.md"
10
  requires-python = ">=3.10"
 
4
 
5
  [project]
6
  name = "amoe-lora"
7
+ version = "0.2.2"
8
  description = "Aleph mixture-of-experts adapters: train, attach, align, detach — with the honesty diagnostics built in. 0.2 adds the diffusion subsystem (amoe.diffusion) and safetensors I/O."
9
  readme = "README.md"
10
  requires-python = ">=3.10"
src/amoe/__init__.py CHANGED
@@ -16,7 +16,7 @@ from .train.trainer import train
16
  from .train.aligner import align
17
  from . import laws
18
 
19
- __version__ = "0.2.1"
20
 
21
  # The diffusion subsystem (amoe.diffusion) is imported lazily — its verbs
22
  # live under `import amoe.diffusion as ad`. Core is pure torch; diffusers
 
16
  from .train.aligner import align
17
  from . import laws
18
 
19
+ __version__ = "0.2.2"
20
 
21
  # The diffusion subsystem (amoe.diffusion) is imported lazily — its verbs
22
  # live under `import amoe.diffusion as ad`. Core is pure torch; diffusers
src/amoe/diffusion/core/relay.py CHANGED
@@ -1,99 +1,104 @@
1
- """RelayPatch2D — the certified per-block residual relay for diffusion
2
- token streams (verbatim port of the r2 bed, pod2/aleph_diffusion_core.py;
3
- certified relay-favorable 3-for-3 substrates: Lune flow / SD15-core eps /
4
- Anima DiT flow — exp001/exp006/exp004).
5
-
6
- Differences from the text-side RelayPatchwork (amoe.core.adapter), each a
7
- paid-for law:
8
- * trailing-dim generalization: forward works on any [..., d] stream;
9
- * zero-init output weight AND bias (exp006 bias-leak law) — a fresh
10
- relay is EXACTLY inert, P-INIT bit-exact;
11
- * `enabled=False` returns x via CODE-PATH SKIP (`return x`, `is x`) —
12
- the toggle law is bit-exact at every dtype;
13
- * dims-from-state-dict reconstruction (never trust constructor defaults).
14
- """
15
- from __future__ import annotations
16
-
17
- import torch
18
- import torch.nn as nn
19
-
20
- from ...core.address import AlephAddress
21
- from ...core.adapter import SquaredReLU
22
-
23
-
24
- class RelayPatch2D(nn.Module):
25
- """forward(x[..., d]) = x + sigmoid(gate) * consume(m_hat(proj(x) slots))."""
26
-
27
- def __init__(self, d: int, n_slots: int = 16, K: int = 64,
28
- tau: float = 0.1, hidden: int = 178):
29
- super().__init__()
30
- self.d, self.n_slots, self.hidden = d, n_slots, hidden
31
- self.proj = nn.Linear(d, n_slots * 4, bias=False)
32
- nn.init.orthogonal_(self.proj.weight)
33
- self.addr = AlephAddress(K, 4, tau)
34
- self.consume = nn.Sequential(
35
- nn.Linear(n_slots * 4, hidden), SquaredReLU(),
36
- nn.LayerNorm(hidden), nn.Linear(hidden, d))
37
- nn.init.zeros_(self.consume[-1].weight) # zero-init out: weight
38
- nn.init.zeros_(self.consume[-1].bias) # AND bias (exp006 law)
39
- self.gate = nn.Parameter(torch.tensor(-3.0))
40
- self.enabled = True # plain attr, not a buffer
41
- self.telemetry = False # read-only ratio stash
42
- self.last_delta_ratio = None
43
-
44
- def assert_zero_init(self):
45
- w, b = self.consume[-1].weight, self.consume[-1].bias
46
- assert w.abs().max().item() == 0.0, "out weight not zero-init"
47
- assert b.abs().max().item() == 0.0, "out BIAS not zero-init (leak law)"
48
-
49
- def forward(self, x: torch.Tensor) -> torch.Tensor:
50
- if not self.enabled:
51
- return x
52
- lead = x.shape[:-1]
53
- slots = self.proj(x).view(*lead, self.n_slots, 4)
54
- feats = self.addr.m_hat(slots).reshape(*lead, self.n_slots * 4)
55
- delta = torch.sigmoid(self.gate) * self.consume(feats)
56
- if self.telemetry:
57
- with torch.no_grad():
58
- self.last_delta_ratio = (
59
- delta.norm() / x.norm().clamp_min(1e-12)).item()
60
- return x + delta
61
-
62
- @classmethod
63
- def from_state_dict(cls, sd: dict) -> "RelayPatch2D":
64
- """Rebuild dims FROM the state dict, then strict-load. Pre-amoe
65
- fork saves lack the addr.home drift-gauge buffer — reconstruct
66
- it from the codebook, LOUDLY (the gauge starts here)."""
67
- sd = dict(sd)
68
- d = sd["proj.weight"].shape[1]
69
- n_slots = sd["proj.weight"].shape[0] // 4
70
- hidden = sd["consume.0.weight"].shape[0]
71
- K = sd["addr.codebook"].shape[0]
72
- if "addr.home" not in sd:
73
- import torch.nn.functional as F
74
- sd["addr.home"] = F.normalize(
75
- sd["addr.codebook"].detach().float(), dim=-1)
76
- print("amoe.diffusion: addr.home reconstructed from codebook "
77
- "(pre-amoe save; drift gauge starts here)")
78
- m = cls(d, n_slots=n_slots, K=K, hidden=hidden)
79
- m.load_state_dict(sd, strict=True)
80
- return m
81
-
82
-
83
- class BlockWithRelay(nn.Module):
84
- """Wrap one trunk block; the relay reads its hidden-states output.
85
- Tuple outputs pass through (hybrid-safe, as amoe.core BlockWithAdapter).
86
- Carries a `w_bands` slot for wrap-uniformity with multiband sites —
87
- the relay ignores it."""
88
-
89
- def __init__(self, block: nn.Module, relay: nn.Module):
90
- super().__init__()
91
- self.block = block
92
- self.mod = relay
93
- self.w_bands = None # unused by relays; uniform wrap API
94
-
95
- def forward(self, *args, **kwargs):
96
- out = self.block(*args, **kwargs)
97
- if isinstance(out, tuple):
98
- return (self.mod(out[0]),) + out[1:]
99
- return self.mod(out)
 
 
 
 
 
 
1
+ """RelayPatch2D — the certified per-block residual relay for diffusion
2
+ token streams (verbatim port of the r2 bed, pod2/aleph_diffusion_core.py;
3
+ certified relay-favorable 3-for-3 substrates: Lune flow / SD15-core eps /
4
+ Anima DiT flow — exp001/exp006/exp004).
5
+
6
+ Differences from the text-side RelayPatchwork (amoe.core.adapter), each a
7
+ paid-for law:
8
+ * trailing-dim generalization: forward works on any [..., d] stream;
9
+ * zero-init output weight AND bias (exp006 bias-leak law) — a fresh
10
+ relay is EXACTLY inert, P-INIT bit-exact;
11
+ * `enabled=False` returns x via CODE-PATH SKIP (`return x`, `is x`) —
12
+ the toggle law is bit-exact at every dtype;
13
+ * dims-from-state-dict reconstruction (never trust constructor defaults).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from ...core.address import AlephAddress
21
+ from ...core.adapter import SquaredReLU
22
+
23
+
24
+ class RelayPatch2D(nn.Module):
25
+ """forward(x[..., d]) = x + sigmoid(gate) * consume(m_hat(proj(x) slots))."""
26
+
27
+ # Hosts dispatch on this: relays ignore the sigma axis, multiband
28
+ # modules require band windows. Marked on both so a caller never has
29
+ # to guess from the class name.
30
+ needs_bands = False
31
+
32
+ def __init__(self, d: int, n_slots: int = 16, K: int = 64,
33
+ tau: float = 0.1, hidden: int = 178):
34
+ super().__init__()
35
+ self.d, self.n_slots, self.hidden = d, n_slots, hidden
36
+ self.proj = nn.Linear(d, n_slots * 4, bias=False)
37
+ nn.init.orthogonal_(self.proj.weight)
38
+ self.addr = AlephAddress(K, 4, tau)
39
+ self.consume = nn.Sequential(
40
+ nn.Linear(n_slots * 4, hidden), SquaredReLU(),
41
+ nn.LayerNorm(hidden), nn.Linear(hidden, d))
42
+ nn.init.zeros_(self.consume[-1].weight) # zero-init out: weight
43
+ nn.init.zeros_(self.consume[-1].bias) # AND bias (exp006 law)
44
+ self.gate = nn.Parameter(torch.tensor(-3.0))
45
+ self.enabled = True # plain attr, not a buffer
46
+ self.telemetry = False # read-only ratio stash
47
+ self.last_delta_ratio = None
48
+
49
+ def assert_zero_init(self):
50
+ w, b = self.consume[-1].weight, self.consume[-1].bias
51
+ assert w.abs().max().item() == 0.0, "out weight not zero-init"
52
+ assert b.abs().max().item() == 0.0, "out BIAS not zero-init (leak law)"
53
+
54
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
55
+ if not self.enabled:
56
+ return x
57
+ lead = x.shape[:-1]
58
+ slots = self.proj(x).view(*lead, self.n_slots, 4)
59
+ feats = self.addr.m_hat(slots).reshape(*lead, self.n_slots * 4)
60
+ delta = torch.sigmoid(self.gate) * self.consume(feats)
61
+ if self.telemetry:
62
+ with torch.no_grad():
63
+ self.last_delta_ratio = (
64
+ delta.norm() / x.norm().clamp_min(1e-12)).item()
65
+ return x + delta
66
+
67
+ @classmethod
68
+ def from_state_dict(cls, sd: dict) -> "RelayPatch2D":
69
+ """Rebuild dims FROM the state dict, then strict-load. Pre-amoe
70
+ fork saves lack the addr.home drift-gauge buffer — reconstruct
71
+ it from the codebook, LOUDLY (the gauge starts here)."""
72
+ sd = dict(sd)
73
+ d = sd["proj.weight"].shape[1]
74
+ n_slots = sd["proj.weight"].shape[0] // 4
75
+ hidden = sd["consume.0.weight"].shape[0]
76
+ K = sd["addr.codebook"].shape[0]
77
+ if "addr.home" not in sd:
78
+ import torch.nn.functional as F
79
+ sd["addr.home"] = F.normalize(
80
+ sd["addr.codebook"].detach().float(), dim=-1)
81
+ print("amoe.diffusion: addr.home reconstructed from codebook "
82
+ "(pre-amoe save; drift gauge starts here)")
83
+ m = cls(d, n_slots=n_slots, K=K, hidden=hidden)
84
+ m.load_state_dict(sd, strict=True)
85
+ return m
86
+
87
+
88
+ class BlockWithRelay(nn.Module):
89
+ """Wrap one trunk block; the relay reads its hidden-states output.
90
+ Tuple outputs pass through (hybrid-safe, as amoe.core BlockWithAdapter).
91
+ Carries a `w_bands` slot for wrap-uniformity with multiband sites —
92
+ the relay ignores it."""
93
+
94
+ def __init__(self, block: nn.Module, relay: nn.Module):
95
+ super().__init__()
96
+ self.block = block
97
+ self.mod = relay
98
+ self.w_bands = None # unused by relays; uniform wrap API
99
+
100
+ def forward(self, *args, **kwargs):
101
+ out = self.block(*args, **kwargs)
102
+ if isinstance(out, tuple):
103
+ return (self.mod(out[0]),) + out[1:]
104
+ return self.mod(out)