MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / forward / gemma4_26b.py
| 1 | """Gemma4 26B forward — shared dense FFN + per-expert MXFP4 MoE. |
| 2 | Architecture: llama.cpp CANNOT run this (no MXFP4 support). MojoLlama CAN. |
| 3 | |
| 4 | Gemma4 26B has alternating head dimensions: |
| 5 | - Most layers: Q_dim=4096 (NH=16, HD=256), K_dim=2048 (NKH=2) |
| 6 | - Every 6th layer (5, 11, 17, 23, 29): Q_dim=8192 (HD=512), K_dim=1024 (HD=512) |
| 7 | Detected per-layer from q_norm_w.shape. |
| 8 | """ |
| 9 | import numpy as np, ctypes |
| 10 | from forward.base import ArchitectureForwardPass |
| 11 | |
| 12 | class ForwardGemma4_26B(ArchitectureForwardPass): |
| 13 | def __init__(self, engine): |
| 14 | super().__init__(engine) |
| 15 | self._cos_table, self._sin_table = {}, {} |
| 16 | self._per_layer_hd = None |
| 17 | self._max_hd = 256 |
| 18 | |
| 19 | def init_weights(self, *a): pass |
| 20 | def init_pointers(self, *a): pass |
| 21 | def init_buffers(self): |
| 22 | """Detect per-layer HD and resize buffers for max (512).""" |
| 23 | e = self.engine |
| 24 | self._per_layer_hd = [] |
| 25 | self._max_hd = 256 |
| 26 | for i in range(e.n_layers): |
| 27 | lw = e._layers[i] |
| 28 | hd = lw.q_norm_w.shape[0] if lw.has_q_norm else 256 |
| 29 | self._per_layer_hd.append(hd) |
| 30 | if hd > self._max_hd: |
| 31 | self._max_hd = hd |
| 32 | max_nk = e.n_kv_head * self._max_hd |
| 33 | # Q/K buffers for max HD |
| 34 | q_need = e.n_head * self._max_hd |
| 35 | k_need = e.n_kv_head * self._max_hd |
| 36 | if len(e._q) < q_need: |
| 37 | e._q = np.zeros(q_need, dtype=np.float32) |
| 38 | e._p_q = e._q.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 39 | if len(e._k) < k_need: |
| 40 | e._k = np.zeros(k_need, dtype=np.float32) |
| 41 | e._p_k = e._k.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 42 | if len(e._att_out) < q_need: |
| 43 | e._att_out = np.zeros(q_need, dtype=np.float32) |
| 44 | e._p_att_out = e._att_out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 45 | # KV cache for max HD |
| 46 | if e.kv_k.shape[2] < max_nk: |
| 47 | old = e.kv_k |
| 48 | e.kv_k = np.zeros((e.n_layers, 4096, max_nk), dtype=np.float32) |
| 49 | e.kv_k[:, :old.shape[1], :old.shape[2]] = old[:, :, :] |
| 50 | old = e.kv_v |
| 51 | e.kv_v = np.zeros((e.n_layers, 4096, max_nk), dtype=np.float32) |
| 52 | e.kv_v[:, :old.shape[1], :old.shape[2]] = old[:, :, :] |
| 53 | |
| 54 | def reset_state(self): pass |
| 55 | |
| 56 | def _rope(self, x, pos, n_heads, hd, rope_dim): |
| 57 | half = rope_dim // 2 |
| 58 | theta = 1000000.0 |
| 59 | key = (theta, pos, half) |
| 60 | if key not in self._cos_table: |
| 61 | freqs = theta ** (-np.arange(0, rope_dim, 2, dtype=np.float64) / rope_dim) |
| 62 | self._cos_table[key] = np.cos(pos * freqs).astype(np.float32) |
| 63 | self._sin_table[key] = np.sin(pos * freqs).astype(np.float32) |
| 64 | c, s = self._cos_table[key], self._sin_table[key] |
| 65 | x2 = x.reshape(n_heads, hd) |
| 66 | out = x2.copy() |
| 67 | out[:, :half] = x2[:, :half] * c - x2[:, half:rope_dim] * s |
| 68 | out[:, half:rope_dim] = x2[:, half:rope_dim] * c + x2[:, :half] * s |
| 69 | return out.reshape(-1) |
| 70 | |
| 71 | def _gate_up_ptrs(self, me, l): |
| 72 | import ctypes as ct |
| 73 | if not hasattr(self, '_gate_up_ptr_cache'): |
| 74 | self._gate_up_ptr_cache = {} |
| 75 | if l in self._gate_up_ptr_cache: |
| 76 | return self._gate_up_ptr_cache[l] |
| 77 | e = self.engine |
| 78 | name = f'blk.{l}.ffn_gate_up_exps.weight' |
| 79 | if name not in e.raw_weights: |
| 80 | self._gate_up_ptr_cache[l] = None |
| 81 | return None |
| 82 | raw = e.raw_weights[name] |
| 83 | base_addr = raw.ctypes.data |
| 84 | per_exp = 2106368 |
| 85 | ptrs = [] |
| 86 | cu = ct.POINTER(ct.c_uint8) |
| 87 | for exp in range(128): |
| 88 | addr = base_addr + exp * per_exp |
| 89 | ptrs.append(ct.cast(addr, cu)) |
| 90 | arr_type = cu * 128 |
| 91 | self._gate_up_ptr_cache[l] = arr_type(*ptrs) |
| 92 | return self._gate_up_ptr_cache[l] |
| 93 | |
| 94 | def forward(self, token_id): |
| 95 | e = self.engine; N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head |
| 96 | L = e.n_layers; FF = e.n_ff; V = e.vocab_size |
| 97 | b_x = e._x; b_r = e._residual; b_xn = e._x_norm |
| 98 | b_oproj = e._o_proj |
| 99 | b_gate = e._gate; b_up = e._up; b_silu = e._silu_gate; b_ffn = e._ffn_out |
| 100 | b_log = e._logits |
| 101 | kern = e._kern; simd = e._simd; eps = e._eps_f |
| 102 | cf = ctypes.POINTER(ctypes.c_float); ci = ctypes.c_int; cu = ctypes.POINTER(ctypes.c_uint8) |
| 103 | |
| 104 | np.copyto(b_x, e.emb[token_id]) |
| 105 | |
| 106 | for i in range(L): |
| 107 | lw = e._layers[i]; me = e._moe_layers[i] |
| 108 | hd = self._per_layer_hd[i] |
| 109 | nq = NH * hd; nk = NKH * hd |
| 110 | b_q = e._q[:nq]; b_k = e._k[:nk]; b_v = e._k[:nk]; b_att = e._att_out[:nq] |
| 111 | |
| 112 | # Attention |
| 113 | np.clip(b_x, -1000.0, 1000.0, out=b_x) |
| 114 | np.copyto(b_r, b_x) |
| 115 | simd.rms_norm(b_xn.ctypes.data_as(cf), b_x.ctypes.data_as(cf), |
| 116 | lw.attn_norm_w.ctypes.data_as(cf), N, eps) |
| 117 | kern.quant_matmul_omp(lw.attn_q_raw, b_xn.ctypes.data_as(cf), b_q.ctypes.data_as(cf), |
| 118 | lw.attn_q_nr, lw.attn_q_nc, lw.attn_q_qt) |
| 119 | kern.quant_matmul_omp(lw.attn_k_raw, b_xn.ctypes.data_as(cf), b_k.ctypes.data_as(cf), |
| 120 | lw.attn_k_nr, lw.attn_k_nc, lw.attn_k_qt) |
| 121 | b_v[:nk] = b_k[:nk] |
| 122 | if lw.has_q_norm: |
| 123 | q2d = b_q.reshape(NH, hd) |
| 124 | qrms = np.sqrt(np.mean(q2d*q2d, axis=1, keepdims=True) + 1e-6) |
| 125 | q2d[:] = q2d / qrms * lw.q_norm_w.reshape(1, hd) |
| 126 | if lw.has_k_norm: |
| 127 | k2d = b_k[:nk].reshape(NKH, hd) |
| 128 | krms = np.sqrt(np.mean(k2d*k2d, axis=1, keepdims=True) + 1e-6) |
| 129 | k2d[:] = k2d / krms * lw.k_norm_w.reshape(1, hd) |
| 130 | rd = min(hd, 256) |
| 131 | b_q[:] = self._rope(b_q, e.pos, NH, hd, rd) |
| 132 | b_k[:nk] = self._rope(b_k[:nk], e.pos, NKH, hd, rd) |
| 133 | e.kv_k[i, e.kv_len[i], :nk] = b_k[:nk] |
| 134 | e.kv_v[i, e.kv_len[i], :nk] = b_v[:nk] |
| 135 | sl = e.kv_len[i] + 1; e.kv_len[i] += 1 |
| 136 | # GQA attention |
| 137 | gr = NH // NKH |
| 138 | kc = e.kv_k[i, :sl, :nk].reshape(sl, NKH, hd) |
| 139 | q2d = b_q.reshape(NH, hd); qg = q2d.reshape(NKH, gr, hd) |
| 140 | kt = kc.transpose(1, 0, 2) |
| 141 | sc = np.einsum('khd,ksd->khs', qg, kt) / np.sqrt(float(hd)) |
| 142 | s2 = sc.reshape(NH, sl) |
| 143 | s2 -= np.max(s2, axis=1, keepdims=True) |
| 144 | np.exp(s2, out=s2); s2 /= np.sum(s2, axis=1, keepdims=True) |
| 145 | at = np.einsum('khs,ksd->khd', s2.reshape(NKH, gr, sl), kc.transpose(1, 0, 2)) |
| 146 | b_att[:] = at.reshape(-1) |
| 147 | # O proj + residual |
| 148 | kern.quant_matmul_omp(lw.attn_out_raw, b_att.ctypes.data_as(cf), b_oproj.ctypes.data_as(cf), |
| 149 | lw.attn_out_nr, lw.attn_out_nc, lw.attn_out_qt) |
| 150 | b_x[:N] = b_r[:N] * getattr(lw, 'res_scale_res_w', 1.0) |
| 151 | if hasattr(lw, 'res_scale_res_b'): b_x[:N] += lw.res_scale_res_b |
| 152 | b_x[:N] += b_oproj[:N] * getattr(lw, 'res_scale_hs_w', 1.0) |
| 153 | if hasattr(lw, 'res_scale_hs_b'): b_x[:N] += lw.res_scale_hs_b |
| 154 | |
| 155 | # FFN (shared dense + MoE) |
| 156 | np.clip(b_x, -1000.0, 1000.0, out=b_x) |
| 157 | np.copyto(b_r, b_x) |
| 158 | simd.rms_norm(b_xn.ctypes.data_as(cf), b_x.ctypes.data_as(cf), |
| 159 | lw.ffn_norm_w.ctypes.data_as(cf), N, eps) |
| 160 | # Shared dense |
| 161 | kern.quant_matmul_omp(lw.ffn_gate_raw, b_xn.ctypes.data_as(cf), b_gate.ctypes.data_as(cf), |
| 162 | lw.ffn_gate_nr, lw.ffn_gate_nc, lw.ffn_gate_qt) |
| 163 | kern.quant_matmul_omp(lw.ffn_up_raw, b_xn.ctypes.data_as(cf), b_up.ctypes.data_as(cf), |
| 164 | lw.ffn_up_nr, lw.ffn_up_nc, lw.ffn_up_qt) |
| 165 | b_silu[:FF] = b_gate[:FF] / (1.0 + np.exp(-np.clip(b_gate[:FF], -80, 80))) |
| 166 | b_silu[:FF] *= b_up[:FF] |
| 167 | kern.quant_matmul_omp(lw.ffn_down_raw, b_silu.ctypes.data_as(cf), b_ffn.ctypes.data_as(cf), |
| 168 | lw.ffn_down_nr, lw.ffn_down_nc, lw.ffn_down_qt) |
| 169 | # MoE per-expert |
| 170 | moe_ffn = np.zeros(N, dtype=np.float32) |
| 171 | if me.router_f32 is not None: |
| 172 | scores = me.router_f32 @ b_xn |
| 173 | scores -= np.max(scores) |
| 174 | np.exp(scores, out=scores); scores /= np.sum(scores) |
| 175 | top_k = min(e.n_experts_per_tok, 8) |
| 176 | top_idx = np.argpartition(scores, -top_k)[-top_k:] |
| 177 | top_wt = scores[top_idx] / np.sum(scores[top_idx]) |
| 178 | gu_ptrs = self._gate_up_ptrs(me, i) |
| 179 | if gu_ptrs is not None and me.down_ptrs_arr is not None: |
| 180 | for exp, wt in zip(top_idx, top_wt): |
| 181 | if wt < 0.01: continue |
| 182 | gu_out = np.zeros(1408, dtype=np.float32) |
| 183 | if hasattr(e._cengine, 'mxfp4_batch_matmul'): |
| 184 | e._cengine.mxfp4_batch_matmul( |
| 185 | gu_ptrs[exp], b_xn.ctypes.data_as(cf), |
| 186 | gu_out.ctypes.data_as(cf), ci(1408), ci(2816), ci(1)) |
| 187 | else: |
| 188 | kern.quant_matmul_omp(gu_ptrs[exp], b_xn.ctypes.data_as(cf), |
| 189 | gu_out.ctypes.data_as(cf), |
| 190 | ci(1408), ci(2816), ci(39)) |
| 191 | g = gu_out[:704]; u = gu_out[704:] |
| 192 | # Clip to prevent overflow in g*u (Gemma4 26B experts produce large values) |
| 193 | g = np.clip(g, -1e10, 1e10) |
| 194 | u = np.clip(u, -1e10, 1e10) |
| 195 | g = g / (1.0 + np.exp(-np.clip(g, -80, 80))) |
| 196 | g_u = g * u |
| 197 | exp_out = np.zeros(N, dtype=np.float32) |
| 198 | if hasattr(e._cengine, 'mxfp4_batch_matmul'): |
| 199 | e._cengine.mxfp4_batch_matmul( |
| 200 | me.down_ptrs_arr[exp], g_u.ctypes.data_as(cf), |
| 201 | exp_out.ctypes.data_as(cf), ci(N), ci(704), ci(1)) |
| 202 | else: |
| 203 | kern.quant_matmul_omp(me.down_ptrs_arr[exp], g_u.ctypes.data_as(cf), |
| 204 | exp_out.ctypes.data_as(cf), |
| 205 | me.down_nr, me.down_nc, me.down_qt) |
| 206 | moe_ffn += wt * exp_out |
| 207 | b_ffn[:N] += moe_ffn |
| 208 | b_x[:N] = b_r[:N] * getattr(lw, 'res_scale_res_w', 1.0) |
| 209 | if hasattr(lw, 'res_scale_res_b'): b_x[:N] += lw.res_scale_res_b |
| 210 | b_x[:N] += b_ffn[:N] * getattr(lw, 'res_scale_hs_w', 1.0) |
| 211 | if hasattr(lw, 'res_scale_hs_b'): b_x[:N] += lw.res_scale_hs_b |
| 212 | |
| 213 | # Final norm + output |
| 214 | np.clip(b_x, -1000.0, 1000.0, out=b_x) |
| 215 | simd.rms_norm(b_xn.ctypes.data_as(cf), b_x.ctypes.data_as(cf), |
| 216 | e._out_norm_w.ctypes.data_as(cf), N, eps) |
| 217 | # Output: b_log = emb @ x_norm |
| 218 | np.dot(e.emb, b_xn, out=b_log[:V]) |
| 219 | e.pos += 1 |
| 220 | return b_log |