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/benchmarks/profile_hotpath.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 / benchmarks / profile_hotpath.py` 462 lines · 17454 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """ 3 Hot-path profiler for MojoLlama MoE engine. 4 5 Instruments the TurboEngineV7MoE.forward() method with perf_counter() 6 timing around each component within the per-layer loop. Reports per-token 7 and per-layer breakdown. 8 """ 9 import sys, os, time, ctypes 10 import numpy as np 11 12 sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels')) 13 from turbo_engine_v7_moe import TurboEngineV7MoE 14 15 MODEL = '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf' 16 17 # ---------- Timing accumulator ---------- 18 TIMERS = {} # component_name -> list of elapsed seconds per call 19 20 def tic(comp): 21 """Start a timer for a component. Returns a callback that accumulates.""" 22 t0 = time.perf_counter() 23 def stop(): 24 dt = time.perf_counter() - t0 25 TIMERS.setdefault(comp, []).append(dt) 26 return stop 27 28 29 class ProfiledTurboEngineV7MoE(TurboEngineV7MoE): 30 """Subclass that adds Python-level perf_counter() timing around each component.""" 31 32 def forward(self, token_id): 33 b_x = self._x 34 b_r = self._residual 35 b_qn = self._x_norm 36 b_q = self._q 37 b_k = self._k 38 b_v = self._v 39 b_att = self._att_out 40 b_gate = self._gate 41 b_up = self._up 42 b_silu = self._silu_gate 43 b_ffn = self._ffn_out 44 b_oproj = self._o_proj 45 N = self.n_embd 46 NH = self.n_head 47 NKH = self.n_kv_head * self.head_dim 48 HD = self.head_dim 49 FF = self.n_ff 50 L = self.n_layers 51 kern = self._kern 52 simd = self._simd 53 eps_f = self._eps_f 54 p_x = self._p_x 55 p_xn = self._p_x_norm 56 p_r = self._p_residual 57 p_q = self._p_q 58 p_k = self._p_k 59 p_v = self._p_v 60 p_att = self._p_att_out 61 p_gate = self._p_gate 62 p_up = self._p_up 63 p_silu = self._p_silu_gate 64 p_oproj = self._p_o_proj 65 p_ffn = self._p_ffn 66 p_logits = self._p_logits 67 68 # --- Embedding lookup --- 69 tok = tic('emb_lookup') 70 np.copyto(b_x, self.emb[token_id]) 71 tok() 72 73 for i in range(L): 74 lw = self._layers[i] 75 76 # Residual copy 77 np.copyto(b_r, b_x) 78 79 # --- RMS norm 1 (pre-attention) --- 80 t_rms1 = tic('rms_norm_pre_attn') 81 simd.rms_norm( 82 p_xn, p_x, 83 lw.attn_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 84 N, eps_f, 85 ) 86 t_rms1() 87 88 # --- QKV matmuls --- 89 t_qkv = tic('attn_qkv') 90 if lw.attn_q_use_c and lw.attn_k_use_c and lw.attn_v_use_c: 91 kern.batch_qkv_omp( 92 lw.attn_q_raw, lw.attn_k_raw, lw.attn_v_raw, 93 p_xn, p_q, p_k, p_v, 94 lw.attn_q_nr, lw.attn_k_nr, lw.attn_v_nr, 95 lw.attn_q_nc, 96 lw.attn_q_qt, lw.attn_k_qt, lw.attn_v_qt, 97 ) 98 else: 99 if lw.attn_q_use_c: 100 kern.quant_matmul_omp( 101 lw.attn_q_raw, p_xn, p_q, 102 lw.attn_q_nr, lw.attn_q_nc, lw.attn_q_qt, 103 ) 104 if lw.attn_k_use_c: 105 kern.quant_matmul_omp( 106 lw.attn_k_raw, p_xn, p_k, 107 lw.attn_k_nr, lw.attn_k_nc, lw.attn_k_qt, 108 ) 109 if lw.attn_v_use_c: 110 kern.quant_matmul_omp( 111 lw.attn_v_raw, p_xn, p_v, 112 lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt, 113 ) 114 t_qkv() 115 116 # --- Q/K norm --- 117 t_qk_norm = tic('attn_qk_norm') 118 if lw.has_q_norm: 119 q_2d = b_q.reshape(NH, HD) 120 q_rms = np.sqrt(np.mean(q_2d * q_2d, axis=1, keepdims=True) + self.eps) 121 q_2d[:] = q_2d / q_rms * lw.q_norm_w.reshape(1, HD) 122 if lw.has_k_norm: 123 k_2d = b_k[:NKH].reshape(self.n_kv_head, HD) 124 k_rms = np.sqrt(np.mean(k_2d * k_2d, axis=1, keepdims=True) + self.eps) 125 k_2d[:] = k_2d / k_rms * lw.k_norm_w.reshape(1, HD) 126 t_qk_norm() 127 128 # --- RoPE --- 129 t_rope = tic('rope') 130 b_q[:] = self._apply_rope_fast(b_q, self.pos, NH) 131 b_k[:] = self._apply_rope_fast(b_k, self.pos, self.n_kv_head) 132 t_rope() 133 134 # --- KV cache store --- 135 t_kv_store = tic('kv_cache_store') 136 self.kv_k[i, self.kv_len[i], :NKH] = b_k[:NKH] 137 self.kv_v[i, self.kv_len[i], :NKH] = b_v[:NKH] 138 t_kv_store() 139 140 # --- Attention (GQA) --- 141 t_attn = tic('attention') 142 seq_len = self.kv_len[i] + 1 143 if self._gqa_attn is not None and seq_len <= 4096: 144 self._gqa_attn.gqa_attention_decode( 145 b_q.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 146 self.kv_k[i].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 147 self.kv_v[i].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 148 b_att.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 149 ctypes.c_int(seq_len), 150 ctypes.c_int(NH), 151 ctypes.c_int(self.n_kv_head), 152 ctypes.c_int(HD), 153 ) 154 else: 155 k_cache = self.kv_k[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) 156 v_cache = self.kv_v[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) 157 q_2d = b_q.reshape(NH, HD) 158 nk = self.n_kv_head 159 gqa = self._gqa_rep 160 q_g = q_2d.reshape(nk, gqa, HD) 161 k_T = k_cache.transpose(1, 0, 2) 162 scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD)) 163 scores = scores.reshape(NH, seq_len) 164 scores -= np.max(scores, axis=1, keepdims=True) 165 np.exp(scores, out=scores) 166 scores /= np.sum(scores, axis=1, keepdims=True) 167 v_T = v_cache.transpose(1, 0, 2) 168 att = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, seq_len), v_T) 169 b_att[:] = att.reshape(-1) 170 self.kv_len[i] += 1 171 t_attn() 172 173 # --- O projection --- 174 t_o = tic('attn_out_proj') 175 if lw.attn_out_use_c: 176 kern.quant_matmul_omp( 177 lw.attn_out_raw, p_att, p_oproj, 178 lw.attn_out_nr, lw.attn_out_nc, lw.attn_out_qt, 179 ) 180 b_x[:N] = b_r[:N] + b_oproj[:N] 181 else: 182 b_x[:N] = b_r[:N] + (lw.attn_out_f32 @ b_att)[:N] 183 t_o() 184 185 # --- FFN --- 186 np.copyto(b_r, b_x) 187 188 # --- RMS norm 2 (pre-FFN) --- 189 t_rms2 = tic('rms_norm_pre_ffn') 190 simd.rms_norm( 191 p_xn, p_x, 192 lw.ffn_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 193 N, eps_f, 194 ) 195 t_rms2() 196 197 # --- MoE FFN --- 198 if self.is_moe and self._moe_layers: 199 self._forward_moe_profiled(i, p_xn, b_ffn, b_r, N) 200 else: 201 # Dense FFN (not used for MoE models, but keep for completeness) 202 t_dense = tic('ffn_dense') 203 if lw.ffn_gate_use_c and lw.ffn_up_use_c: 204 kern.batch_gate_up_omp( 205 lw.ffn_gate_raw, lw.ffn_up_raw, p_xn, p_gate, p_up, 206 lw.ffn_gate_nr, lw.ffn_up_nr, 207 lw.ffn_gate_nc, lw.ffn_gate_qt, lw.ffn_up_qt, 208 ) 209 else: 210 if lw.ffn_gate_use_c: 211 kern.quant_matmul_omp( 212 lw.ffn_gate_raw, p_xn, p_gate, 213 lw.ffn_gate_nr, lw.ffn_gate_nc, lw.ffn_gate_qt, 214 ) 215 if lw.ffn_up_use_c: 216 kern.quant_matmul_omp( 217 lw.ffn_up_raw, p_xn, p_up, 218 lw.ffn_up_nr, lw.ffn_up_nc, lw.ffn_up_qt, 219 ) 220 simd.silu(p_silu, p_gate, ctypes.c_int(FF)) 221 b_silu[:FF] *= b_up[:FF] 222 if lw.ffn_down_use_c: 223 kern.quant_matmul_omp( 224 lw.ffn_down_raw, p_silu, p_ffn, 225 lw.ffn_down_nr, lw.ffn_down_nc, lw.ffn_down_qt, 226 ) 227 b_x[:N] = b_r[:N] + b_ffn[:N] 228 else: 229 b_x[:N] = b_r[:N] + (lw.ffn_down_f32 @ b_silu[:lw.ffn_down_nc.value])[:N] 230 t_dense() 231 232 # --- Final norm --- 233 t_fn = tic('final_norm') 234 simd.rms_norm( 235 p_xn, p_x, 236 self._out_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 237 N, eps_f, 238 ) 239 t_fn() 240 241 # --- Output projection --- 242 t_out = tic('output_proj') 243 if self._out_use_c: 244 kern.quant_matmul_omp( 245 self._out_raw, p_xn, p_logits, 246 self._out_nr, self._out_nc, self._out_qt, 247 ) 248 else: 249 self._logits[:] = self._out_f32 @ b_qn 250 t_out() 251 252 self.pos += 1 253 return self._logits 254 255 def _forward_moe_profiled(self, layer, p_xn, b_ffn_out, b_residual, N): 256 """Profiled MoE FFN dispatch with separate router/softmax/expert timing.""" 257 me = self._moe_layers[layer] 258 n_exp = me.n_experts 259 top_k = self.n_experts_per_tok 260 FF = me.n_ff_expert 261 kern = self._kern 262 263 # --- Router --- 264 t_router = tic('moe_router') 265 if me.router_raw is not None: 266 kern.quant_matmul_omp( 267 me.router_raw, p_xn, self._p_moe_router, 268 me.router_nr, me.router_nc, me.router_qt, 269 ) 270 else: 271 np.copyto( 272 self._moe_router_scores[:n_exp], 273 (me.router_f32 @ self._x_norm)[:n_exp], 274 ) 275 t_router() 276 277 # --- Softmax + Top-K --- 278 t_topk = tic('moe_softmax_topk') 279 scores = self._moe_router_scores[:n_exp] 280 scores -= np.max(scores) 281 np.exp(scores, out=scores) 282 scores /= np.sum(scores) 283 top_indices = np.argpartition(scores, -top_k)[-top_k:] 284 top_weights = scores[top_indices] 285 top_weights /= np.sum(top_weights) 286 t_topk() 287 288 # --- Fused MoE dispatch (gate/up/down matmuls + silu + combine) --- 289 t_moe = tic('moe_fused_experts') 290 gate_ptrs = me.gate_ptrs_arr 291 up_ptrs = me.up_ptrs_arr 292 down_ptrs = me.down_ptrs_arr 293 294 top_idx_arr = np.ascontiguousarray(top_indices.astype(np.int32)) 295 top_wt_arr = np.ascontiguousarray(top_weights.astype(np.float32)) 296 297 self._moe_combined[:] = 0.0 298 kern.moe_forward_omp( 299 gate_ptrs, up_ptrs, down_ptrs, 300 p_xn, 301 ctypes.c_int(FF), ctypes.c_int(N), 302 me.gate_qt, me.up_qt, me.down_qt, 303 top_idx_arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), 304 top_wt_arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 305 ctypes.c_int(top_k), 306 self._p_moe_combined, 307 self._moe_prealloc_buf.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 308 self._moe_prealloc_q8.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), 309 ) 310 311 b_ffn_out[:N] = self._moe_combined[:N] 312 t_moe() 313 314 315 def main(): 316 print("Loading model...", flush=True) 317 t0 = time.perf_counter() 318 e = ProfiledTurboEngineV7MoE(MODEL, 32) 319 print(f"Load time: {time.perf_counter()-t0:.1f}s", flush=True) 320 321 L = e.n_layers 322 N = e.n_embd 323 NH = e.n_head 324 NKH = e.n_kv_head 325 HD = e.head_dim 326 NE = e.n_experts 327 NK = e.n_experts_per_tok 328 moe_int = e.n_ff_expert if hasattr(e, 'n_ff_expert') else e.n_ff 329 print(f"Model: {L}L/{N}D/{NH}H/{NKH}KV | MoE {NE}x{NK} | int={moe_int} | V={e.vocab_size}", flush=True) 330 331 # Warmup: 5 tokens 332 print("\nWarmup (5 tokens)...", flush=True) 333 e.reset() 334 logits = e.forward(1) # BOS token 335 tok = int(np.argmax(np.nan_to_num(logits, nan=-1e10))) 336 for _ in range(4): 337 logits = e.forward(tok) 338 tok = int(np.argmax(np.nan_to_num(logits, nan=-1e10))) 339 340 # Clear accumulators 341 TIMERS.clear() 342 e.reset() 343 344 # Profiled run: 20 tokens 345 N_TOKENS = 20 346 print(f"Profiling {N_TOKENS} tokens...", flush=True) 347 logits = e.forward(1) # BOS 348 tok = int(np.argmax(np.nan_to_num(logits, nan=-1e10))) 349 for i in range(N_TOKENS - 1): 350 logits = e.forward(tok) 351 tok = int(np.argmax(np.nan_to_num(logits, nan=-1e10))) 352 353 # Aggregate 354 n_layers = L 355 total_calls_per_token = {} 356 total_ms_per_token = {} 357 grand_total_ms = 0.0 358 for comp, times in TIMERS.items(): 359 total_s = sum(times) 360 total_ms = total_s * 1000.0 361 grand_total_ms += total_ms 362 total_calls_per_token[comp] = len(times) 363 total_ms_per_token[comp] = total_ms / N_TOKENS 364 365 grand_total_per_token = grand_total_ms / N_TOKENS 366 367 # Group into categories for the final report 368 cat_map = { 369 'emb_lookup': 'Emb lookup', 370 'rms_norm_pre_attn': 'RMS norms', 371 'rms_norm_pre_ffn': 'RMS norms', 372 'final_norm': 'RMS norms', 373 'attn_qkv': 'Attention QKV', 374 'attn_qk_norm': 'Attention QKV', 375 'rope': 'Attention QKV', 376 'kv_cache_store': 'Attention QKV', 377 'attention': 'Attention QKV', 378 'attn_out_proj': 'Attention QKV', 379 'moe_router': 'Router', 380 'moe_softmax_topk': 'Router', 381 'moe_fused_experts':'MoE FFN gate/up/down', 382 'output_proj': 'Output proj', 383 } 384 cat_times = {} 385 for comp, t in total_ms_per_token.items(): 386 cat = cat_map.get(comp, 'Other') 387 cat_times[cat] = cat_times.get(cat, 0.0) + t 388 389 # Print detailed per-component 390 print(f"\n{'='*72}") 391 print(f" HOT-PATH PROFILE: {N_TOKENS} tokens x {n_layers} layers = {N_TOKENS*n_layers} layer-tokens") 392 print(f"{'='*72}") 393 print(f" {'COMPONENT':30s} {'ms/tok':>10s} {'%':>8s} {'calls/tok':>10s}") 394 print(f" {'─'*60}") 395 for comp in sorted(total_ms_per_token.keys(), key=lambda c: total_ms_per_token[c], reverse=True): 396 ms = total_ms_per_token[comp] 397 pct = ms / grand_total_per_token * 100 if grand_total_per_token > 0 else 0 398 ct = total_calls_per_token[comp] / N_TOKENS 399 label = comp.replace('_', ' ').title() 400 print(f" {comp:30s} {ms:9.2f}ms {pct:7.1f}% {ct:9.1f}") 401 print(f" {'─'*60}") 402 print(f" {'TOTAL':30s} {grand_total_per_token:9.2f}ms {'100.0%':>8s}") 403 404 # Print category breakdown 405 print(f"\n {'─'*60}") 406 print(f" {'CATEGORY':30s} {'ms/tok':>10s} {'%':>8s}") 407 print(f" {'─'*60}") 408 cat_order = ['Attention QKV', 'MoE FFN gate/up/down', 'Router', 'Output proj', 'RMS norms', 'Emb lookup', 'Other'] 409 for cat in cat_order: 410 if cat in cat_times: 411 ms = cat_times[cat] 412 pct = ms / grand_total_per_token * 100 413 print(f" {cat:30s} {ms:9.2f}ms {pct:7.1f}%") 414 print(f" {'─'*60}") 415 print(f" {'TOTAL':30s} {grand_total_per_token:9.2f}ms {1000.0/grand_total_per_token:7.1f} tok/s") 416 print(f"{'='*72}") 417 418 # Per-layer detail (top components) 419 print(f"\nPer-layer detail (ms/layer, avg over {N_TOKENS} tokens):") 420 comps_by_layer = {} 421 for comp, times in TIMERS.items(): 422 # Group into batches of n_layers * N_TOKENS 423 calls_per_token_per_layer = len(times) // (n_layers * N_TOKENS) 424 if calls_per_token_per_layer == 0: 425 continue 426 layers_per_token_tuples = [] 427 idx = 0 428 for _ in range(N_TOKENS): 429 for layer_i in range(n_layers): 430 for _ in range(calls_per_token_per_layer): 431 layers_per_token_tuples.append((layer_i, times[idx])) 432 idx += 1 433 # Average per layer across tokens 434 layer_sums = {} 435 layer_counts = {} 436 for layer_i, dt in layers_per_token_tuples: 437 layer_sums[layer_i] = layer_sums.get(layer_i, 0.0) + dt 438 layer_counts[layer_i] = layer_counts.get(layer_i, 0) + 1 439 avg_per_layer = {} 440 for li in range(n_layers): 441 if li in layer_sums: 442 avg_per_layer[li] = layer_sums[li] / N_TOKENS * 1000.0 # ms/layer/token 443 comps_by_layer[comp] = avg_per_layer 444 445 # Show layer-variance for top 3 components 446 top_comps = sorted(total_ms_per_token.keys(), key=lambda c: total_ms_per_token[c], reverse=True)[:4] 447 for comp in top_comps: 448 if comp in comps_by_layer and comps_by_layer[comp]: 449 vals = comps_by_layer[comp] 450 layer_ms = [vals.get(li, 0) for li in range(n_layers)] 451 min_v = min(layer_ms) 452 max_v = max(layer_ms) 453 avg_v = sum(layer_ms) / len(layer_ms) 454 print(f" {comp:25s}: min={min_v:.3f}ms max={max_v:.3f}ms avg={avg_v:.3f}ms " 455 f"range/avg={max_v/min_v:.1f}x" if min_v > 0 else 456 f" {comp:25s}: min={min_v:.3f}ms max={max_v:.3f}ms avg={avg_v:.3f}ms") 457 458 print(f"\nDone. (grand total = {grand_total_ms:.1f}ms for {N_TOKENS} tokens)") 459 460 461 if __name__ == '__main__': 462 main()