Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/kernels/forward/gemma4.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / kernels / forward / gemma4.py` 201 lines ยท 10066 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Gemma 4 forward pass via C function โ€” single call from Python, no layer loop overhead.""" 3 import numpy as np, ctypes 4 from forward.base import ArchitectureForwardPass 5 6 class ForwardGemma4(ArchitectureForwardPass): 7 """Gemma4 forward pass โ€” calls gemma4_forward_c for all 35 layers in one C call.""" 8 9 def __init__(self, engine): 10 super().__init__(engine) 11 e = engine; a = e.arch_name 12 13 def _get(name): 14 fields = e.reader.fields 15 for key, val in fields.items(): 16 if key == name: 17 parts = val.parts if hasattr(val, 'parts') else [] 18 if len(parts) >= 1: 19 data = parts[-1] 20 if hasattr(data, '__iter__') and len(data) == 1: return int(data[0]) 21 return data 22 return None 23 24 self.per_layer_dim = int(_get(f'{a}.embedding_length_per_layer_input') or 256) 25 self.sliding_window = int(_get(f'{a}.attention.sliding_window') or 512) 26 self.shared_kv = int(_get(f'{a}.attention.shared_kv_layers') or 20) 27 self.logit_cap = float(_get(f'{a}.final_logit_softcapping') or 30.0) 28 self.rope_freq_base_swa = float(_get(f'{a}.rope.freq_base_swa') or 10000.0) 29 self.rope_freq_base = float(_get(f'{a}.rope.freq_base') or `1000000`.0) 30 self.rope_dim_swa = int(_get(f'{a}.rope.dimension_count_swa') or 256) 31 self.rope_dim = int(_get(f'{a}.rope.dimension_count') or 512) 32 self._c_built = False 33 34 def _build_c(self): 35 """Build per-layer ctype arrays once.""" 36 if self._c_built: return 37 self._c_built = True 38 e = self.engine; L = e.n_layers 39 cf = ctypes.POINTER(ctypes.c_float); cu = ctypes.POINTER(ctypes.c_uint8); ci = ctypes.c_int 40 41 def fp(arr): 42 return arr.ctypes.data_as(cf) if arr is not None and hasattr(arr, 'ctypes') else cf() 43 def up(arr): 44 return arr.ctypes.data_as(cu) if arr is not None and hasattr(arr, 'ctypes') else cu() 45 46 # F32 norm/projection weight arrays 47 self._ca_attn = (cf*L)(*[fp(lw.attn_norm_w) for lw in e._layers]) 48 self._ca_ffn = (cf*L)(*[fp(lw.ffn_norm_w) for lw in e._layers]) 49 self._ca_pan = (cf*L)(*[fp(getattr(lw,'post_attn_norm_w',None)) for lw in e._layers]) 50 self._ca_pfw = (cf*L)(*[fp(getattr(lw,'post_ffw_norm_w',None)) for lw in e._layers]) 51 self._ca_pn = (cf*L)(*[fp(getattr(lw,'post_norm_w',None)) for lw in e._layers]) 52 self._ca_ls = (cf*L)(*[fp(getattr(lw,'layer_scale',None)) for lw in e._layers]) 53 self._ca_qn = (cf*L)(*[fp(getattr(lw,'q_norm_w',None)) for lw in e._layers]) 54 self._ca_kn = (cf*L)(*[fp(getattr(lw,'k_norm_w',None)) for lw in e._layers]) 55 self._ca_pr = (cf*L)(*[fp(getattr(lw,'per_layer_proj',None)) for lw in e._layers]) 56 self._ca_ig = (cf*L)(*[fp(getattr(lw,'per_layer_inp_gate',None)) for lw in e._layers]) 57 58 # Quantized weight pointer arrays 59 self._ca_wq = (cu*L)(*[up(getattr(lw,'attn_q_raw',None)) for lw in e._layers]) 60 self._ca_wk = (cu*L)(*[up(getattr(lw,'attn_k_raw',None)) for lw in e._layers]) 61 self._ca_wv = (cu*L)(*[up(getattr(lw,'attn_v_raw',None)) for lw in e._layers]) 62 self._ca_wo = (cu*L)(*[up(getattr(lw,'attn_out_raw',None)) for lw in e._layers]) 63 self._ca_wg = (cu*L)(*[up(getattr(lw,'ffn_gate_raw',None)) for lw in e._layers]) 64 self._ca_wu = (cu*L)(*[up(getattr(lw,'ffn_up_raw',None)) for lw in e._layers]) 65 self._ca_wd = (cu*L)(*[up(getattr(lw,'ffn_down_raw',None)) for lw in e._layers]) 66 67 def gv(lw, attr): 68 v = getattr(lw, attr, None) 69 if v is None: return 0 70 return v.value if hasattr(v,'value') else int(v) 71 72 # Dimension and quant type arrays 73 self._ca_nq = (ci*L)(*[gv(lw,'attn_q_nr') for lw in e._layers]) 74 self._ca_nk = (ci*L)(*[gv(lw,'attn_k_nr') for lw in e._layers]) 75 self._ca_nv = (ci*L)(*[gv(lw,'attn_v_nr') for lw in e._layers]) 76 self._ca_no = (ci*L)(*[gv(lw,'attn_out_nr') for lw in e._layers]) 77 self._ca_ng = (ci*L)(*[gv(lw,'ffn_gate_nr') for lw in e._layers]) 78 self._ca_nu = (ci*L)(*[gv(lw,'ffn_up_nr') for lw in e._layers]) 79 self._ca_nd = (ci*L)(*[gv(lw,'ffn_down_nr') for lw in e._layers]) 80 self._ca_qq = (ci*L)(*[gv(lw,'attn_q_qt') for lw in e._layers]) 81 self._ca_kq = (ci*L)(*[gv(lw,'attn_k_qt') for lw in e._layers]) 82 self._ca_vq = (ci*L)(*[gv(lw,'attn_v_qt') for lw in e._layers]) 83 self._ca_oq = (ci*L)(*[gv(lw,'attn_out_qt') for lw in e._layers]) 84 self._ca_gq = (ci*L)(*[gv(lw,'ffn_gate_qt') for lw in e._layers]) 85 self._ca_uq = (ci*L)(*[gv(lw,'ffn_up_qt') for lw in e._layers]) 86 self._ca_dq = (ci*L)(*[gv(lw,'ffn_down_qt') for lw in e._layers]) 87 88 # Per-layer metadata 89 hd = []; sw = []; kvi = []; rd = []; fb = [] 90 for lw in e._layers: 91 hd.append(getattr(lw,'gemma4_head_dim',e.head_dim)) 92 sw.append(1 if getattr(lw,'gemma4_is_swa',False) else 0) 93 kvi.append(getattr(lw,'gemma4_kv_idx',0)) 94 rd.append(getattr(lw,'gemma4_rope_dim',e.head_dim)) 95 fb.append(getattr(lw,'gemma4_freq_base',`1000000`.0)) 96 self._ca_hd = (ci*L)(*hd); self._ca_sw = (ci*L)(*sw) 97 self._ca_kv = (ci*L)(*kvi); self._ca_rd = (ci*L)(*rd) 98 self._ca_fb = (ctypes.c_float*L)(*fb) 99 100 def init_weights(self, *a): pass # handled by engine 101 def init_pointers(self, *a): pass 102 def init_buffers(self): pass 103 def reset_state(self): pass 104 105 def forward(self, token_id): 106 e = self.engine; self._build_c() 107 L=e.n_layers; N=e.n_embd; V=e.vocab_size; NH=e.n_head; NKH=e.n_kv_head 108 S = int(max(int(e.n_embd), int(e.n_head)*512, int(e.n_ff)//2, int(self.per_layer_dim), 8192)) 109 ws = np.zeros(14*S, dtype=np.float32) 110 if isinstance(token_id, (list, np.ndarray)): 111 tid = np.array([[int(token_id[0])]], dtype=np.int32) 112 else: 113 tid = np.array([[int(token_id)]], dtype=np.int32) 114 ci = ctypes.c_int; cf = ctypes.POINTER(ctypes.c_float); cu = ctypes.POINTER(ctypes.c_uint8) 115 cpi = ctypes.POINTER(ci); cpf = ctypes.POINTER(cf); cpu = ctypes.POINTER(cu) 116 ce = e._cengine 117 fn = ce.gemma4_forward_c 118 119 # Set argtypes once 120 if not hasattr(fn, '_at_set'): 121 # Build argtypes carefully matching C function signature 122 at = [] 123 # tokens, B 124 at += [cpi, ci] 125 # L, N, NH, NKH, V, PL, SW, FF_half (8 ints) 126 at += [ci]*8 127 # eps, logit_cap (2 floats) 128 at += [ctypes.c_float]*2 129 # emb 130 at += [cf] 131 # w_out, qt_out, nr_out, nc_out 132 at += [cu, ci, ci, ci] 133 # out_norm_w 134 at += [cf] 135 # 10 F32 pointer arrays (norm, proj, etc.) 136 at += [cpf]*10 137 # 7 uint8 pointer arrays + 7 nr int arrays + 7 qt int arrays (interleaved per weight) 138 # wq, q_nr, q_qt, wk, k_nr, k_qt, wv, v_nr, v_qt, wo, o_nr, o_qt, 139 # wg, g_nr, g_qt, wu, u_nr, u_qt, wd, d_nr, d_qt 140 at += [cpu, cpi, cpi] * 7 141 # head_dims, is_swa, kv_idx, rope_dim (4 int arrays) 142 at += [cpi]*4 143 # freq_base (float array) โ€” single float*, not float** 144 at += [cf] 145 # kv_k, kv_v, kv_lens, max_ctx 146 at += [cf, cf, cpi, ci] 147 # cos_rope, sin_rope 148 at += [cf, cf] 149 # logits, ws 150 at += [cf, cf] 151 fn.argtypes = at 152 fn.restype = None 153 fn._at_set = True 154 # RoPE table 155 mpos = int(max(8192, int(self.sliding_window)*2)) 156 cos_t = np.zeros(mpos*512, dtype=np.float32) 157 sin_t = np.zeros(mpos*512, dtype=np.float32) 158 rope_base = float(self.rope_freq_base) 159 for p in range(mpos): 160 for j in range(min(256, int(e.head_dim))): 161 hp = j 162 t = float(p) / (rope_base ** (2.0*hp/512.0)) 163 cos_t[p*512+hp] = np.cos(t); sin_t[p*512+hp] = np.sin(t) 164 165 # Handle both quantized (C path) and F32 output weights 166 if hasattr(e, '_out_raw') and e._out_raw is not None: 167 out_w_arg = e._out_raw # uint8_t* for quantized weights 168 elif hasattr(e, '_out_f32'): 169 # Cast F32 float* to uint8_t* for C function compatibility 170 out_w_arg = e._out_f32.ctypes.data_as(cu) 171 else: 172 out_w_arg = cu() 173 out_qt_arg = e._out_qt if hasattr(e, '_out_qt') else ci(0) 174 out_nr_arg = e._out_nr if hasattr(e, '_out_nr') else ci(N) 175 out_nc_arg = e._out_nc if hasattr(e, '_out_nc') else ci(V) 176 177 fn(tid.ctypes.data_as(ctypes.POINTER(ci)), ci(1), 178 ci(L), ci(N), ci(NH), ci(NKH), ci(V), ci(self.per_layer_dim), 179 ci(self.sliding_window), ci(e.n_ff//2), 180 e._eps_f, ctypes.c_float(self.logit_cap), 181 e.emb.ctypes.data_as(cf), 182 out_w_arg, out_qt_arg, out_nr_arg, out_nc_arg, 183 e._out_norm_w.ctypes.data_as(cf), 184 self._ca_attn, self._ca_ffn, self._ca_pan, self._ca_pfw, 185 self._ca_pn, self._ca_ls, self._ca_qn, self._ca_kn, 186 self._ca_pr, self._ca_ig, 187 self._ca_wq, self._ca_nq, self._ca_qq, 188 self._ca_wk, self._ca_nk, self._ca_kq, 189 self._ca_wv, self._ca_nv, self._ca_vq, 190 self._ca_wo, self._ca_no, self._ca_oq, 191 self._ca_wg, self._ca_ng, self._ca_gq, 192 self._ca_wu, self._ca_nu, self._ca_uq, 193 self._ca_wd, self._ca_nd, self._ca_dq, 194 self._ca_hd, self._ca_sw, self._ca_kv, 195 self._ca_rd, self._ca_fb, 196 e.kv_k.ctypes.data_as(cf), e.kv_v.ctypes.data_as(cf), 197 e.kv_len.ctypes.data_as(ctypes.POINTER(ci)), ci(e.kv_k.shape[1]), 198 cos_t.ctypes.data_as(cf), sin_t.ctypes.data_as(cf), 199 e._p_logits, ws.ctypes.data_as(cf)) 200 e.pos += 1 201 return e._logits