MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / forward / zaya.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ZAYA-8B forward pass — optimized. Interleaved ATTN / MoE+MoD.""" |
| 3 | import numpy as np, ctypes, os, gguf |
| 4 | from gguf.constants import GGMLQuantizationType as QT |
| 5 | from forward.base import ArchitectureForwardPass |
| 6 | |
| 7 | GGML_Q4_K=12; GGML_Q6_K=14 |
| 8 | C_KERNEL_TYPES = {GGML_Q4_K, GGML_Q6_K} |
| 9 | BLOCK_SIZES = {12:144, 14:210, 2:18, 3:20, 8:34, 13:176, 39:17} |
| 10 | BLOCK_VALS = {12:256, 14:256, 2:32, 3:32, 8:32, 13:256, 39:32} |
| 11 | |
| 12 | class ForwardZaya(ArchitectureForwardPass): |
| 13 | def __init__(self, engine): |
| 14 | super().__init__(engine) |
| 15 | e = engine |
| 16 | # Use engine's thread count (MXFP4 benefits from multi-threading) |
| 17 | nt = max(1, getattr(e, 'n_threads', 1)) |
| 18 | os.environ['OMP_NUM_THREADS'] = str(nt) |
| 19 | e.vocab_size = 262272 |
| 20 | e.head_dim = 128 |
| 21 | e.rope_dim = 64 |
| 22 | self._cos_table = {} |
| 23 | self._sin_table = {} |
| 24 | self._fused_gate_up = np.zeros(4096, dtype=np.float32) |
| 25 | |
| 26 | def init_weights(self, weights, raw_weights, weight_info, weight_qtypes): |
| 27 | e = self.engine |
| 28 | for t in e.reader.tensors: |
| 29 | if t.name in ('token_embd.weight', 'model.embed_tokens.weight'): |
| 30 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) |
| 31 | in_dim, out_dim = int(t.shape[0]), int(t.shape[1]) |
| 32 | arr = np.ascontiguousarray(f32.reshape(out_dim, in_dim)) |
| 33 | # Ensure correct orientation: [vocab_size, n_embd] |
| 34 | if arr.shape[1] != e.n_embd: |
| 35 | arr = np.ascontiguousarray(arr.T) |
| 36 | e.emb = arr |
| 37 | break |
| 38 | if e.emb is not None and e._kern is not None: |
| 39 | pass # Output via np.dot |
| 40 | |
| 41 | def init_pointers(self, layer_idx, pfx, lw): |
| 42 | """Set per-layer weight pointers.""" |
| 43 | e = self.engine |
| 44 | weights = e.weights |
| 45 | raw = e.raw_weights |
| 46 | wi = e.weight_info |
| 47 | cu_p = ctypes.POINTER(ctypes.c_uint8) |
| 48 | |
| 49 | # Norm + scaling (always present) |
| 50 | lw.attn_norm_w = weights.get(f'{pfx}.attn_norm.weight') |
| 51 | lw.res_scale_hs_w = weights.get(f'{pfx}.res_scale_hs.weight', |
| 52 | np.ones(e.n_embd, dtype=np.float32)).ravel() |
| 53 | lw.res_scale_hs_b = weights.get(f'{pfx}.res_scale_hs.bias', |
| 54 | np.zeros(e.n_embd, dtype=np.float32)).ravel() |
| 55 | rw = weights.get(f'{pfx}.res_scale_res.weight') |
| 56 | lw.res_scale_res_w = rw.ravel() if rw is not None else np.ones(e.n_embd, dtype=np.float32) |
| 57 | rb = weights.get(f'{pfx}.res_scale_res.bias') |
| 58 | lw.res_scale_res_b = rb.ravel() if rb is not None else np.zeros(e.n_embd, dtype=np.float32) |
| 59 | |
| 60 | if layer_idx % 2 == 1: # MoE layers |
| 61 | lw.ffn_gate_inp_w = weights.get(f'{pfx}.ffn_gate_inp.weight') |
| 62 | lw.ffn_gate_inp_b = weights.get(f'{pfx}.ffn_gate_inp.bias') |
| 63 | if lw.ffn_gate_inp_b is not None: |
| 64 | lw.ffn_gate_inp_b = lw.ffn_gate_inp_b.ravel() |
| 65 | lw.ffn_gate_w = weights.get(f'{pfx}.ffn_gate.weight') |
| 66 | lw.ffn_gate_b = weights.get(f'{pfx}.ffn_gate.bias') |
| 67 | if lw.ffn_gate_b is not None: |
| 68 | lw.ffn_gate_b = lw.ffn_gate_b.ravel() |
| 69 | lw.ffn_norm_w = weights.get(f'{pfx}.ffn_norm.weight') |
| 70 | lw.zaya_router_mlp2_w = weights.get(f'{pfx}.zaya_router_mlp2.weight') |
| 71 | lw.zaya_router_mlp2_b = weights.get(f'{pfx}.zaya_router_mlp2.bias') |
| 72 | if lw.zaya_router_mlp2_b is not None: |
| 73 | lw.zaya_router_mlp2_b = lw.zaya_router_mlp2_b.ravel() |
| 74 | lw.zaya_router_mlp4_w = weights.get(f'{pfx}.zaya_router_mlp4.weight') |
| 75 | lw.zaya_router_biases_w = weights.get(f'{pfx}.zaya_router_biases.weight') |
| 76 | if lw.zaya_router_biases_w is not None: |
| 77 | lw.zaya_router_biases_w = lw.zaya_router_biases_w.ravel() |
| 78 | |
| 79 | # Load expert raw pointers — try per-expert first, then packed 3D |
| 80 | cu_p = ctypes.POINTER(ctypes.c_uint8) |
| 81 | n_exp = e.n_experts or 16 |
| 82 | for attr, wname in [('gate_up', 'ffn_gate_up_exps'), ('down', 'ffn_down_exps')]: |
| 83 | ptrs, info = [], None |
| 84 | # Try per-expert format: blk.N.wname.E.weight |
| 85 | per_exp = any(e.raw_weights.get(f'{pfx}.{wname}.{ex}.weight') is not None for ex in range(1)) |
| 86 | if per_exp: |
| 87 | for exp in range(n_exp): |
| 88 | eqname = f'{pfx}.{wname}.{exp}.weight' |
| 89 | raw = e.raw_weights.get(eqname) |
| 90 | winfo = e.weight_info.get(eqname) |
| 91 | if raw is not None and winfo is not None: |
| 92 | ptr = raw.ctypes.data_as(cu_p) |
| 93 | ptrs.append(ptr) |
| 94 | if info is None: |
| 95 | info = (winfo[0], winfo[1], winfo[3]) |
| 96 | else: |
| 97 | ptrs.append(ctypes.cast(0, cu_p)) |
| 98 | else: |
| 99 | # Packed 3D format: blk.N.wname.weight [out_dim, in_dim, n_exp] |
| 100 | pname = f'{pfx}.{wname}.weight' |
| 101 | raw = e.raw_weights.get(pname) |
| 102 | winfo = e.weight_info.get(pname) |
| 103 | if raw is not None and winfo is not None: |
| 104 | out_dim, in_dim, bs, qt, n_exp2 = winfo |
| 105 | bv = {8: 32, 12: 256, 14: 256, 39: 32}.get(qt, 32) |
| 106 | rb = ((in_dim + bv - 1) // bv) * bs |
| 107 | eb = out_dim * rb |
| 108 | raw_ptr = raw.ctypes.data_as(cu_p) |
| 109 | info = (out_dim, in_dim, qt) |
| 110 | for exp in range(n_exp2): |
| 111 | addr = ctypes.addressof(raw_ptr.contents) + exp * eb |
| 112 | ptrs.append(ctypes.cast(addr, cu_p)) |
| 113 | if ptrs: |
| 114 | arr_type = cu_p * n_exp |
| 115 | setattr(lw, f'{attr}_ptrs', arr_type(*ptrs)) |
| 116 | if info: |
| 117 | setattr(lw, f'{attr}_info', info) |
| 118 | |
| 119 | def _rope(self, x, pos, n_heads, hd): |
| 120 | half = self.engine.rope_dim // 2 |
| 121 | theta = 5000000.0 |
| 122 | key = (theta, pos, half) |
| 123 | if key not in self._cos_table: |
| 124 | f = theta ** (np.arange(0, self.engine.rope_dim, 2, dtype=np.float32) / self.engine.rope_dim) |
| 125 | self._cos_table[key] = np.cos(pos / f).astype(np.float32) |
| 126 | self._sin_table[key] = np.sin(pos / f).astype(np.float32) |
| 127 | c, s = self._cos_table[key], self._sin_table[key] |
| 128 | x2 = x.reshape(n_heads, hd) |
| 129 | o = x2.copy() |
| 130 | o[:, :half] = x2[:, :half] * c - x2[:, half:self.engine.rope_dim] * s |
| 131 | o[:, half:self.engine.rope_dim] = x2[:, half:self.engine.rope_dim] * c + x2[:, :half] * s |
| 132 | return o.reshape(-1) |
| 133 | |
| 134 | def forward(self, token_id): |
| 135 | e = self.engine |
| 136 | N = e.n_embd; NH = e.n_head; NKH = e.n_kv_head; HD = e.head_dim; L = e.n_layers |
| 137 | NQ = NH * HD; NK = NKH * HD |
| 138 | |
| 139 | b_x = e._x; b_r = e._residual; b_xn = e._x_norm |
| 140 | b_q = e._q; b_k = e._k[:NK]; b_v = e._k[:NK] |
| 141 | b_att = e._att_out; b_up = e._up; b_silu = e._silu_gate |
| 142 | b_ffn = e._ffn_out; b_oproj = e._o_proj; b_log = e._logits |
| 143 | |
| 144 | kern = e._kern; simd = e._simd; eps = e._eps_f |
| 145 | cf = ctypes.POINTER(ctypes.c_float); ci = ctypes.c_int; cu = ctypes.POINTER(ctypes.c_uint8) |
| 146 | |
| 147 | # Use cengine's mxfp4 matmul for MXFP4 model (type 39) |
| 148 | ce = getattr(e, '_cengine', None) |
| 149 | if ce is not None and not hasattr(ce, '_mxfp4_ready'): |
| 150 | ce.mxfp4_batch_matmul.argtypes = [cu, cf, cf, ci, ci, ci] |
| 151 | ce.mxfp4_batch_matmul.restype = None |
| 152 | ce._mxfp4_ready = True |
| 153 | # Use ce's mxfp4 matmul when qt == 39 (MXFP4) |
| 154 | _mxm_ce_count = [0] |
| 155 | def mxm(w, x, out, nr, nc, qt): |
| 156 | qtv = qt.value if isinstance(qt, ctypes.c_int) else qt |
| 157 | if qtv == 39: |
| 158 | _mxm_ce_count[0] += 1 |
| 159 | ce.mxfp4_batch_matmul(w, x, out, nr, nc, ci(1)) |
| 160 | else: |
| 161 | kern.quant_matmul_omp(w, x, out, nr, nc, qt) |
| 162 | import forward.zaya as _zmod_mxm |
| 163 | _zmod_mxm._mxm_ce_count = _mxm_ce_count |
| 164 | |
| 165 | np.copyto(b_x, e.emb[token_id]) |
| 166 | |
| 167 | for i in range(L): |
| 168 | lw = e._layers[i] |
| 169 | np.clip(b_x, -1000.0, 1000.0, out=b_x) |
| 170 | np.copyto(b_r, b_x) |
| 171 | simd.rms_norm(e._p_x_norm, e._p_x, lw.attn_norm_w.ctypes.data_as(cf), N, eps) |
| 172 | |
| 173 | if i % 2 == 0: # ATTN layer |
| 174 | mxm(lw.attn_q_raw, e._p_x_norm, e._p_q, ci(NQ), ci(N), lw.attn_q_qt) |
| 175 | mxm(lw.attn_k_raw, e._p_x_norm, e._p_k, ci(NK), ci(N), lw.attn_k_qt) |
| 176 | |
| 177 | b_q[:] = self._rope(b_q, e.pos, NH, HD) |
| 178 | b_k[:NK] = self._rope(b_k[:NK], e.pos, NKH, HD) |
| 179 | |
| 180 | e.kv_k[i, e.kv_len[i], :NK] = b_k[:NK] |
| 181 | b_v[:] = b_k[:NK] |
| 182 | sl = e.kv_len[i] + 1 |
| 183 | kc = e.kv_k[i, :sl, :NK].reshape(sl, NKH, HD) |
| 184 | q2 = b_q.reshape(NH, HD) |
| 185 | gr = NH // NKH |
| 186 | qg = q2.reshape(NKH, gr, HD) |
| 187 | kt = kc.transpose(1, 0, 2) |
| 188 | sc = np.einsum('khd,ksd->khs', qg, kt) / np.sqrt(float(HD)) |
| 189 | s2 = sc.reshape(NH, sl) |
| 190 | s2 -= np.max(s2, axis=1, keepdims=True) |
| 191 | np.exp(s2, out=s2); s2 /= np.sum(s2, axis=1, keepdims=True) |
| 192 | at = np.einsum('khs,ksd->khd', s2.reshape(NKH, gr, sl), kc.transpose(1, 0, 2)) |
| 193 | b_att[:NQ] = at.reshape(-1) |
| 194 | e.kv_len[i] += 1 |
| 195 | |
| 196 | mxm(lw.attn_out_raw, e._p_att_out, e._p_o_proj, |
| 197 | lw.attn_out_nr, lw.attn_out_nc, lw.attn_out_qt) |
| 198 | b_x[:N] = b_r[:N] * lw.res_scale_res_w + lw.res_scale_res_b + \ |
| 199 | b_oproj[:N] * lw.res_scale_hs_w + lw.res_scale_hs_b |
| 200 | else: # MoE layer |
| 201 | h = lw.ffn_gate_inp_w @ b_xn |
| 202 | if lw.ffn_gate_inp_b is not None: h += lw.ffn_gate_inp_b |
| 203 | h = lw.ffn_gate_w @ h |
| 204 | if lw.ffn_gate_b is not None: h += lw.ffn_gate_b |
| 205 | h = 0.5 * h * (1.0 + np.tanh(np.sqrt(2.0/np.pi) * (h + 0.044715 * h * h * h))) |
| 206 | h = lw.zaya_router_mlp2_w @ h |
| 207 | if lw.zaya_router_mlp2_b is not None: h += lw.zaya_router_mlp2_b |
| 208 | ms = lw.zaya_router_mlp4_w @ h |
| 209 | if lw.zaya_router_biases_w is not None: ms += lw.zaya_router_biases_w |
| 210 | ms -= np.max(ms); np.exp(ms, out=ms); ms /= np.sum(ms) |
| 211 | |
| 212 | ec = int(np.argmax(ms)); ew = float(ms[ec]) |
| 213 | if ec < 16 and ew > 0.01: |
| 214 | ew /= ms[:16].sum() |
| 215 | od, id_, qt = lw.gate_up_info |
| 216 | mxm(lw.gate_up_ptrs[ec], e._p_x_norm, |
| 217 | self._fused_gate_up.ctypes.data_as(cf), |
| 218 | ci(od), ci(id_), ci(qt)) |
| 219 | F2 = od // 2 # 2048 |
| 220 | np.copyto(b_silu[:F2], self._fused_gate_up[:F2]) |
| 221 | np.copyto(b_up[:F2], self._fused_gate_up[F2:]) |
| 222 | b_silu[:F2] = b_silu[:F2] / (1.0 + np.exp(-b_silu[:F2])) |
| 223 | b_silu[:F2] *= b_up[:F2] |
| 224 | |
| 225 | od2, id2, qt2 = lw.down_info |
| 226 | mxm(lw.down_ptrs[ec], e._p_silu_gate, e._p_ffn, |
| 227 | ci(od2), ci(id2), ci(qt2)) |
| 228 | b_ffn[:N] *= ew |
| 229 | else: |
| 230 | b_ffn[:N] = 0.0 |
| 231 | |
| 232 | b_x[:N] = b_r[:N] * lw.res_scale_res_w + lw.res_scale_res_b + \ |
| 233 | b_ffn[:N] * lw.res_scale_hs_w + lw.res_scale_hs_b |
| 234 | |
| 235 | np.clip(b_x, -1000.0, 1000.0, out=b_x) |
| 236 | simd.rms_norm(e._p_x_norm, e._p_x, e._out_norm_w.ctypes.data_as(cf), N, eps) |
| 237 | np.dot(e.emb, b_xn, out=b_log[:e.emb.shape[0]]) |
| 238 | e.pos += 1 |
| 239 | return b_log |