MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / profile_qwen36.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Profile Qwen3.6 MXFP4 by instrumenting the actual forward pass.""" |
| 3 | import sys, os, time, numpy as np |
| 4 | |
| 5 | sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') |
| 6 | MODEL = "/tmp/models/qwen3.6-mxfp4.gguf" |
| 7 | |
| 8 | # Monkey-patch timing into actual engine |
| 9 | import turbo_engine_v7_moe as te_mod |
| 10 | orig_forward = te_mod.TurboEngineV7MoE.forward |
| 11 | orig_fwd_moe = te_mod.TurboEngineV7MoE._forward_moe |
| 12 | orig_apply_rope = te_mod.TurboEngineV7MoE._apply_rope_fast |
| 13 | |
| 14 | def timed_forward(self, token_id): |
| 15 | """Instrumented forward with per-layer timing.""" |
| 16 | import time as _t |
| 17 | N = self.n_embd; NH = self.n_head; NKH = self.n_kv_head * self.head_dim |
| 18 | HD = self.head_dim; L = self.n_layers |
| 19 | |
| 20 | # Counters |
| 21 | self._timing = getattr(self, '_timing', { |
| 22 | 'ssm_decode': 0.0, 'ssm_gate': 0.0, 'ssm_gate_mul': 0.0, 'ssm_out': 0.0, |
| 23 | 'attn_qkv': 0.0, 'attn_split': 0.0, 'rope': 0.0, 'kv_cache': 0.0, 'gqa': 0.0, |
| 24 | 'attn_proj': 0.0, 'ffn_rms': 0.0, 'ffn_moe': 0.0, 'ffn_shexp': 0.0, |
| 25 | 'rms1': 0.0, 'rms2': 0.0, 'residual': 0.0, 'final': 0.0, |
| 26 | 'count': 0, 'attn_layers': 0, 'ssm_layers': 0 |
| 27 | }) |
| 28 | tim = self._timing |
| 29 | |
| 30 | import ctypes |
| 31 | b_x = self._x; b_r = self._residual |
| 32 | N = self.n_embd; NH = self.n_head; NKH = self.n_kv_head * self.head_dim |
| 33 | HD = self.head_dim; L = self.n_layers |
| 34 | kern = self._kern; simd = self._simd |
| 35 | cf = ctypes.POINTER(ctypes.c_float); ci = ctypes.c_int |
| 36 | |
| 37 | tim['count'] += 1 |
| 38 | t_all = _t.perf_counter() |
| 39 | |
| 40 | # Embedding |
| 41 | np.copyto(b_x, self.emb[token_id]) |
| 42 | |
| 43 | for i in range(L): |
| 44 | lw = self._layers[i] |
| 45 | is_ssm = (self.layer_types is not None and self.layer_types[i] == 1) |
| 46 | |
| 47 | # Residual copy |
| 48 | t0 = _t.perf_counter() |
| 49 | np.copyto(b_r, b_x) |
| 50 | tim['residual'] += _t.perf_counter() - t0 |
| 51 | |
| 52 | # RMS norm 1 |
| 53 | t0 = _t.perf_counter() |
| 54 | simd.rms_norm(self._p_x_norm, self._p_x, |
| 55 | lw.attn_norm_w.ctypes.data_as(cf), N, self._eps_f) |
| 56 | tim['rms1'] += _t.perf_counter() - t0 |
| 57 | |
| 58 | if is_ssm and self._cengine is not None and lw.ssm_conv1d_ptr is not None: |
| 59 | # ═══ SSM path ═══ |
| 60 | tim['ssm_layers'] += 1 |
| 61 | ce = self._cengine |
| 62 | t0 = _t.perf_counter() |
| 63 | ce.ssm_decode_step( |
| 64 | self._p_x_norm, self._ssm_intermediate.ctypes.data_as(cf), |
| 65 | lw.ssm_conv1d_ptr, lw.ssm_a_ptr, lw.ssm_dt_bias_ptr, |
| 66 | lw.ssm_alpha_ptr, lw.ssm_beta_ptr, lw.ssm_norm_ptr, |
| 67 | self._ssm_state[i].ctypes.data_as(cf), |
| 68 | ci(1), ci(N), ci(self.ssm_inner), |
| 69 | ci(self.ssm_groups), ci(self.ssm_state_size), |
| 70 | ci(self.ssm_conv_kernel), ci(self.ssm_dt_rank)) |
| 71 | tim['ssm_decode'] += _t.perf_counter() - t0 |
| 72 | |
| 73 | t0 = _t.perf_counter() |
| 74 | kern.quant_matmul_omp(lw.attn_gate_raw, self._p_x_norm, |
| 75 | self._gate_4096.ctypes.data_as(cf), |
| 76 | lw.attn_gate_nr, lw.attn_gate_nc, lw.attn_gate_qt) |
| 77 | tim['ssm_gate'] += _t.perf_counter() - t0 |
| 78 | |
| 79 | t0 = _t.perf_counter() |
| 80 | np.multiply(self._gate_4096, self._ssm_intermediate, out=self._gate_4096) |
| 81 | tim['ssm_gate_mul'] += _t.perf_counter() - t0 |
| 82 | |
| 83 | t0 = _t.perf_counter() |
| 84 | kern.quant_matmul_omp(lw.ssm_out_raw, |
| 85 | self._gate_4096.ctypes.data_as(cf), self._p_o_proj, |
| 86 | lw.ssm_out_nr, lw.ssm_out_nc, lw.ssm_out_qt) |
| 87 | tim['ssm_out'] += _t.perf_counter() - t0 |
| 88 | |
| 89 | t0 = _t.perf_counter() |
| 90 | self._x[:N] = self._residual[:N] + self._o_proj[:N] |
| 91 | tim['residual'] += _t.perf_counter() - t0 |
| 92 | |
| 93 | else: |
| 94 | # ═══ Attention path ═══ |
| 95 | tim['attn_layers'] += 1 |
| 96 | t0 = _t.perf_counter() |
| 97 | qkv_buf = self._qk |
| 98 | if len(self._qk) < 8192: |
| 99 | self._qk = np.zeros(8192, dtype=np.float32) |
| 100 | self._p_qk = self._qk.ctypes.data_as(cf) |
| 101 | p_qkv = self._p_qk |
| 102 | kern.quant_matmul_omp(lw.attn_qkv_raw, self._p_x_norm, p_qkv, |
| 103 | lw.attn_qkv_nr, lw.attn_qkv_nc, lw.attn_qkv_qt) |
| 104 | tim['attn_qkv'] += _t.perf_counter() - t0 |
| 105 | |
| 106 | t0 = _t.perf_counter() |
| 107 | nq = NH * HD; nk = NKH |
| 108 | self._q[:] = self._qk[:nq] |
| 109 | self._k[:nk] = self._qk[nq:nq+nk] |
| 110 | self._v[:nk] = self._qk[nq+N:nq+N+nk] |
| 111 | tim['attn_split'] += _t.perf_counter() - t0 |
| 112 | |
| 113 | t0 = _t.perf_counter() |
| 114 | rope_d = self.rope_dim if hasattr(self, 'rope_dim') and self.rope_dim > 0 else HD |
| 115 | self._q[:] = self._apply_rope_fast(self._q, self.pos, NH, rope_dim=rope_d) |
| 116 | self._k[:] = self._apply_rope_fast(self._k, self.pos, self.n_kv_head, rope_dim=rope_d) |
| 117 | tim['rope'] += _t.perf_counter() - t0 |
| 118 | |
| 119 | t0 = _t.perf_counter() |
| 120 | self.kv_k[i, self.kv_len[i], :NKH] = self._k[:NKH] |
| 121 | self.kv_v[i, self.kv_len[i], :NKH] = self._v[:NKH] |
| 122 | tim['kv_cache'] += _t.perf_counter() - t0 |
| 123 | |
| 124 | t0 = _t.perf_counter() |
| 125 | seq_len = self.kv_len[i] + 1 |
| 126 | if self._gqa_attn is not None and seq_len <= 4096: |
| 127 | self._gqa_attn.gqa_attention_decode( |
| 128 | self._q.ctypes.data_as(cf), |
| 129 | self.kv_k[i].ctypes.data_as(cf), |
| 130 | self.kv_v[i].ctypes.data_as(cf), |
| 131 | self._att_out.ctypes.data_as(cf), |
| 132 | ci(seq_len), ci(NH), ci(self.n_kv_head), ci(HD)) |
| 133 | self.kv_len[i] += 1 |
| 134 | tim['gqa'] += _t.perf_counter() - t0 |
| 135 | |
| 136 | t0 = _t.perf_counter() |
| 137 | kern.quant_matmul_omp(lw.attn_gate_raw, self._p_att_out, self._p_o_proj, |
| 138 | lw.attn_gate_nr, lw.attn_gate_nc, lw.attn_gate_qt) |
| 139 | self._x[:N] = self._residual[:N] + self._o_proj[:N] |
| 140 | tim['attn_proj'] += _t.perf_counter() - t0 |
| 141 | |
| 142 | # ── FFN ── |
| 143 | t0 = _t.perf_counter() |
| 144 | np.copyto(self._residual, self._x) |
| 145 | simd.rms_norm(self._p_x_norm, self._p_x, |
| 146 | lw.ffn_norm_w.ctypes.data_as(cf), N, self._eps_f) |
| 147 | tim['ffn_rms'] += _t.perf_counter() - t0 |
| 148 | |
| 149 | t0 = _t.perf_counter() |
| 150 | self._forward_moe(i, self._p_x_norm, self._ffn_out, self._residual, N) |
| 151 | tim['ffn_moe'] += _t.perf_counter() - t0 |
| 152 | |
| 153 | # Shared expert |
| 154 | if hasattr(lw, 'shexp_router_ptr') and lw.shexp_router_ptr is not None: |
| 155 | t0 = _t.perf_counter() |
| 156 | shexp_score = float(np.dot(self._x_norm, |
| 157 | np.ctypeslib.as_array(lw.shexp_router_ptr, shape=(N,)))) |
| 158 | if shexp_score > 0: |
| 159 | shexp_int = lw.shexp_gate_nr.value |
| 160 | kern.quant_matmul_omp(lw.shexp_gate_raw, self._p_x_norm, self._p_gate, |
| 161 | lw.shexp_gate_nr, lw.shexp_gate_nc, lw.shexp_gate_qt) |
| 162 | kern.quant_matmul_omp(lw.shexp_up_raw, self._p_x_norm, self._p_up, |
| 163 | lw.shexp_up_nr, lw.shexp_up_nc, lw.shexp_up_qt) |
| 164 | simd.silu(self._p_silu_gate, self._p_gate, ci(shexp_int)) |
| 165 | self._silu_gate[:shexp_int] *= self._up[:shexp_int] |
| 166 | kern.quant_matmul_omp(lw.shexp_down_raw, self._p_silu_gate, self._p_ffn_out, |
| 167 | lw.shexp_down_nr, lw.shexp_down_nc, lw.shexp_down_qt) |
| 168 | self._x[:N] += shexp_score * self._ffn_out[:N] |
| 169 | tim['ffn_shexp'] += _t.perf_counter() - t0 |
| 170 | |
| 171 | # Final norm + output |
| 172 | t0 = _t.perf_counter() |
| 173 | simd.rms_norm(self._p_x_norm, self._p_x, |
| 174 | self._out_norm_w.ctypes.data_as(cf), N, self._eps_f) |
| 175 | kern.quant_matmul_omp(self._out_raw, self._p_x_norm, self._p_logits, |
| 176 | self._out_nr, self._out_nc, self._out_qt) |
| 177 | self.pos += 1 |
| 178 | tim['final'] += _t.perf_counter() - t0 |
| 179 | |
| 180 | return self._logits |
| 181 | |
| 182 | te_mod.TurboEngineV7MoE.forward = timed_forward |
| 183 | |
| 184 | print(f"Loading Qwen3.6 MXFP4...", flush=True) |
| 185 | e = te_mod.TurboEngineV7MoE(MODEL, 32) |
| 186 | N=e.n_embd; L=e.n_layers; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim |
| 187 | |
| 188 | print("\nWarmup...", flush=True) |
| 189 | for _ in range(5): |
| 190 | e.forward(np.array([1], dtype=np.int32)) |
| 191 | e._timing = {k: 0.0 for k in e._timing} |
| 192 | |
| 193 | # Benchmark 30 tokens |
| 194 | print("Benchmarking 30 tokens...", flush=True) |
| 195 | for tok in range(30): |
| 196 | e.forward(np.array([tok], dtype=np.int32)) |
| 197 | |
| 198 | tim = e._timing |
| 199 | n = tim['count'] |
| 200 | total = sum(v for k,v in tim.items() if k not in ('count','attn_layers','ssm_layers')) |
| 201 | |
| 202 | print(f"\n{'='*60}") |
| 203 | print(f" Qwen3.6 MXFP4 — Per-Component Breakdown (30 tokens, {n} samples)") |
| 204 | print(f"{'='*60}") |
| 205 | print(f" {'Component':25s} {'ms/tok':>10s} {'%':>6s}") |
| 206 | print(f" {'-'*43}") |
| 207 | |
| 208 | components = [ |
| 209 | ('RMS Norm (pre)', 'rms1'), |
| 210 | ('Residual copy', 'residual'), |
| 211 | ('SSM decode (C)', 'ssm_decode'), |
| 212 | ('SSM attn_gate matmul', 'ssm_gate'), |
| 213 | ('SSM gate multiply', 'ssm_gate_mul'), |
| 214 | ('SSM out matmul', 'ssm_out'), |
| 215 | ('Attention QKV matmul', 'attn_qkv'), |
| 216 | ('Attention QKV split', 'attn_split'), |
| 217 | ('RoPE', 'rope'), |
| 218 | ('KV cache store', 'kv_cache'), |
| 219 | ('GQA attention', 'gqa'), |
| 220 | ('Attn output proj', 'attn_proj'), |
| 221 | ('FFN RMS+residual', 'ffn_rms'), |
| 222 | ('MoE FFN (fused)', 'ffn_moe'), |
| 223 | ('Shared expert', 'ffn_shexp'), |
| 224 | ('Final norm+output', 'final'), |
| 225 | ] |
| 226 | |
| 227 | for name, key in components: |
| 228 | if key in tim: |
| 229 | ms = tim[key] / n * 1000 |
| 230 | print(f" {name:25s} {ms:10.1f} {ms/total*100:5.0f}%") |
| 231 | |
| 232 | print(f" {'-'*43}") |
| 233 | print(f" {'TOTAL':25s} {total/n*1000:10.1f} {'100':5s}%") |
| 234 | print(f" {'Throughput':25s} {n/(total):10.1f} tok/s") |
| 235 | print(f"\n {tim['attn_layers']/n:.1f} attn layers/tok, {tim['ssm_layers']/n:.1f} SSM layers/tok") |