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_profile.py

159 lines · 5525 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Profile the OMP engine layer-by-layer to find bottlenecks."""
3import time, sys, os, ctypes, numpy as np
4
5# Add project path
6sys.path.insert(0, '/onedev-workspace/work/src')
7os.chdir('/onedev-workspace/work')
8
9from mojollama.kernels.omp_engine import Model, mm, rms, Q4_TS
10import gguf
11
12# Load model
13mdl = Model('Llama-3.2-1B-Instruct-Q4_0.gguf')
14n = mdl.n
15hd = n["head_dim"]
16nh = n["n_head"]
17nkh = n["n_kv_head"]
18print(f"Model: {n}")
19
20# Setup KV cache
21kvc = [{"k": np.zeros((0, n["n_kv"]), dtype=np.float32),
22 "v": np.zeros((0, n["n_kv"]), dtype=np.float32)}
23 for _ in range(n["n_layers"])]
24
25# Get first token embedding
26h = mdl.get("token_embd.weight")[0][128000].astype(np.float32).copy()
27print(f"Embedding shape: {h.shape}, dtype: {h.dtype}")
28
29# Warmup C library
30dummy_out = np.zeros(1, dtype=np.float32)
31w_test = mdl.get("blk.0.attn_q.weight")[0]
32x_test = h.copy()
33mm(mdl.get("blk.0.attn_q.weight"), h, n["n_embd"])
34
35print("\n=== Per-Operation Profiling (Layer 0) ===\n")
36
37layer = 0
38iterations = 50
39
40# 1. RMS Norm
41times_rms = []
42for _ in range(iterations):
43 t0 = time.perf_counter()
44 h_normed = rms(h, mdl.get(f"blk.{layer}.attn_norm.weight")[0])
45 t1 = time.perf_counter()
46 times_rms.append((t1-t0)*1000)
47print(f"RMS norm: {np.median(times_rms):.3f} ms (median of {iterations})")
48
49# 2. Q projection (2048 → 2048)
50times_q = []
51for _ in range(iterations):
52 t0 = time.perf_counter()
53 q = mm(mdl.get(f"blk.{layer}.attn_q.weight"), h_normed.copy(), n["n_embd"])
54 t1 = time.perf_counter()
55 times_q.append((t1-t0)*1000)
56print(f"Q proj (2048→2048): {np.median(times_q):.3f} ms")
57
58# 3. K projection (2048 → 512)
59times_k = []
60for _ in range(iterations):
61 t0 = time.perf_counter()
62 k = mm(mdl.get(f"blk.{layer}.attn_k.weight"), h_normed.copy(), n["n_embd"])
63 t1 = time.perf_counter()
64 times_k.append((t1-t0)*1000)
65print(f"K proj (2048→512): {np.median(times_k):.3f} ms")
66
67# 4. V projection (2048 → 512)
68times_v = []
69for _ in range(iterations):
70 t0 = time.perf_counter()
71 v = mm(mdl.get(f"blk.{layer}.attn_v.weight"), h_normed.copy(), n["n_embd"])
72 t1 = time.perf_counter()
73 times_v.append((t1-t0)*1000)
74print(f"V proj (2048→512): {np.median(times_v):.3f} ms")
75
76# 5. RoPE
77q2 = q.reshape(nh, hd)
78k2 = k.reshape(nkh, hd)
79times_rope = []
80for _ in range(iterations):
81 q_copy = q2.copy()
82 k_copy = k2.copy()
83 t0 = time.perf_counter()
84 freqs = 1.0 / (500000.0 ** (np.arange(0, hd, 2, dtype=np.float32) / hd))
85 cos_f = np.cos(0 * freqs)
86 sin_f = np.sin(0 * freqs)
87 for xx, nx in [(q_copy, nh), (k_copy, nkh)]:
88 xr = xx.reshape(nx, hd//2, 2)
89 xr_rot = np.stack([-xr[...,1], xr[...,0]], axis=-1)
90 xx[:] = (xr*cos_f.reshape(1,hd//2,1) + xr_rot*sin_f.reshape(1,hd//2,1)).reshape(nx, hd)
91 t1 = time.perf_counter()
92 times_rope.append((t1-t0)*1000)
93print(f"RoPE: {np.median(times_rope):.3f} ms")
94
95# 6. Attention
96times_attn = []
97for _ in range(iterations):
98 t0 = time.perf_counter()
99 ng = nh // nkh
100 att = np.zeros(nh*hd, dtype=np.float32)
101 for hh in range(nh):
102 kvh = hh // ng
103 ks = kvc[layer]["k"][0:1, kvh*hd:(kvh+1)*hd]
104 vs = kvc[layer]["v"][0:1, kvh*hd:(kvh+1)*hd]
105 sc = q2[hh] @ ks.T
106 sc = sc - np.max(sc)
107 att[hh*hd:(hh+1)*hd] = (np.exp(sc)/np.sum(np.exp(sc))) @ vs
108 t1 = time.perf_counter()
109 times_attn.append((t1-t0)*1000)
110print(f"Attention (1 pos, 32 heads): {np.median(times_attn):.3f} ms")
111
112# 7. O projection + residual
113times_o = []
114for _ in range(iterations):
115 t0 = time.perf_counter()
116 h = rms(h, mdl.get(f"blk.{layer}.attn_norm.weight")[0])
117 r = h.copy()
118 att_out = mm(mdl.get(f"blk.{layer}.attn_output.weight"), att, n["n_embd"])
119 h = r + att_out
120 t1 = time.perf_counter()
121 times_o.append((t1-t0)*1000)
122print(f"O proj + residual (2048→2048): {np.median(times_o):.3f} ms")
123
124# 8. FFN
125times_ffn = []
126for _ in range(iterations):
127 h_ffn = h.copy()
128 t0 = time.perf_counter()
129 h_normed = rms(h_ffn, mdl.get(f"blk.{layer}.ffn_norm.weight")[0])
130 gate = mm(mdl.get(f"blk.{layer}.ffn_gate.weight"), h_normed, n["n_embd"])
131 gate = gate / (1 + np.exp(-gate))
132 up = mm(mdl.get(f"blk.{layer}.ffn_up.weight"), h_normed, n["n_embd"])
133 down = mm(mdl.get(f"blk.{layer}.ffn_down.weight"), gate*up, n["n_ff"])
134 h_ffn = h_ffn + down
135 t1 = time.perf_counter()
136 times_ffn.append((t1-t0)*1000)
137print(f"FFN (gate+up+down): {np.median(times_ffn):.3f} ms")
138
139# 9. Just the overhead (no computation)
140times_overhead = []
141for _ in range(iterations):
142 t0 = time.perf_counter()
143 _ = mdl.get(f"blk.{layer}.attn_q.weight") # weight lookup
144 _ = h.copy() # numpy copy
145 t1 = time.perf_counter()
146 times_overhead.append((t1-t0)*1000)
147print(f"Python overhead (lookup+copy): {np.median(times_overhead):.3f} ms")
148
149# Summary
150total_matmul = np.median(times_q) + np.median(times_k) + np.median(times_v) + np.median(times_o) + np.median(times_ffn)
151other = 57.0 - total_matmul # from observed layer time
152print(f"\n=== Summary ===")
153print(f"Q+K+V+O+FFN matmul time: {total_matmul:.3f} ms")
154print(f"RMS norm: {np.median(times_rms):.3f} ms")
155print(f"RoPE: {np.median(times_rope):.3f} ms")
156print(f"Attention: {np.median(times_attn):.3f} ms")
157print(f"Python overhead: {np.median(times_overhead):.3f} ms")
158print(f"Estimated layer total: {total_matmul + np.median(times_rms)*2 + np.median(times_rope) + np.median(times_attn):.3f} ms")
159print(f"Target: <3ms per layer (for >80 tok/s × 16 layers = ~12ms total)")