Phase-Technologies commited on
Commit
eaa50c3
Β·
verified Β·
1 Parent(s): e7a02c0

Add model architecture component: arg_layer.py

Browse files
Files changed (1) hide show
  1. model/arg_layer.py +291 -0
model/arg_layer.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ARG (Adaptive Recurrent Gating) Layer β€” FORGE's core sequence mixer.
3
+
4
+ Combines:
5
+ 1. Complex-eigenvalue selective SSM (recurrent branch)
6
+ 2. Local windowed GQA (local attention branch)
7
+ 3. Learned scalar gate α_t ∈ [0,1] that blends the two
8
+ 4. Compound Positional Bias (CPB) for SSM initialization
9
+ """
10
+
11
+ from __future__ import annotations
12
+ import math
13
+ from typing import Optional, Tuple
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from einops import rearrange
19
+
20
+ from .dgn_norm import build_norm
21
+ from .rotary_embedding import RotaryEmbedding
22
+ from .triton_kernels import fused_swiglu
23
+ from .triton_ssm import fused_triton_ssm
24
+
25
+
26
+
27
+ class ARGLayer(nn.Module):
28
+ """
29
+ Adaptive Recurrent Gating Layer.
30
+
31
+ For each token t:
32
+ h_recur_t = ComplexSSM(x_{0:t})
33
+ h_local_t = WindowedGQA(x_{t-W:t})
34
+ Ξ±_t = Οƒ(w_g Β· x_t)
35
+ output_t = Ξ±_t * h_local_t + (1 - Ξ±_t) * h_recur_t
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ d_model: int = 1280,
41
+ d_inner: int = 1280,
42
+ d_state: int = 48,
43
+ d_rank: int = 48,
44
+ conv_kernel: int = 4,
45
+ local_window: int = 64,
46
+ local_n_heads: int = 8,
47
+ local_n_kv_heads: int = 2,
48
+ head_dim: int = 80,
49
+ norm_type: str = "dgn",
50
+ dgn_n_groups: int = 16,
51
+ norm_eps: float = 1e-6,
52
+ use_flash_attention: bool = True,
53
+ rope_base: float = 500_000.0,
54
+ layer_idx: int = 0,
55
+ max_seq_len: int = 4096,
56
+ ):
57
+ super().__init__()
58
+ self.d_model = d_model
59
+ self.d_inner = d_inner
60
+ self.d_state = d_state
61
+ self.d_rank = d_rank
62
+ self.conv_kernel = conv_kernel
63
+ self.local_window = local_window
64
+ self.local_n_heads = local_n_heads
65
+ self.local_n_kv_heads = local_n_kv_heads
66
+ self.head_dim = head_dim
67
+ self.use_flash_attention = use_flash_attention
68
+ self.layer_idx = layer_idx
69
+
70
+ # ── Pre-norm ──────────────────────────────────────────────────────────
71
+ self.norm = build_norm(norm_type, d_model, dgn_n_groups, norm_eps)
72
+
73
+ # ── Recurrent Branch ──────────────────────────────────────────────────
74
+ # Input projection: x β†’ (x_inner, z) both d_inner
75
+ self.in_proj = nn.Linear(d_model, 2 * d_inner, bias=False)
76
+
77
+ # Depthwise causal conv for local mixing
78
+ self.conv1d = nn.Conv1d(
79
+ d_inner, d_inner,
80
+ kernel_size=conv_kernel,
81
+ padding=conv_kernel - 1, # causal padding
82
+ groups=d_inner,
83
+ bias=True,
84
+ )
85
+
86
+ # Input-dependent SSM parameters (low-rank for Ξ”)
87
+ self.x_proj = nn.Linear(d_inner, d_rank + 2 * d_state, bias=False)
88
+ self.dt_proj = nn.Linear(d_rank, d_inner, bias=True)
89
+
90
+ # Complex SSM eigenvalue parameters
91
+ # Uses real-pair encoding: each complex eigenvalue Ξ» = -exp(Ξ½) Β± jΞΈ
92
+ # is represented as two real state channels, so d_state must be even.
93
+ # theta (oscillation) is implicitly learned through B/C projections.
94
+ assert d_state % 2 == 0, "d_state must be even for complex-pair encoding"
95
+ self.d_state_complex = d_state // 2
96
+
97
+ self.nu = nn.Parameter(torch.zeros(self.d_state_complex)) # decay (log scale)
98
+
99
+ # Skip connection coefficient D
100
+ self.D = nn.Parameter(torch.ones(d_inner))
101
+
102
+ # Output projection
103
+ self.out_proj = nn.Linear(d_inner, d_model, bias=False)
104
+
105
+ # ── Local Attention Branch ────────────────────────────────────────────
106
+ q_dim = local_n_heads * head_dim
107
+ kv_dim = local_n_kv_heads * head_dim
108
+
109
+ self.local_q = nn.Linear(d_model, q_dim, bias=False)
110
+ self.local_k = nn.Linear(d_model, kv_dim, bias=False)
111
+ self.local_v = nn.Linear(d_model, kv_dim, bias=False)
112
+ self.local_o = nn.Linear(q_dim, d_model, bias=False)
113
+
114
+ # Local RoPE (initialize with safe maximum length of 8192 to avoid dynamic cache expansion during forward pass)
115
+ self.local_rope = RotaryEmbedding(
116
+ head_dim=head_dim,
117
+ max_seq_len=max_seq_len * 2,
118
+ base=rope_base,
119
+ )
120
+
121
+ # ── Adaptive Gate ─────────────────────────────────────────────────────
122
+ self.gate_proj = nn.Linear(d_model, 1, bias=True)
123
+ nn.init.zeros_(self.gate_proj.weight)
124
+ nn.init.zeros_(self.gate_proj.bias) # Ξ±=0.5 at init: sigmoid(0) = 0.5
125
+
126
+ # Initialize weights
127
+ self._init_weights()
128
+
129
+ def _init_weights(self):
130
+ """Careful initialization for stable training."""
131
+ # dt_proj bias: positive to encourage non-trivial step sizes at init
132
+ dt_init_std = self.d_rank ** -0.5
133
+ nn.init.uniform_(self.dt_proj.weight, -dt_init_std, dt_init_std)
134
+ dt_bias = torch.exp(
135
+ torch.rand(self.d_inner) * (math.log(0.1) - math.log(0.001)) + math.log(0.001)
136
+ )
137
+ with torch.no_grad():
138
+ self.dt_proj.bias.copy_(dt_bias + torch.log(-torch.expm1(-dt_bias)))
139
+
140
+ # nu init β€” zero β†’ moderate decay at start
141
+ nn.init.zeros_(self.nu)
142
+
143
+ # Conv1d β€” identity-like init
144
+ nn.init.zeros_(self.conv1d.weight)
145
+ for i in range(self.d_inner):
146
+ self.conv1d.weight.data[i, 0, -1] = 1.0
147
+
148
+ # ─────────────────────────────────────────────────────────────────────────
149
+ # COMPLEX EIGENVALUE β†’ REAL A MATRIX
150
+ # ─────────────────────────────────────────────────────────────────────────
151
+
152
+ def _build_real_A(self) -> torch.Tensor:
153
+ """
154
+ Build the (d_inner, d_state) real-valued A matrix for selective_scan_fn.
155
+
156
+ Each complex eigenvalue Ξ»_i = -exp(Ξ½_i) + jΞΈ_i is encoded as two real
157
+ state channels with the same decay rate. The theta (oscillation) enters
158
+ via the B/C projections. mamba_ssm's selective_scan_fn discretizes A
159
+ internally via exp(A * Ξ”), so we pass the continuous-time log-decay
160
+ (negative real, per state channel).
161
+ """
162
+ decay = -F.softplus(self.nu.float()) # fp32 β€” mamba_ssm requires A in fp32
163
+ A_diag = decay.repeat_interleave(2) # (d_state,)
164
+ A = A_diag.unsqueeze(0).expand(self.d_inner, -1).contiguous().float() # (d_inner, d_state), fp32
165
+ return A
166
+
167
+ # ─────────────────────────────────────────────────────────────────────────
168
+ # RECURRENT BRANCH
169
+ # ─────────────────────────────────────────────────────────────────────────
170
+
171
+ @torch._dynamo.disable
172
+ def recurrent_branch(
173
+ self,
174
+ x: torch.Tensor, # (B, T, d_model)
175
+ position_offset: int = 0,
176
+ ) -> torch.Tensor:
177
+ """
178
+ Selective SSM recurrent branch using mamba_ssm's fused CUDA kernel.
179
+ Returns (B, T, d_model).
180
+
181
+ Uses selective_scan_fn (same kernel as Mamba) which:
182
+ - Processes all channels in parallel with an efficient associative scan
183
+ - Applies delta_softplus internally (no manual softplus on dt)
184
+ - Fuses the z-gate SiLU multiplication inside the kernel
185
+ - Eliminates 512Γ— Python-level kernel launches per layer
186
+ """
187
+ B, T, _ = x.shape
188
+
189
+ # ── Project inputs ────────────────────────────────────────────────────
190
+ xz = self.in_proj(x) # (B, T, 2*d_inner)
191
+ x_inner, z = xz.chunk(2, dim=-1) # each (B, T, d_inner)
192
+
193
+ # ── Causal conv for local mixing ──────────────────────────────────────
194
+ x_conv = rearrange(x_inner, 'b t d -> b d t')
195
+ x_conv = self.conv1d(x_conv)[:, :, :T] # trim causal padding, still (B, d_inner, T)
196
+ x_conv = F.silu(x_conv) # (B, d_inner, T)
197
+ x_conv_t = rearrange(x_conv, 'b d t -> b t d')
198
+
199
+ # ── Input-dependent SSM parameters ────────────────────────────────────
200
+ x_dbl = self.x_proj(x_conv_t) # (B, T, d_rank + 2*d_state)
201
+ dt_raw, B_ssm, C_ssm = x_dbl.split([self.d_rank, self.d_state, self.d_state], dim=-1)
202
+
203
+ # dt: per-channel step size β€” (B, T, d_inner) β†’ (B, d_inner, T)
204
+ dt = F.softplus(self.dt_proj(dt_raw))
205
+ dt = rearrange(dt, 'b t d -> b d t').contiguous()
206
+
207
+ # B, C: (B, d_state, T)
208
+ B_ssm = rearrange(B_ssm, 'b t n -> b n t').contiguous()
209
+ C_ssm = rearrange(C_ssm, 'b t n -> b n t').contiguous()
210
+
211
+ # ── Build A from complex eigenvalue params ────────────────────────────
212
+ A = self._build_real_A() # (d_inner, d_state), negative real
213
+
214
+ # ── Pure Triton Fused Selective SSM Scan ──────────────────────────────
215
+ z_t = rearrange(z, 'b t d -> b d t').contiguous()
216
+ y = fused_triton_ssm(x_conv, dt, A, B_ssm, C_ssm, self.D, z_t)
217
+ y = rearrange(y, 'b d t -> b t d')
218
+
219
+ return self.out_proj(y.to(dtype=x.dtype)) # (B, T, d_model)
220
+
221
+ # ─────────────────────────────────────────────────────────────────────────
222
+ # LOCAL ATTENTION BRANCH
223
+ # ─────────────────────────────────────────────────────────────────────────
224
+
225
+ @torch._dynamo.disable
226
+ def local_attention_branch(
227
+ self,
228
+ x: torch.Tensor, # (B, T, d_model)
229
+ ) -> torch.Tensor:
230
+ """
231
+ Windowed GQA with window size W.
232
+ Uses native PyTorch SDPA with sliding window mask.
233
+ Returns (B, T, d_model).
234
+ """
235
+ B, T, _ = x.shape
236
+ W = self.local_window
237
+
238
+ Q = self.local_q(x) # (B, T, n_heads * head_dim)
239
+ K = self.local_k(x) # (B, T, n_kv_heads * head_dim)
240
+ V = self.local_v(x)
241
+
242
+ Q = rearrange(Q, 'b t (h d) -> b h t d', d=self.head_dim) # (B, H, T, D)
243
+ K = rearrange(K, 'b t (h d) -> b h t d', d=self.head_dim)
244
+ V = rearrange(V, 'b t (h d) -> b h t d', d=self.head_dim)
245
+
246
+ # Apply local RoPE
247
+ Q, K = self.local_rope.apply_rotary(Q, K)
248
+
249
+ # GQA: expand KV to match Q heads
250
+ n_rep = self.local_n_heads // self.local_n_kv_heads
251
+ if n_rep > 1:
252
+ K = K.repeat_interleave(n_rep, dim=1) # (B, H, T, D)
253
+ V = V.repeat_interleave(n_rep, dim=1)
254
+
255
+ # Fast PyTorch SDPA with sliding window mask
256
+ indices = torch.arange(T, device=x.device)
257
+ mask_2d = (indices.unsqueeze(0) <= indices.unsqueeze(1)) & \
258
+ (indices.unsqueeze(0) >= (indices.unsqueeze(1) - W))
259
+ mask_4d = mask_2d.unsqueeze(0).unsqueeze(0)
260
+ attn_out = F.scaled_dot_product_attention(Q, K, V, attn_mask=mask_4d)
261
+ out = rearrange(attn_out, 'b h t d -> b t (h d)')
262
+
263
+ return self.local_o(out) # (B, T, d_model)
264
+
265
+ # ─────────────────────────────────────────────────────────────────────────
266
+ # FORWARD PASS
267
+ # ─────────────────────────────────────────────────────────────────────────
268
+
269
+ def forward(
270
+ self,
271
+ x: torch.Tensor,
272
+ position_offset: int = 0,
273
+ ) -> torch.Tensor:
274
+ """
275
+ x: (B, T, d_model)
276
+ Returns: (B, T, d_model) β€” residual connection applied inside
277
+ """
278
+ residual = x
279
+ x_norm = self.norm(x)
280
+
281
+ # Two branches
282
+ h_recur = self.recurrent_branch(x_norm, position_offset)
283
+ h_local = self.local_attention_branch(x_norm)
284
+
285
+ # Learned gate
286
+ alpha = torch.sigmoid(self.gate_proj(x_norm)) # (B, T, 1)
287
+
288
+ # Blend and add residual
289
+ mixed = alpha * h_local + (1.0 - alpha) * h_recur # (B, T, d_model)
290
+
291
+ return residual + mixed