interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / bench_fast_profile.py

126 lines · 4363 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Detailed forward pass profiling for FastEngine."""
3import sys, os, time, numpy as np
4sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
5
6from mojollama.kernels.fast_engine import FastEngine
7
8engine = FastEngine('Llama-3.2-1B-Instruct-Q4_0.gguf', n_threads=32)
9engine.reset()
10
11# Warmup
12engine.forward([128000])
13engine.forward([9906])
14
15print("\n=== Detailed Layer Profile ===\n")
16
17# Profile each component of layer 0
18h = engine._emb_cache[128000].astype(np.float32).copy()
19n_embd = engine.n_embd
20
21# Time each op 100 times
22def bench(label, fn, iters=100):
23 # Warmup
24 for _ in range(5): fn()
25 times = []
26 for _ in range(iters):
27 t0 = time.perf_counter()
28 fn()
29 t1 = time.perf_counter()
30 times.append((t1-t0)*1e6)
31 times.sort()
32 med = times[iters//2]
33 print(f" {label:40s}: {med:8.1f} µs")
34 return med
35
36# RMS norm
37t_rms = bench("RMS norm (C kernel)", lambda: engine.rms_norm(h, 'blk.0.attn_norm.weight'))
38
39# Q projection
40t_q = bench("Q proj (C OMP)", lambda: engine.matmul('blk.0.attn_q.weight', h, n_embd))
41
42# K projection
43t_k = bench("K proj (C OMP)", lambda: engine.matmul('blk.0.attn_k.weight', h, n_embd))
44
45# V projection
46t_v = bench("V proj (C OMP)", lambda: engine.matmul('blk.0.attn_v.weight', h, n_embd))
47
48# RoPE (both Q and K)
49q = engine.matmul('blk.0.attn_q.weight', h, n_embd)
50t_rope = bench("RoPE Q+K", lambda: (engine.apply_rope(q, 0, engine.n_head),
51 engine.apply_rope(q, 0, engine.n_kv_head)))
52
53# Attention (single position, Python loop)
54k_new = engine.matmul('blk.0.attn_k.weight', h, n_embd)
55v_new = engine.matmul('blk.0.attn_v.weight', h, n_embd)
56
57# Reset KV for attention test
58engine.kv_k[0] = np.zeros((0, engine.n_kv), dtype=np.float32)
59engine.kv_v[0] = np.zeros((0, engine.n_kv), dtype=np.float32)
60t_attn = bench("Attention (1 pos, Python+einsum)", lambda: engine.attention(q, k_new, v_new, 0, 0))
61
62# O projection
63att = np.random.randn(engine.n_embd).astype(np.float32)
64t_o = bench("O proj (C OMP)", lambda: engine.matmul('blk.0.attn_output.weight', att, n_embd))
65
66# FFN norm
67t_ffn_norm = bench("RMS norm FFN (C kernel)", lambda: engine.rms_norm(h, 'blk.0.ffn_norm.weight'))
68
69# FFN gate
70t_gate = bench("FFN gate (C OMP)", lambda: engine.matmul('blk.0.ffn_gate.weight', h, n_embd))
71
72# SiLU
73gate_raw = np.random.randn(engine.n_ff).astype(np.float32)
74t_silu = bench("SiLU (C kernel)", lambda: engine.silu(gate_raw.copy()))
75
76# FFN up
77t_up = bench("FFN up (C OMP)", lambda: engine.matmul('blk.0.ffn_up.weight', h, n_embd))
78
79# FFN down
80gate_up = np.random.randn(engine.n_ff).astype(np.float32)
81t_down = bench("FFN down (C OMP)", lambda: engine.matmul('blk.0.ffn_down.weight', gate_up, engine.n_ff))
82
83# Residual add
84t_resid = bench("Residual add (numpy)", lambda: h + h)
85
86# KV cache vstack
87kv_k = np.random.randn(1, engine.n_kv).astype(np.float32)
88kv_v = np.random.randn(1, engine.n_kv).astype(np.float32)
89t_kv_update = bench("KV cache update (vstack)",
90 lambda: np.vstack([np.zeros((1, engine.n_kv), dtype=np.float32), kv_k]))
91
92# Total estimate
93total_per_layer = (t_rms*2 + t_q + t_k + t_v + t_rope + t_attn + t_o +
94 t_ffn_norm + t_gate + t_silu + t_up + t_down + t_resid*2 + t_kv_update*2)
95total_16layers = total_per_layer * engine.n_layers
96tok_per_sec = 1e6 / total_16layers
97
98print(f"\n=== Summary ===")
99print(f"Per layer: {total_per_layer/1000:.2f} ms")
100print(f"Total (16 layers): {total_16layers/1000:.2f} ms")
101print(f"Estimated decode: {tok_per_sec:.1f} tok/s")
102print(f"Target: 85 tok/s (llama.cpp)")
103print(f"Gap: {(85 - tok_per_sec)/85*100:.1f}%")
104
105# Breakdown by category
106matmul_total = t_q + t_k + t_v + t_o + t_gate + t_up + t_down
107other_total = total_per_layer - matmul_total
108print(f"\nMatmul total: {matmul_total/1000:.2f} ms ({matmul_total/total_per_layer*100:.1f}%)")
109print(f"Other (Python): {other_total/1000:.2f} ms ({other_total/total_per_layer*100:.1f}%)")
110
111# Now measure actual forward pass
112engine.reset()
113for tok in [128000, 9906]:
114 engine.forward([tok])
115
116times = []
117next_tok = 3000
118for i in range(20):
119 t0 = time.perf_counter()
120 logits = engine.forward([next_tok])
121 t1 = time.perf_counter()
122 times.append((t1-t0)*1000)
123 next_tok = int(np.argmax(logits))
124
125times.sort()
126print(f"\nActual decode (median): {times[10]:.2f} ms/tok = {1000/times[10]:.1f} tok/s")