|
| 1 | +"""GDN Path B — hand-MSL recurrent forward via mx.fast.metal_kernel. |
| 2 | +
|
| 3 | +Adapted from ``mlx-recurrence/mlx_recurrence/gla_scan.py`` (MIT, D-CSIL): |
| 4 | +the GLA recurrence |
| 5 | + h[i] = gate * h[i] + k[i] * v[j] |
| 6 | +is extended to the GDN recurrence (FLA naive form) |
| 7 | + h *= exp(g) # alpha decay |
| 8 | + v_eff[j] = beta * (v[j] - sum_i k[i] * h[i,j]) |
| 9 | + h[i] += k[i] * v_eff[j] |
| 10 | + o[j] = sum_i q[i] * h[i,j] |
| 11 | +
|
| 12 | +Per-thread layout (j fixed, i varies in registers) matches the GLA kernel: |
| 13 | +each thread owns column j of the H_k x H_v state for one (batch, head). |
| 14 | +
|
| 15 | +Backward pass: not implemented in this revision — calls fall back to the |
| 16 | +Path A reference for autograd. Forward kernel can still be used for |
| 17 | +inference benchmarking via the dispatch table. |
| 18 | +
|
| 19 | +API matches ``naive_recurrent_gated_delta_rule`` (returns ``(o, final_state)``). |
| 20 | +Constraints (relaxed in future versions): |
| 21 | + - head_k_dim must equal head_v_dim (same shape per head — matches the |
| 22 | + GLA scan assumption inherited from mlx-recurrence). |
| 23 | + - dtype: all inputs cast to float32 internally (matches FLA naive). |
| 24 | +""" |
| 25 | + |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +import mlx.core as mx |
| 29 | + |
| 30 | +from cppmega_v4._tilelang._kernel_cache import get_or_build_kernel |
| 31 | + |
| 32 | + |
| 33 | +def _gdn_forward_kernel( |
| 34 | + q: mx.array, |
| 35 | + k: mx.array, |
| 36 | + v: mx.array, |
| 37 | + beta: mx.array, |
| 38 | + g: mx.array, |
| 39 | +) -> tuple[mx.array, mx.array]: |
| 40 | + """Metal forward for GDN recurrence. |
| 41 | +
|
| 42 | + Args: |
| 43 | + q, k: [B, T, H, Dh] |
| 44 | + v: [B, T, H, Dh] — must match k's head dim for this kernel |
| 45 | + beta: [B, T, H] |
| 46 | + g: [B, T, H] — gate-decay logit (alpha = exp(g)) |
| 47 | +
|
| 48 | + Returns: |
| 49 | + o: [B, T, H, Dh] |
| 50 | + h_final: [B, H, Dh, Dh] (only the last timestep's state) |
| 51 | + """ |
| 52 | + if q.ndim != 4 or k.shape != q.shape or v.shape != q.shape: |
| 53 | + raise ValueError( |
| 54 | + f"q/k/v must match shape [B, T, H, Dh]; got q={q.shape}, k={k.shape}, v={v.shape}" |
| 55 | + ) |
| 56 | + if beta.shape != q.shape[:3] or g.shape != q.shape[:3]: |
| 57 | + raise ValueError( |
| 58 | + f"beta/g must be [B, T, H]; got beta={beta.shape}, g={g.shape}" |
| 59 | + ) |
| 60 | + |
| 61 | + b, t, h, dh = q.shape |
| 62 | + # Match FLA naive: cast to float32, apply 1/sqrt(Dh) scale to q. |
| 63 | + q = q.astype(mx.float32) * (dh ** -0.5) |
| 64 | + k = k.astype(mx.float32) |
| 65 | + v = v.astype(mx.float32) |
| 66 | + beta = beta.astype(mx.float32) |
| 67 | + g = g.astype(mx.float32) |
| 68 | + |
| 69 | + q_flat = q.reshape(-1) |
| 70 | + k_flat = k.reshape(-1) |
| 71 | + v_flat = v.reshape(-1) |
| 72 | + beta_flat = beta.reshape(-1) |
| 73 | + g_flat = g.reshape(-1) |
| 74 | + |
| 75 | + source = f""" |
| 76 | + uint j = thread_position_in_grid.x; |
| 77 | + uint bh = thread_position_in_grid.y; |
| 78 | +
|
| 79 | + if (j >= {dh}u || bh >= {b * h}u) return; |
| 80 | +
|
| 81 | + uint bb = bh / {h}u; |
| 82 | + uint head = bh % {h}u; |
| 83 | +
|
| 84 | + // Thread-local state: one column of the Dh x Dh state matrix |
| 85 | + float state[{dh}]; |
| 86 | + for (int i = 0; i < {dh}; i++) state[i] = 0.0f; |
| 87 | +
|
| 88 | + for (int ti = 0; ti < {t}; ti++) {{ |
| 89 | + int g_idx = bb * {t * h} + ti * {h} + head; |
| 90 | + float alpha_t = exp(g[g_idx]); |
| 91 | + float beta_t = beta[g_idx]; |
| 92 | +
|
| 93 | + int kv_base = (bb * {t} + ti) * {h * dh} + head * {dh}; |
| 94 | + float v_j = v[kv_base + j]; |
| 95 | +
|
| 96 | + // Phase 1: alpha decay (per FLA naive: applied BEFORE delta) |
| 97 | + for (int i = 0; i < {dh}; i++) state[i] *= alpha_t; |
| 98 | +
|
| 99 | + // Phase 2: kth_S_j = sum_i k[i] * state[i, j] (own column) |
| 100 | + float kth_S_j = 0.0f; |
| 101 | + for (int i = 0; i < {dh}; i++) {{ |
| 102 | + float k_i = k[kv_base + i]; |
| 103 | + kth_S_j += k_i * state[i]; |
| 104 | + }} |
| 105 | +
|
| 106 | + // Phase 3: v_eff = beta * (v - kth_S) |
| 107 | + float v_eff_j = beta_t * (v_j - kth_S_j); |
| 108 | +
|
| 109 | + // Phase 4: state[i] += k[i] * v_eff_j and o[j] = sum_i q[i] * state[i] |
| 110 | + float o_j = 0.0f; |
| 111 | + for (int i = 0; i < {dh}; i++) {{ |
| 112 | + float k_i = k[kv_base + i]; |
| 113 | + float q_i = q[kv_base + i]; |
| 114 | + state[i] += k_i * v_eff_j; |
| 115 | + o_j += q_i * state[i]; |
| 116 | + }} |
| 117 | +
|
| 118 | + output[kv_base + j] = o_j; |
| 119 | + }} |
| 120 | +
|
| 121 | + // Write final state column for this thread (if requested by caller) |
| 122 | + int sf_base = (bb * {h} + head) * {dh * dh} + j; |
| 123 | + for (int i = 0; i < {dh}; i++) {{ |
| 124 | + state_final[sf_base + i * {dh}] = state[i]; |
| 125 | + }} |
| 126 | + """ |
| 127 | + |
| 128 | + kernel_name = f"v4_gdn_fwd_{b}_{t}_{h}_{dh}" |
| 129 | + kernel = get_or_build_kernel( |
| 130 | + name=kernel_name, |
| 131 | + input_names=["q", "k", "v", "beta", "g"], |
| 132 | + output_names=["output", "state_final"], |
| 133 | + source=source, |
| 134 | + ) |
| 135 | + |
| 136 | + grid = (dh, b * h, 1) |
| 137 | + tg_x = min(dh, 64) |
| 138 | + threadgroup = (tg_x, 1, 1) |
| 139 | + |
| 140 | + results = kernel( |
| 141 | + inputs=[q_flat, k_flat, v_flat, beta_flat, g_flat], |
| 142 | + output_shapes=[ |
| 143 | + (b * t * h * dh,), |
| 144 | + (b * h * dh * dh,), |
| 145 | + ], |
| 146 | + output_dtypes=[mx.float32, mx.float32], |
| 147 | + grid=grid, |
| 148 | + threadgroup=threadgroup, |
| 149 | + ) |
| 150 | + o = results[0].reshape(b, t, h, dh) |
| 151 | + state_final = results[1].reshape(b, h, dh, dh) |
| 152 | + return o, state_final |
| 153 | + |
| 154 | + |
| 155 | +def gdn_forward_path_b( |
| 156 | + q: mx.array, |
| 157 | + k: mx.array, |
| 158 | + v: mx.array, |
| 159 | + beta: mx.array, |
| 160 | + g: mx.array, |
| 161 | + *, |
| 162 | + scale: float | None = None, |
| 163 | + initial_state: mx.array | None = None, |
| 164 | + output_final_state: bool = False, |
| 165 | +): |
| 166 | + """Path B forward, signature matching ``naive_recurrent_gated_delta_rule``. |
| 167 | +
|
| 168 | + Constraints: |
| 169 | + - ``initial_state`` not supported in this revision (must be None); |
| 170 | + falls back to zero-init inside the kernel. |
| 171 | + - ``scale`` not supported (uses 1/sqrt(Dh) per FLA convention). |
| 172 | + - ``head_k_dim == head_v_dim`` required. |
| 173 | +
|
| 174 | + On unsupported configs returns the Path A reference output instead so |
| 175 | + the dispatch never silently produces wrong numerics. |
| 176 | + """ |
| 177 | + if initial_state is not None or scale is not None or v.shape[-1] != k.shape[-1]: |
| 178 | + # Fall through to Path A for cases this kernel doesn't yet cover. |
| 179 | + from cppmega_v4.nn._external.fla_naive_gated_delta_rule import ( |
| 180 | + naive_recurrent_gated_delta_rule, |
| 181 | + ) |
| 182 | + return naive_recurrent_gated_delta_rule( |
| 183 | + q, k, v, beta, g, |
| 184 | + scale=scale, initial_state=initial_state, |
| 185 | + output_final_state=output_final_state, |
| 186 | + ) |
| 187 | + o, sf = _gdn_forward_kernel(q, k, v, beta, g) |
| 188 | + return o, (sf if output_final_state else None) |
| 189 | + |
| 190 | + |
| 191 | +__all__ = ["gdn_forward_path_b"] |
0 commit comments