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 / src / mojollama / benchmarks / server_threaded_qwen36.py

181 lines · 7526 bytes Raw Blame History
1#!/usr/bin/env python3
2"""
3Qwen3.6 MXFP4 threaded server — weight-efficient.
4Master engine loaded once. Child threads share weight refs, get fresh buffers.
5"""
6import sys, os, time, threading, ctypes, numpy as np
7
8sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'kernels'))
9MODEL = "/tmp/models/qwen3.6-mxfp4.gguf"
10N_WORKERS = 1
11GEN_TOKENS = 50
12OMP_PER = 1 # each thread runs single-threaded (avoids OMP pool contention)
13
14os.environ['OMP_NUM_THREADS'] = str(OMP_PER)
15
16from turbo_engine_v7_moe import TurboEngineV7MoE
17
18def create_child(master):
19 """Create a lightweight child engine sharing master's weights."""
20 child = TurboEngineV7MoE.__new__(TurboEngineV7MoE)
21 # Share read-only data (references — no copy)
22 for attr in ['n_embd','n_head','n_kv_head','head_dim','n_ff','n_layers',
23 'vocab_size','eps','n_experts','n_experts_per_tok','n_ff_expert',
24 'is_moe','arch_prefix','rope_dim','rope_freq_base',
25 'full_attn_interval','n_layers_actual',
26 'ssm_groups','ssm_state_size','ssm_dt_rank','ssm_conv_kernel','ssm_inner',
27 'layer_types','n_threads','model_path',
28 'weights','raw_weights','weight_qtypes','weight_info',
29 'emb','reader',
30 '_kern','_simd','_cengine','_gqa_attn',
31 '_layers','_moe_layers',
32 '_out_raw','_out_nr','_out_nc','_out_qt','_out_use_c',
33 '_out_norm_w','_out_f32',
34 'out_w_name']:
35 if hasattr(master, attr):
36 setattr(child, attr, getattr(master, attr))
37
38 # Create fresh per-thread buffers (same as _init_buffers)
39 N = master.n_embd
40 NK = master.n_head * master.head_dim
41 NKH = master.n_kv_head * master.head_dim
42 MAX_POS = 4096
43 FF_expert = master.n_ff_expert if master.is_moe else master.n_ff
44 FF = master.n_ff
45
46 child.kv_k = np.zeros((master.n_layers, MAX_POS, NKH), dtype=np.float32)
47 child.kv_v = np.zeros((master.n_layers, MAX_POS, NKH), dtype=np.float32)
48 child.kv_len = np.zeros(master.n_layers, dtype=np.int32)
49
50 child._x = np.zeros(N, dtype=np.float32)
51 child._x_norm = np.zeros(N, dtype=np.float32)
52 child._residual = np.zeros(N, dtype=np.float32)
53 qkv_sz = max(NK + NKH, 8192) if getattr(master, 'arch_prefix', '') == 'qwen35moe' else NK + NKH
54 child._qk = np.zeros(qkv_sz, dtype=np.float32)
55 child._q = child._qk[:NK]
56 child._k = child._qk[NK:NK+NKH]
57 child._v = np.zeros(NKH, dtype=np.float32)
58 child._att_out = np.zeros(NK, dtype=np.float32)
59 child._o_proj = np.zeros(N, dtype=np.float32)
60 child._gate = np.zeros(FF, dtype=np.float32)
61 child._up = np.zeros(FF, dtype=np.float32)
62 child._silu_gate = np.zeros(FF, dtype=np.float32)
63 child._ffn_out = np.zeros(N, dtype=np.float32)
64
65 n_exp = max(128, master.n_experts) if master.is_moe else 128
66 child._moe_router_scores = np.zeros(n_exp, dtype=np.float32)
67 child._moe_gate_out = np.zeros(FF_expert, dtype=np.float32)
68 child._moe_up_out = np.zeros(FF_expert, dtype=np.float32)
69 child._moe_silu_out = np.zeros(FF_expert, dtype=np.float32)
70 child._moe_expert_out = np.zeros(N, dtype=np.float32)
71 child._moe_combined = np.zeros(N, dtype=np.float32)
72 max_top_k = max(8, master.n_experts_per_tok)
73 child._moe_prealloc_buf = np.zeros(3 * max_top_k * FF_expert, dtype=np.float32)
74 child._moe_prealloc_q8 = np.zeros((N // 32) * 34, dtype=np.uint8)
75 child._logits = np.zeros(master.vocab_size, dtype=np.float32)
76
77 if master.arch_prefix == 'qwen35moe':
78 child._ssm_state = np.zeros((master.n_layers, master.ssm_groups, master.ssm_state_size), dtype=np.float32)
79 child._ssm_intermediate = np.zeros(master.ssm_inner, dtype=np.float32)
80 child._gate_4096 = np.zeros(master.ssm_inner, dtype=np.float32)
81 else:
82 child._ssm_state = None; child._ssm_intermediate = None; child._gate_4096 = None
83
84 # ctypes pointers
85 cf = ctypes.POINTER(ctypes.c_float)
86 child._p_x = child._x.ctypes.data_as(cf)
87 child._p_x_norm = child._x_norm.ctypes.data_as(cf)
88 child._p_residual = child._residual.ctypes.data_as(cf)
89 child._p_q = child._q.ctypes.data_as(cf)
90 child._p_k = child._k.ctypes.data_as(cf)
91 child._p_v = child._v.ctypes.data_as(cf)
92 child._p_qk = child._qk.ctypes.data_as(cf)
93 child._p_att_out = child._att_out.ctypes.data_as(cf)
94 child._p_gate = child._gate.ctypes.data_as(cf)
95 child._p_up = child._up.ctypes.data_as(cf)
96 child._p_silu_gate = child._silu_gate.ctypes.data_as(cf)
97 child._p_o_proj = child._o_proj.ctypes.data_as(cf)
98 child._p_ffn = child._ffn_out.ctypes.data_as(cf)
99 child._p_logits = child._logits.ctypes.data_as(cf)
100 child._p_moe_router = child._moe_router_scores.ctypes.data_as(cf)
101 child._p_moe_gate = child._moe_gate_out.ctypes.data_as(cf)
102 child._p_moe_up = child._moe_up_out.ctypes.data_as(cf)
103 child._p_moe_silu = child._moe_silu_out.ctypes.data_as(cf)
104 child._p_moe_expert = child._moe_expert_out.ctypes.data_as(cf)
105 child._p_moe_combined = child._moe_combined.ctypes.data_as(cf)
106
107 child._rope_cos_table = {}
108 child._rope_sin_table = {}
109 child._eps_f = ctypes.c_float(master.eps)
110 child._gqa_rep = master.n_head // master.n_kv_head if master.n_head != master.n_kv_head else 1
111 child.pos = 0
112
113 return child
114
115# ── Server ──
116print(f"Loading master engine...", flush=True)
117master = TurboEngineV7MoE(MODEL, 32)
118print(f"Creating {N_WORKERS} children...", flush=True)
119
120results = [None] * N_WORKERS
121
122def worker(tid):
123 os.environ['OMP_NUM_THREADS'] = str(OMP_PER)
124 try:
125 e = create_child(master)
126 # Warmup
127 for _ in range(3):
128 e.forward(np.array([[1]], dtype=np.int32))
129 e.kv_len[:] = 0; e.pos = 0
130 if e._ssm_state is not None: e._ssm_state.fill(0)
131
132 # Benchmark
133 tok = np.array([[1 + tid]], dtype=np.int32)
134 t_list = []
135 for step in range(GEN_TOKENS):
136 t0 = time.perf_counter()
137 logits = e.forward(tok)
138 t_list.append(time.perf_counter() - t0)
139 tok = np.array([[int(np.argmax(logits))]], dtype=np.int32)
140 t_list = t_list[5:]
141 avg_ms = float(np.mean(t_list) * 1000)
142 tps = float(1000 / avg_ms)
143 results[tid] = (avg_ms, tps)
144 except Exception as ex:
145 import traceback; traceback.print_exc()
146 results[tid] = ('err', str(ex)[:100])
147
148threads = []
149t_start = time.perf_counter()
150for i in range(N_WORKERS):
151 t = threading.Thread(target=worker, args=(i,))
152 threads.append(t)
153 t.start()
154
155for t in threads:
156 t.join()
157
158wall = time.perf_counter() - t_start
159
160print(f"\n{'='*60}")
161print(f" Qwen3.6 MXFP4 — Threaded Server (children share weight refs)")
162print(f"{'='*60}")
163tps_list = []
164for tid in range(N_WORKERS):
165 r = results[tid]
166 if r and r[0] != 'err':
167 ms, tps = r
168 print(f" Worker {tid:2d}: {ms:5.1f}ms → {tps:5.1f} tok/s")
169 tps_list.append(tps)
170 elif r and r[0] == 'err':
171 print(f" Worker {tid:2d}: ERROR {r[1]}")
172
173if tps_list:
174 avg_tps = float(np.mean(tps_list))
175 agg = avg_tps * N_WORKERS
176 print(f"{'─'*60}")
177 print(f" Per-user: {avg_tps:.1f} tok/s avg")
178 print(f" Aggregate: {agg:.0f} tok/s")
179 print(f" Wall: {wall:.1f}s")
180 print(f" 200% target (51 tok/s): {agg/51:.1f}x {'PASS' if agg>51 else 'FAIL'}")
181 print(f" 750% target (191 tok/s): {agg/191:.1f}x {'PASS' if agg>191 else 'FAIL'}")