MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / turbo_engine_v7_moe.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | TurboEngine v7-MoE — Zero-allocation engine with C-accelerated MoE support. |
| 4 | |
| 5 | Optimized load: keeps large 2D tensors as raw quantized (no F32 dequant). |
| 6 | Uses C quant_matmul_omp for all projections including expert matmuls. |
| 7 | """ |
| 8 | |
| 9 | import numpy as np |
| 10 | import ctypes |
| 11 | import os |
| 12 | import time |
| 13 | import gguf |
| 14 | from gguf.constants import GGMLQuantizationType as QT |
| 15 | |
| 16 | from forward.base import ArchitectureForwardPass |
| 17 | from forward.zaya_bc import BC |
| 18 | |
| 19 | GGML_F32 = 0; GGML_F16 = 1; GGML_Q4_0 = 2; GGML_Q4_1 = 3 |
| 20 | GGML_Q5_0 = 6 |
| 21 | GGML_Q8_0 = 8; GGML_Q4_K = 12; GGML_Q5_K = 13; GGML_Q6_K = 14; GGML_MXFP4 = 39 |
| 22 | C_KERNEL_TYPES = {GGML_Q4_0, GGML_Q4_1, GGML_Q4_K, GGML_Q5_K, GGML_Q6_K, GGML_Q8_0, GGML_MXFP4, GGML_Q5_0} |
| 23 | QTYPE_NAMES = {0:"F32",1:"F16",2:"Q4_0",3:"Q4_1",12:"Q4_K",8:"Q8_0",13:"Q5_K",14:"Q6_K"} |
| 24 | BLOCK_SIZES = {2:18, 3:20, 6:22, 12:144, 13:176, 14:210, 8:34, 39:17} |
| 25 | BLOCK_VALS = {2:32, 3:32, 6:32, 12:256, 13:256, 14:256, 8:32, 39:32} |
| 26 | |
| 27 | |
| 28 | class MoEExpertPointers: |
| 29 | """Pre-computed raw quantized pointers for one MoE layer's experts.""" |
| 30 | __slots__ = ['gate_raw', 'up_raw', 'down_raw', |
| 31 | 'gate_ptrs', 'up_ptrs', 'down_ptrs', |
| 32 | 'gate_ptrs_arr', 'up_ptrs_arr', 'down_ptrs_arr', |
| 33 | 'gate_nr', 'gate_nc', 'gate_qt', |
| 34 | 'up_nr', 'up_nc', 'up_qt', |
| 35 | 'down_nr', 'down_nc', 'down_qt', |
| 36 | 'gate_use_c', 'up_use_c', 'down_use_c', |
| 37 | 'gate_f32', 'up_f32', 'down_f32', |
| 38 | 'router_raw', 'router_nr', 'router_nc', 'router_qt', |
| 39 | 'router_f32', |
| 40 | 'n_experts', 'n_ff_expert', 'n_embd'] |
| 41 | |
| 42 | def __init__(self): |
| 43 | self.gate_raw = [] |
| 44 | self.up_raw = [] |
| 45 | self.down_raw = [] |
| 46 | self.gate_ptrs = [] |
| 47 | self.up_ptrs = [] |
| 48 | self.down_ptrs = [] |
| 49 | self.gate_ptrs_arr = None |
| 50 | self.up_ptrs_arr = None |
| 51 | self.down_ptrs_arr = None |
| 52 | self.router_raw = None |
| 53 | self.router_f32 = None |
| 54 | self.gate_use_c = False |
| 55 | self.up_use_c = False |
| 56 | self.down_use_c = False |
| 57 | |
| 58 | |
| 59 | class LayerWeights: |
| 60 | """Dense layer weights — pre-computed ctypes pointers.""" |
| 61 | __slots__ = ['attn_q_raw', 'attn_k_raw', 'attn_v_raw', 'attn_out_raw', |
| 62 | 'ffn_gate_raw', 'ffn_up_raw', 'ffn_down_raw', |
| 63 | 'attn_q_nr', 'attn_q_nc', 'attn_q_qt', |
| 64 | 'attn_k_nr', 'attn_k_nc', 'attn_k_qt', |
| 65 | 'attn_v_nr', 'attn_v_nc', 'attn_v_qt', |
| 66 | 'attn_out_nr', 'attn_out_nc', 'attn_out_qt', |
| 67 | 'ffn_gate_nr', 'ffn_gate_nc', 'ffn_gate_qt', |
| 68 | 'ffn_up_nr', 'ffn_up_nc', 'ffn_up_qt', |
| 69 | 'ffn_down_nr', 'ffn_down_nc', 'ffn_down_qt', |
| 70 | 'attn_norm_w', 'ffn_norm_w', |
| 71 | 'attn_q_f32', 'attn_k_f32', 'attn_v_f32', 'attn_out_f32', |
| 72 | 'ffn_gate_f32', 'ffn_up_f32', 'ffn_down_f32', |
| 73 | 'attn_q_use_c', 'attn_k_use_c', 'attn_v_use_c', 'attn_out_use_c', |
| 74 | 'ffn_gate_use_c', 'ffn_up_use_c', 'ffn_down_use_c', |
| 75 | 'q_norm_w', 'k_norm_w', |
| 76 | 'has_q_norm', 'has_k_norm', |
| 77 | 'moe', |
| 78 | 'attn_qk_raw', 'attn_qk_nr', 'attn_qk_nc', 'attn_qk_qt', |
| 79 | 'attn_qk_use_c', |
| 80 | '_attn_qk_raw_buf', |
| 81 | # Qwen3.6 hybrid SSM+attention fields |
| 82 | 'attn_qkv_raw', 'attn_qkv_nr', 'attn_qkv_nc', 'attn_qkv_qt', 'attn_qkv_use_c', |
| 83 | 'attn_gate_raw', 'attn_gate_nr', 'attn_gate_nc', 'attn_gate_qt', 'attn_gate_use_c', |
| 84 | 'ssm_conv1d_ptr', 'ssm_a_ptr', 'ssm_dt_bias_ptr', |
| 85 | 'ssm_alpha_ptr', 'ssm_beta_ptr', 'ssm_norm_ptr', |
| 86 | 'ssm_out_raw', 'ssm_out_nr', 'ssm_out_nc', 'ssm_out_qt', 'ssm_out_use_c', |
| 87 | 'shexp_gate_raw', 'shexp_gate_nr', 'shexp_gate_nc', 'shexp_gate_qt', 'shexp_gate_use_c', |
| 88 | 'shexp_up_raw', 'shexp_up_nr', 'shexp_up_nc', 'shexp_up_qt', 'shexp_up_use_c', |
| 89 | 'shexp_down_raw', 'shexp_down_nr', 'shexp_down_nc', 'shexp_down_qt', 'shexp_down_use_c', |
| 90 | 'shexp_router_ptr', 'shexp_router_nr', |
| 91 | # Gemma4 specific fields |
| 92 | 'post_attn_norm_w', 'post_ffw_norm_w', 'post_norm_w', |
| 93 | 'per_layer_proj', 'per_layer_inp_gate', 'layer_scale', |
| 94 | 'gemma4_nq', 'gemma4_nk', 'gemma4_nv', 'gemma4_head_dim', |
| 95 | 'gemma4_is_swa', 'gemma4_rope_dim', 'gemma4_freq_base', 'gemma4_kv_idx', |
| 96 | # ZAYA specific fields |
| 97 | 'res_scale_hs_w', 'res_scale_hs_b', 'res_scale_res_w', 'res_scale_res_b', |
| 98 | 'ffn_gate_inp_w', 'ffn_gate_inp_b', 'ffn_gate_w', 'ffn_gate_b', 'ffn_norm_w', |
| 99 | 'zaya_router_mlp2_w', 'zaya_router_mlp2_b', 'zaya_router_mlp4_w', |
| 100 | 'zaya_router_biases_w', 'zaya_router_eda_w', |
| 101 | 'cca_val_proj1_w', 'cca_val_proj2_w', |
| 102 | 'cca_vp1_raw', 'cca_vp2_raw', 'cca_vp1_nr', 'cca_vp2_nr', |
| 103 | 'cca_vp1_nc', 'cca_vp2_nc', 'cca_vp1_qt', 'cca_vp2_qt', |
| 104 | 'ssm_conv1d_w', 'ssm_conv1d_b', |
| 105 | 'gate_up_exps_raw_arr', 'down_exps_raw_arr', |
| 106 | 'gate_up_exps_nr', 'down_exps_nr', |
| 107 | 'gate_up_exps_nc', 'down_exps_nc', |
| 108 | 'gate_up_exps_qt', 'down_exps_qt', |
| 109 | 'gate_up_exps_n_exp', 'down_exps_n_exp', |
| 110 | 'gate_up_ptrs', 'down_ptrs', |
| 111 | 'gate_up_info', 'down_info'] |
| 112 | |
| 113 | |
| 114 | class TurboEngineV7MoE: |
| 115 | """Zero-allocation engine with MoE support via C quant matmul.""" |
| 116 | |
| 117 | def __init__(self, model_path, n_threads=32): |
| 118 | os.environ['OMP_NUM_THREADS'] = str(n_threads) |
| 119 | self.n_threads = n_threads |
| 120 | self.model_path = model_path |
| 121 | |
| 122 | t_start = time.perf_counter() |
| 123 | self.reader = gguf.GGUFReader(model_path) |
| 124 | self._parse_metadata() |
| 125 | print(f" GGUFReader: {time.perf_counter()-t_start:.1f}s", flush=True) |
| 126 | |
| 127 | # Architecture forward dispatch |
| 128 | self._arch_forward = None |
| 129 | if self.arch_name == 'gemma4': |
| 130 | # Gemma4 E4B (42L) uses C forward; Gemma4 26B (30L) uses Python forward |
| 131 | if self.n_layers >= 35: |
| 132 | from forward.gemma4 import ForwardGemma4 |
| 133 | self._arch_forward = ForwardGemma4(self) |
| 134 | else: |
| 135 | # Gemma4 26B: override head_dim from GGUF (512 or n_embd//n_head=176) to actual 256 |
| 136 | # WHY: The GGUF stores attention.key_length=512 (rope dim for K) which |
| 137 | # the engine uses as head_dim. Actual Q head_dim = Q_dim/NH = 4096/16 = 256. |
| 138 | # The forward class (ForwardGemma4_26B) hardcodes HD=256 internally. |
| 139 | self.head_dim = 256 |
| 140 | from forward.gemma4_26b import ForwardGemma4_26B |
| 141 | self._arch_forward = ForwardGemma4_26B(self) |
| 142 | elif self.arch_name == 'zaya': |
| 143 | from forward.zaya import ForwardZaya |
| 144 | self._arch_forward = ForwardZaya(self) |
| 145 | |
| 146 | self._load_kernels() |
| 147 | t0 = time.perf_counter() |
| 148 | self._load_weights() |
| 149 | print(f" Weights: {time.perf_counter()-t0:.1f}s", flush=True) |
| 150 | |
| 151 | t0 = time.perf_counter() |
| 152 | self._preload_pointers() |
| 153 | print(f" Preload pointers: {time.perf_counter()-t0:.1f}s", flush=True) |
| 154 | |
| 155 | t0 = time.perf_counter() |
| 156 | self._init_buffers() |
| 157 | print(f" Buffers: {time.perf_counter()-t0:.1f}s", flush=True) |
| 158 | |
| 159 | t0 = time.perf_counter() |
| 160 | self._init_c_batch_caches() |
| 161 | print(f" C batch caches: {time.perf_counter()-t0:.1f}s", flush=True) |
| 162 | |
| 163 | self.reset() |
| 164 | moe_str = f'/MoE-{self.n_experts}x{self.n_experts_per_tok}' if self.is_moe else '' |
| 165 | print(f"TurboEngine v7-MoE: {self.n_layers}L/{self.n_embd}D/" |
| 166 | f"{self.n_ff}FF/{self.n_head}H/{self.n_kv_head}KV" |
| 167 | f"{moe_str} | t={self.n_threads} | vocab={self.vocab_size}") |
| 168 | |
| 169 | def _parse_metadata(self): |
| 170 | fields = self.reader.fields |
| 171 | def _get(name): |
| 172 | for key, val in fields.items(): |
| 173 | if key == name: |
| 174 | parts = val.parts if hasattr(val, 'parts') else [] |
| 175 | if len(parts) >= 1: |
| 176 | data = parts[-1] |
| 177 | if hasattr(data, '__iter__') and len(data) == 1: |
| 178 | return int(data[0]) |
| 179 | return data |
| 180 | |
| 181 | # Read architecture from GGUF metadata (general.architecture) |
| 182 | arch_raw = _get('general.architecture') |
| 183 | if arch_raw is not None: |
| 184 | if isinstance(arch_raw, bytes): |
| 185 | arch = arch_raw.decode('utf-8') |
| 186 | elif isinstance(arch_raw, str): |
| 187 | arch = arch_raw |
| 188 | elif hasattr(arch_raw, 'tobytes'): |
| 189 | # numpy array of uint8 (GGUF string encoding) |
| 190 | arch = bytes(arch_raw.tolist()).decode('utf-8') |
| 191 | else: |
| 192 | arch = str(arch_raw) |
| 193 | else: |
| 194 | # Fallback: detect from known prefixes |
| 195 | arch = 'llama' |
| 196 | for prefix in ['gpt-oss', 'qwen35moe', 'qwen3moe', 'qwen2moe', 'qwen2', 'llama', 'mistral', 'falcon', 'gemma', 'starcoder2', 'phi3', 'deepseek2', 'mixtral']: |
| 197 | for key in fields: |
| 198 | if f'{prefix}.block_count' in key: |
| 199 | arch = prefix; break |
| 200 | if arch != 'llama': |
| 201 | break |
| 202 | |
| 203 | self.arch_name = arch |
| 204 | self.arch_prefix = arch |
| 205 | self.n_layers = int(_get(f'{arch}.block_count') or 16) |
| 206 | self.n_embd = int(_get(f'{arch}.embedding_length') or 2048) |
| 207 | self.n_ff = int(_get(f'{arch}.feed_forward_length') or self.n_embd * 4) |
| 208 | self.n_head = int(_get(f'{arch}.attention.head_count') or 32) |
| 209 | self.n_kv_head = int(_get(f'{arch}.attention.head_count_kv') or self.n_head) |
| 210 | self.head_dim = int(_get(f'{arch}.attention.key_length') or (self.n_embd // self.n_head)) |
| 211 | self.rope_freq_base = float(_get(f'{arch}.rope.freq_base') or 10000.0) |
| 212 | self.eps = float(_get(f'{arch}.attention.layer_norm_rms_epsilon') or 1e-6) |
| 213 | self.vocab_size = int(_get(f'{arch}.vocab_size') or 0) |
| 214 | self.n_experts = _get(f'{arch}.expert_count') |
| 215 | self.n_experts_per_tok = _get(f'{arch}.expert_used_count') or _get(f'{arch}.experts_used_count') |
| 216 | self.n_ff_expert = int(_get(f'{arch}.expert_feed_forward_length') or self.n_ff) |
| 217 | self.is_moe = self.n_experts is not None |
| 218 | if not self.is_moe: |
| 219 | self.n_experts = 1; self.n_experts_per_tok = 1 |
| 220 | else: |
| 221 | self.n_experts = int(self.n_experts); self.n_experts_per_tok = int(self.n_experts_per_tok) |
| 222 | self.arch_prefix = arch |
| 223 | # Qwen3.6 hybrid SSM+attention fields |
| 224 | self.rope_dim = int(_get(f'{arch}.rope.dimension_count') or 0) |
| 225 | self.full_attn_interval = int(_get(f'{arch}.full_attention_interval') or 4) |
| 226 | self.n_layers_actual = self.n_layers |
| 227 | # SSM parameters |
| 228 | self.ssm_groups = 32 |
| 229 | self.ssm_state_size = 128 |
| 230 | self.ssm_dt_rank = 32 |
| 231 | self.ssm_conv_kernel = 4 |
| 232 | self.ssm_inner = self.n_head * self.head_dim # 4096 |
| 233 | # Layer types: 0=full attention, 1=SSM (Qwen3.6 hybrid) |
| 234 | if self.arch_prefix == 'qwen35moe': |
| 235 | self.layer_types = [0 if i % self.full_attn_interval == 0 else 1 for i in range(self.n_layers)] |
| 236 | print(f" Qwen3.6 hybrid: {sum(1 for t in self.layer_types if t==0)} attn + {sum(1 for t in self.layer_types if t==1)} ssm layers, rope_dim={self.rope_dim}", flush=True) |
| 237 | else: |
| 238 | self.layer_types = None |
| 239 | |
| 240 | def _load_kernels(self): |
| 241 | kernel_dir = os.path.dirname(os.path.abspath(__file__)) |
| 242 | cf = ctypes.POINTER(ctypes.c_float) |
| 243 | cu = ctypes.POINTER(ctypes.c_uint8) |
| 244 | ci = ctypes.c_int |
| 245 | |
| 246 | # Load combined engine (merged quant_kernels + cengine_batch_instr, with Q5_0 Q8_0 kernel) |
| 247 | combined_path = os.path.join(kernel_dir, 'combined_engine.so') |
| 248 | so_path = combined_path if os.path.exists(combined_path) else os.path.join(kernel_dir, 'quant_kernels_omp.so') |
| 249 | if os.path.exists(so_path): |
| 250 | so = ctypes.CDLL(so_path) |
| 251 | so.quant_matmul_omp.argtypes = [cu, cf, cf, ci, ci, ci] |
| 252 | so.quant_matmul_omp.restype = None |
| 253 | so.f32_matmul_omp.argtypes = [cf, cf, cf, ci, ci] |
| 254 | so.f32_matmul_omp.restype = None |
| 255 | so.batch_qkv_omp.argtypes = [cu, cu, cu, cf, cf, cf, cf, ci, ci, ci, ci, ci, ci] |
| 256 | so.batch_qkv_omp.restype = None |
| 257 | so.batch_gate_up_omp.argtypes = [cu, cu, cf, cf, cf, ci, ci, ci, ci] |
| 258 | so.batch_gate_up_omp.restype = None |
| 259 | so.set_num_threads.argtypes = [ci] |
| 260 | so.set_num_threads.restype = None |
| 261 | so.set_num_threads(self.n_threads) |
| 262 | # Fused SSM layer forward — replaces 3 ctypes calls |
| 263 | so.ssm_layer_fused.argtypes = [ |
| 264 | cf, cf, cf, # x, residual, output |
| 265 | cf, cf, cf, # conv1d_w, a_param, dt_bias |
| 266 | cf, cf, cf, # alpha, beta, ssm_norm_w |
| 267 | cf, # state |
| 268 | cu, ci, ci, ci, # gate_raw, gate_nr, gate_nc, gate_qt |
| 269 | cu, ci, ci, ci, # ssm_out_raw, ssm_out_nr, ssm_out_nc, ssm_out_qt |
| 270 | ci, ci, ci, ci, ci, ci, ci] # B, N, inner, groups, state_size, conv_kernel, dt_rank |
| 271 | so.ssm_layer_fused.restype = None |
| 272 | # Full C batch forward — eliminates Python loop overhead |
| 273 | so.qwen36_batch_forward.argtypes = [ |
| 274 | # Scalars (18: 7+4+7 ints+float) |
| 275 | ci, ci, ci, ci, ci, ci, ci, # B, L, N, NH, n_kv_h, HD, FF |
| 276 | ci, ci, ci, ctypes.c_float, # n_experts, top_k, n_ff_expert, eps |
| 277 | ci, ci, ci, ci, ci, ci, ci, # rope_dim, max_ctx, ssm_inner, ssm_groups, ssm_state_size, ssm_conv_kernel, ssm_dt_rank |
| 278 | # Embedding |
| 279 | cf, ci, # emb, emb_quant |
| 280 | # Arrays (pointers) |
| 281 | ctypes.POINTER(ci), # layer_types |
| 282 | ctypes.POINTER(ci), # tokens |
| 283 | cf, # logits |
| 284 | # Per-layer weight pointer arrays |
| 285 | ctypes.POINTER(cf), ctypes.POINTER(cf), # attn_norm_w, ffn_norm_w |
| 286 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), # attn_qkv_raw, qkv_nr, qkv_nc, qkv_qt |
| 287 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), # attn_gate_raw, gate_nr, gate_nc, gate_qt |
| 288 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), # ssm_out_raw, ssm_out_nr, ssm_out_nc, ssm_out_qt |
| 289 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), # attn_out_raw, out_nr, out_nc, out_qt |
| 290 | ctypes.POINTER(cu), ctypes.POINTER(ci), # gate_exp_raw, gate_exp_qt |
| 291 | ctypes.POINTER(cu), ctypes.POINTER(ci), # up_exp_raw, up_exp_qt |
| 292 | ctypes.POINTER(cu), ctypes.POINTER(ci), # down_exp_raw, down_exp_qt |
| 293 | ctypes.POINTER(cf), ctypes.POINTER(cf), ctypes.POINTER(cf), # shexp_gate_raw, shexp_up_raw, shexp_down_raw |
| 294 | ctypes.POINTER(cf), # shexp_router |
| 295 | ctypes.POINTER(ci), # shexp_int |
| 296 | # Added MoE params |
| 297 | ctypes.POINTER(cu), ctypes.POINTER(ci), # moe_router_raw, moe_router_qt |
| 298 | ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), # shexp_gate_qt, shexp_up_qt, shexp_down_qt |
| 299 | # Output norm + proj |
| 300 | cf, cu, ci, ci, ci, # out_norm_w, out_w, out_nr_final, out_nc_final, out_qt_final |
| 301 | # SSM per-layer |
| 302 | ctypes.POINTER(cf), ctypes.POINTER(cf), ctypes.POINTER(cf), # ssm_conv1d, ssm_a, ssm_dt_bias |
| 303 | ctypes.POINTER(cf), ctypes.POINTER(cf), ctypes.POINTER(cf), # ssm_alpha, ssm_beta, ssm_norm |
| 304 | cf, # ssm_state |
| 305 | # KV cache |
| 306 | cf, cf, ctypes.POINTER(ci), # kv_k, kv_v, kv_lens |
| 307 | cf, cf, # cos_table, sin_table |
| 308 | # Workspace |
| 309 | cf, cu, # ws, q8_ws |
| 310 | ] |
| 311 | so.qwen36_batch_forward.restype = None |
| 312 | # GPT-OSS batch forward — separate Q/K/V, no SSM (optional) |
| 313 | # WHY: Was added to cengine_batch_instr.c in development but git |
| 314 | # checkout can lose it. Wrap in try/except so the engine still loads. |
| 315 | try: |
| 316 | so.gptoss_batch_forward.argtypes = [ |
| 317 | # Scalars (8 ints + 1 float + 2 ints) |
| 318 | ci, ci, ci, ci, ci, ci, ci, # B, L, N, NH, n_kv_h, HD, FF |
| 319 | ci, ci, ci, ctypes.c_float, # n_experts, top_k, n_ff_expert, eps |
| 320 | ci, ci, # rope_dim, max_ctx |
| 321 | # Embedding |
| 322 | cf, # emb |
| 323 | ctypes.POINTER(ci), # tokens |
| 324 | cf, # logits |
| 325 | # Per-layer weight pointer arrays |
| 326 | ctypes.POINTER(cf), ctypes.POINTER(cf), # attn_norm_w, post_attn_norm_w |
| 327 | # Q (raw ptr, nr, nc, qt) |
| 328 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), |
| 329 | # K (raw ptr, nr, nc, qt) |
| 330 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), |
| 331 | # V (raw ptr, nr, nc, qt) |
| 332 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), |
| 333 | # O (raw ptr, nr, nc, qt) |
| 334 | ctypes.POINTER(cu), ctypes.POINTER(ci), ctypes.POINTER(ci), ctypes.POINTER(ci), |
| 335 | # MoE router (F32 float**) + experts (uint8_t** + int*) |
| 336 | ctypes.POINTER(cf), # w_gate_inp (F32 router per layer) |
| 337 | ctypes.POINTER(cu), ctypes.POINTER(ci), # gate_exp_raw, gate_exp_qt |
| 338 | ctypes.POINTER(cu), ctypes.POINTER(ci), # up_exp_raw, up_exp_qt |
| 339 | ctypes.POINTER(cu), ctypes.POINTER(ci), # down_exp_raw, down_exp_qt |
| 340 | # Output norm + projection |
| 341 | cf, cu, ci, ci, ci, # out_norm_w, out_w, out_nr, out_nc, out_qt |
| 342 | # KV cache |
| 343 | cf, cf, ctypes.POINTER(ci), # kv_k, kv_v, kv_lens |
| 344 | cf, cf, # cos_table, sin_table |
| 345 | # Workspace |
| 346 | cf, cu, # ws, q8_ws |
| 347 | ] |
| 348 | so.gptoss_batch_forward.restype = None |
| 349 | except AttributeError: |
| 350 | pass # gptoss_batch_forward not compiled into .so — will use Python fallback |
| 351 | # ZAYA batch forward — BC struct based, MXFP4 MoE |
| 352 | try: |
| 353 | so.zaya_batch_forward.argtypes = [ |
| 354 | ctypes.POINTER(BC), # bc |
| 355 | ctypes.POINTER(ctypes.c_int), # tokens |
| 356 | ci, # B |
| 357 | cf, # ws (workspace) |
| 358 | ] |
| 359 | so.zaya_batch_forward.restype = None |
| 360 | except AttributeError: |
| 361 | pass # zaya_batch_forward not compiled into .so — will use Python fallback |
| 362 | # MoE fused kernel — eliminates 1,152 ctypes calls/token |
| 363 | so.moe_forward_omp.argtypes = [ |
| 364 | ctypes.POINTER(cu), # gate_raw[] — array of per-expert uint8_t* |
| 365 | ctypes.POINTER(cu), # up_raw[] |
| 366 | ctypes.POINTER(cu), # down_raw[] |
| 367 | cf, # x_norm |
| 368 | ci, ci, # n_ff_expert, n_embd |
| 369 | ci, ci, ci, # qt_gate, qt_up, qt_down |
| 370 | ctypes.POINTER(ctypes.c_int), # top_indices[top_k] |
| 371 | cf, # top_weights[top_k] |
| 372 | ci, # top_k |
| 373 | cf, # combined[n_embd] |
| 374 | cf, # prealloc_buf[3*top_k*n_ff_expert] |
| 375 | cu, # prealloc_q8[n_blocks_x*34] |
| 376 | ] |
| 377 | so.moe_forward_omp.restype = None |
| 378 | self._kern = so |
| 379 | # GQA attention C kernel |
| 380 | gqa_path = os.path.join(kernel_dir, 'gqa_attention.so') |
| 381 | if os.path.exists(gqa_path): |
| 382 | self._gqa_attn = ctypes.CDLL(gqa_path) |
| 383 | self._gqa_attn.gqa_attention_decode.argtypes = [ |
| 384 | cf, cf, cf, cf, ci, ci, ci, ci, cf] |
| 385 | self._gqa_attn.gqa_attention_decode.restype = None |
| 386 | else: |
| 387 | self._gqa_attn = None |
| 388 | # Dequant functions for requantize |
| 389 | so.q6_k_dequantize_row.argtypes = [cu, cf, ci] |
| 390 | so.q6_k_dequantize_row.restype = None |
| 391 | so.q4_k_dequantize_row.argtypes = [cu, cf, ci] |
| 392 | so.q4_k_dequantize_row.restype = None |
| 393 | else: |
| 394 | self._kern = None |
| 395 | |
| 396 | # Load cengine_batch_instr.so for batch_forward and ssm_decode_step |
| 397 | cengine_path = os.path.join(kernel_dir, 'cengine_batch_instr.so') |
| 398 | self._cengine = None |
| 399 | if os.path.exists(cengine_path): |
| 400 | ce = ctypes.CDLL(cengine_path) |
| 401 | # ssm_decode_step: void ssm_decode_step(x, ssm_intermediate, conv1d_w, a_param, dt_bias, alpha, beta, ssm_norm_w, state, B, N, inner, groups, state_size, conv_kernel, dt_rank) |
| 402 | ce.ssm_decode_step.argtypes = [ |
| 403 | cf, cf, cf, cf, cf, cf, cf, cf, cf, |
| 404 | ci, ci, ci, ci, ci, ci, ci] |
| 405 | ce.ssm_decode_step.restype = None |
| 406 | # batch_forward: void batch_forward(BC*, tokens, B, ws) |
| 407 | # We'll define BC struct later |
| 408 | self._cengine = ce |
| 409 | |
| 410 | simd_path = os.path.join(kernel_dir, 'simd_ops.so') |
| 411 | if os.path.exists(simd_path): |
| 412 | simd = ctypes.CDLL(simd_path) |
| 413 | simd.rms_norm.argtypes = [cf, cf, cf, ci, ctypes.c_float] |
| 414 | simd.rms_norm.restype = None |
| 415 | simd.silu.argtypes = [cf, cf, ci] |
| 416 | simd.silu.restype = None |
| 417 | simd.residual_add.argtypes = [cf, cf, cf, ci] |
| 418 | simd.residual_add.restype = None |
| 419 | simd.apply_rope.argtypes = [cf, cf, ci, ci, ci, ci, ctypes.c_float] |
| 420 | simd.apply_rope.restype = None |
| 421 | self._simd = simd |
| 422 | else: |
| 423 | self._simd = None |
| 424 | |
| 425 | def _load_weights(self): |
| 426 | """Load weights: keep quantized for C kernel dispatch, F32 only when needed.""" |
| 427 | self.weights = {} # F32 weights (1D norms, small 2D, fallback) |
| 428 | self.raw_weights = {} # Raw quantized bytes for C kernel |
| 429 | self.weight_qtypes = {} |
| 430 | self.weight_info = {} # For 2D: (n_rows, n_cols, block_sz, qt) |
| 431 | # For 3D: (out_dim, in_dim, block_sz, qt, n_experts) |
| 432 | |
| 433 | # Pre-scan to identify large tensors that should stay quantized only |
| 434 | skip_f32 = set() # tensor names to NOT dequantize to F32 |
| 435 | if self._kern is not None: |
| 436 | for t in self.reader.tensors: |
| 437 | name = t.name |
| 438 | if len(t.shape) == 2: |
| 439 | in_dim, out_dim = int(t.shape[0]), int(t.shape[1]) |
| 440 | qtype = QT(t.tensor_type).value |
| 441 | if qtype in C_KERNEL_TYPES: |
| 442 | f32_mb = out_dim * in_dim * 4 / 1024 / 1024 |
| 443 | if f32_mb > 10: |
| 444 | skip_f32.add(name) |
| 445 | |
| 446 | total_tensors = len(list(self.reader.tensors)) |
| 447 | processed = 0 |
| 448 | for t in self.reader.tensors: |
| 449 | name = t.name |
| 450 | qtype = QT(t.tensor_type).value |
| 451 | self.weight_qtypes[name] = qtype |
| 452 | processed += 1 |
| 453 | if processed % 100 == 0: |
| 454 | print(f" Loading tensors: {processed}/{total_tensors}...", flush=True) |
| 455 | |
| 456 | if len(t.shape) == 2: |
| 457 | in_dim, out_dim = int(t.shape[0]), int(t.shape[1]) |
| 458 | |
| 459 | if name in skip_f32 and qtype in C_KERNEL_TYPES: |
| 460 | # Raw quantized only — use C kernel (no copy — mmap view for multiprocessing sharing) |
| 461 | raw = np.ascontiguousarray(t.data.reshape(-1), dtype=np.uint8) |
| 462 | self.raw_weights[name] = raw |
| 463 | self.weight_info[name] = (out_dim, in_dim, BLOCK_SIZES.get(qtype, 0), qtype) |
| 464 | else: |
| 465 | # Dequantize to F32 |
| 466 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) |
| 467 | f32 = f32.reshape(out_dim, in_dim) |
| 468 | self.weights[name] = np.ascontiguousarray(f32) |
| 469 | if qtype in C_KERNEL_TYPES: |
| 470 | raw = np.ascontiguousarray(t.data.reshape(-1), dtype=np.uint8) |
| 471 | self.raw_weights[name] = raw |
| 472 | self.weight_info[name] = (out_dim, in_dim, BLOCK_SIZES.get(qtype, 0), qtype) |
| 473 | |
| 474 | elif len(t.shape) == 3: |
| 475 | # MoE 3D: store raw quantized only (no F32 dequant) |
| 476 | in_dim, out_dim, n_exp = int(t.shape[0]), int(t.shape[1]), int(t.shape[2]) |
| 477 | if qtype in C_KERNEL_TYPES: |
| 478 | raw = np.ascontiguousarray(t.data.reshape(-1), dtype=np.uint8) |
| 479 | self.raw_weights[name] = raw |
| 480 | self.weight_info[name] = (out_dim, in_dim, BLOCK_SIZES.get(qtype, 0), qtype, n_exp) |
| 481 | else: |
| 482 | # Unsupported quant — dequant to F32 |
| 483 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) |
| 484 | f32 = f32.reshape(n_exp, out_dim, in_dim) |
| 485 | self.weights[name] = np.ascontiguousarray(f32) |
| 486 | |
| 487 | elif len(t.shape) == 1: |
| 488 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32).reshape(-1) |
| 489 | self.weights[name] = np.ascontiguousarray(f32) |
| 490 | |
| 491 | # Token embedding: must dequantize for lookup |
| 492 | print(f" Loading token embedding...", flush=True) |
| 493 | for t in self.reader.tensors: |
| 494 | if t.name in ('token_embd.weight', 'model.embed_tokens.weight'): |
| 495 | qtype = QT(t.tensor_type).value |
| 496 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) |
| 497 | if len(t.shape) == 2: |
| 498 | in_dim, out_dim = int(t.shape[0]), int(t.shape[1]) |
| 499 | f32 = f32.reshape(out_dim, in_dim) if f32.shape[0] == in_dim else f32 |
| 500 | if f32.shape[1] != self.n_embd: |
| 501 | f32 = np.ascontiguousarray(f32.T) |
| 502 | self.weights['token_embd.weight'] = np.ascontiguousarray(f32) |
| 503 | self.vocab_size = f32.shape[0] |
| 504 | self.emb = self.weights['token_embd.weight'] |
| 505 | break |
| 506 | |
| 507 | # Output weight |
| 508 | self.out_w_name = 'output.weight' if 'output.weight' in self.raw_weights or 'output.weight' in self.weights else 'token_embd.weight' if 'token_embd.weight' in self.raw_weights or 'token_embd.weight' in self.weights else 'model.embed_tokens.weight' |
| 509 | out_info = self.weight_info.get(self.out_w_name) |
| 510 | if out_info is not None and self._kern is not None and self.arch_name != 'zaya': |
| 511 | # Skip requantization for arch-specific forward passes that use np.dot |
| 512 | self._out_nr = ctypes.c_int(out_info[0]) |
| 513 | self._out_nc = ctypes.c_int(out_info[1]) |
| 514 | self._out_qt_orig = ctypes.c_int(out_info[3]) |
| 515 | if out_info[3] in (12, 14, 13): # K-quants → requantize to Q8_0 |
| 516 | print(f" Converting output: {QTYPE_NAMES.get(out_info[3], out_info[3])} → Q8_0...", flush=True) |
| 517 | self._out_raw = self._requantize_output(self.raw_weights[self.out_w_name], out_info) |
| 518 | self._out_qt = ctypes.c_int(8) |
| 519 | elif out_info[3] == 1: # F16 → requantize to Q8_0 |
| 520 | print(f" Converting output: F16 → Q8_0 for C matmul...", flush=True) |
| 521 | self._out_raw = self._requantize_output(self.raw_weights[self.out_w_name], out_info) |
| 522 | self._out_qt = ctypes.c_int(8) |
| 523 | else: |
| 524 | self._out_raw = self.raw_weights[self.out_w_name].ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 525 | self._out_qt = out_info[3] |
| 526 | self._out_use_c = True |
| 527 | else: |
| 528 | self._out_f32 = self.weights[self.out_w_name] |
| 529 | self._out_use_c = False |
| 530 | |
| 531 | self._out_norm_w = self.weights.get('output_norm.weight') |
| 532 | if self._out_norm_w is None and 'model.final_norm.weight' in self.weights: |
| 533 | self._out_norm_w = self.weights['model.final_norm.weight'] |
| 534 | self.weights['output_norm.weight'] = self._out_norm_w |
| 535 | |
| 536 | # ZAYA MXFP4 naming adapter |
| 537 | if self.arch_name == 'zaya' and 'model.layers.0.input_norm.weight' in self.weights: |
| 538 | print(" MXFP4 full naming adapter...", flush=True) |
| 539 | import re as _re |
| 540 | n_layer = self.n_layers |
| 541 | n_exp = self.n_experts |
| 542 | |
| 543 | # Helper to create weight/raw aliases |
| 544 | def _alias(src, dst): |
| 545 | if src in self.weights and dst not in self.weights: |
| 546 | self.weights[dst] = self.weights[src] |
| 547 | if src in self.raw_weights and dst not in self.raw_weights: |
| 548 | self.raw_weights[dst] = self.raw_weights[src] |
| 549 | if src in self.weight_info: |
| 550 | self.weight_info[dst] = self.weight_info[src] |
| 551 | |
| 552 | # Global tensors |
| 553 | _alias('model.embed_tokens.weight', 'token_embd.weight') |
| 554 | _alias('model.final_norm.weight', 'output_norm.weight') |
| 555 | for sn in ['hidden_states_scale','hidden_states_bias','residual_scale','residual_bias']: |
| 556 | src = f'model.res_scale.{sn}' |
| 557 | if src in self.weights: |
| 558 | d32 = self.weights[src].ravel() |
| 559 | if np.any(np.abs(d32) > 1e6) or np.any(d32 < -1): |
| 560 | continue |
| 561 | pref = 'res_scale_hs' if 'hidden' in sn else 'res_scale_res' |
| 562 | suff = 'weight' if 'scale' in sn else 'bias' |
| 563 | self.weights[f'{pref}.{suff}'] = d32 |
| 564 | |
| 565 | # Per-layer |
| 566 | for l in range(n_layer): |
| 567 | ps, pd = f'model.layers.{l}', f'blk.{l}' |
| 568 | even = l % 2 == 0 |
| 569 | # input_norm → attn_norm |
| 570 | _alias(f'{ps}.input_norm.weight', f'{pd}.attn_norm.weight') |
| 571 | |
| 572 | if even: |
| 573 | for s, d in [('self_attn.qkv.linear_q','attn_q'),('self_attn.qkv.linear_k','attn_k'), |
| 574 | ('self_attn.o_proj','attn_output')]: |
| 575 | _alias(f'{ps}.{s}.weight', f'{pd}.{d}.weight') |
| 576 | for i in [1,2]: |
| 577 | _alias(f'{ps}.self_attn.qkv.val_proj{i}.weight', f'{pd}.cca_val_proj{i}.weight') |
| 578 | for sf in ['weight','bias']: |
| 579 | _alias(f'{ps}.self_attn.qkv.conv_qk.0.{sf}', f'{pd}.ssm_conv1d.{sf}') |
| 580 | # Res scales — skip broken MXFP4 [N,1] dequant, use defaults |
| 581 | else: |
| 582 | rmap = [ |
| 583 | ('zaya_block.router.rmsnorm_eda.weight','ffn_norm.weight'), |
| 584 | ('zaya_block.router.down_proj.weight','ffn_gate_inp.weight'), |
| 585 | ('zaya_block.router.down_proj.bias','ffn_gate_inp.bias'), |
| 586 | ('zaya_block.router.router_mlp.0.weight','ffn_gate.weight'), |
| 587 | ('zaya_block.router.router_mlp.0.bias','ffn_gate.bias'), |
| 588 | ('zaya_block.router.router_mlp.2.weight','zaya_router_mlp2.weight'), |
| 589 | ('zaya_block.router.router_mlp.2.bias','zaya_router_mlp2.bias'), |
| 590 | ('zaya_block.router.router_mlp.4.weight','zaya_router_mlp4.weight'), |
| 591 | ] |
| 592 | for s, d in rmap: |
| 593 | _alias(f'{ps}.{s}', f'{pd}.{d}') |
| 594 | # balancing_biases → zaya_router_biases |
| 595 | src = f'{ps}.zaya_block.router.balancing_biases' |
| 596 | dst = f'{pd}.zaya_router_biases.weight' |
| 597 | if src in self.weights and dst not in self.weights: |
| 598 | w = self.weights[src] |
| 599 | self.weights[dst] = w.ravel()[:17] if w.ndim > 1 else w[:17] |
| 600 | # Res scales |
| 601 | for sn in ['hidden_states_scale','hidden_states_bias','residual_scale','residual_bias']: |
| 602 | src = f'{ps}.res_scale.{sn}' |
| 603 | if src in self.weights: |
| 604 | d32 = self.weights[src].ravel() |
| 605 | # Filter: skip broken MXFP4 [N,1] dequant (>1e6 or < -1) |
| 606 | if np.any(np.abs(d32) > 1e6) or np.any(d32 < -1): |
| 607 | continue |
| 608 | pref = 'res_scale_hs' if 'hidden' in sn else 'res_scale_res' |
| 609 | self.weights[f'{pd}.{pref}.{"weight" if "scale" in sn else "bias"}'] = d32 |
| 610 | # Per-expert weights |
| 611 | for e in range(n_exp): |
| 612 | for src_w, dst_w in [('linear_fc1','ffn_gate_up_exps'),('linear_fc2','ffn_down_exps')]: |
| 613 | _alias(f'{ps}.zaya_block.experts.local_experts.{e}.{src_w}.weight', |
| 614 | f'{pd}.{dst_w}.{e}.weight') |
| 615 | print(f" Alias map: {n_layer}L x {n_exp}E", flush=True) |
| 616 | |
| 617 | if self._arch_forward is not None: |
| 618 | self._arch_forward.init_weights(self.weights, self.raw_weights, self.weight_info, self.weight_qtypes) |
| 619 | |
| 620 | def _requantize_output(self, raw_weights, out_info): |
| 621 | """Requantize output from K-quant to Q8_0 for faster logits projection.""" |
| 622 | n_rows, n_cols = out_info[0], out_info[1] |
| 623 | orig_qt = out_info[3] |
| 624 | |
| 625 | f32 = np.zeros((n_rows, n_cols), dtype=np.float32) |
| 626 | |
| 627 | if orig_qt == 14: # Q6_K |
| 628 | n_blk = n_cols // 256 |
| 629 | raw_ptr = raw_weights.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 630 | for r in range(n_rows): |
| 631 | off = r * n_blk * 210 |
| 632 | ptr = ctypes.cast(ctypes.addressof(raw_ptr.contents) + off, ctypes.POINTER(ctypes.c_uint8)) |
| 633 | self._kern.q6_k_dequantize_row( |
| 634 | ptr, f32[r].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), ctypes.c_int(n_cols)) |
| 635 | elif orig_qt == 12: # Q4_K |
| 636 | n_blk = n_cols // 256 |
| 637 | raw_ptr = raw_weights.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 638 | for r in range(n_rows): |
| 639 | off = r * n_blk * 144 |
| 640 | ptr = ctypes.cast(ctypes.addressof(raw_ptr.contents) + off, ctypes.POINTER(ctypes.c_uint8)) |
| 641 | self._kern.q4_k_dequantize_row( |
| 642 | ptr, f32[r].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), ctypes.c_int(n_cols)) |
| 643 | elif orig_qt == 1: # F16 — view as float16 then convert to float32 |
| 644 | raw_u16 = np.frombuffer(raw_weights[:n_rows*n_cols*2], dtype=np.uint16).copy().reshape(n_rows, n_cols) |
| 645 | f32 = raw_u16.astype(np.float32).view(np.float32) |
| 646 | else: |
| 647 | raise NotImplementedError(f"Requantize from type {orig_qt}") |
| 648 | |
| 649 | # Quantize to Q8_0 (34 bytes per 32 values) |
| 650 | n_blocks = n_cols // 32 |
| 651 | blocks = f32.reshape(n_rows, n_blocks, 32) |
| 652 | amax = np.max(np.abs(blocks), axis=2, keepdims=True) |
| 653 | amax = np.clip(amax, 1e-10, None) |
| 654 | d = amax / 127.0 |
| 655 | qs = np.clip(np.round(blocks / d), -127, 127).astype(np.int8) |
| 656 | d_f16 = d[:, :, 0].astype(np.float16) |
| 657 | d_u16 = d_f16.view(np.uint16) |
| 658 | |
| 659 | q8 = np.zeros((n_rows, n_blocks, 34), dtype=np.uint8) |
| 660 | q8[:, :, 0] = d_u16 & 0xFF |
| 661 | q8[:, :, 1] = (d_u16 >> 8) & 0xFF |
| 662 | q8[:, :, 2:] = qs.view(np.uint8) |
| 663 | |
| 664 | q8_flat = q8.reshape(n_rows * n_blocks * 34) |
| 665 | self._out_q8_buf = np.ascontiguousarray(q8_flat, dtype=np.uint8) |
| 666 | return self._out_q8_buf.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 667 | |
| 668 | def _compute_expert_raw_offsets(self, raw_bytes, n_experts, out_dim, in_dim, block_sz, block_vals): |
| 669 | """Compute byte offsets into raw weight array for each expert.""" |
| 670 | n_blocks_per_row = (in_dim + block_vals - 1) // block_vals |
| 671 | row_bytes = n_blocks_per_row * block_sz |
| 672 | expert_bytes = out_dim * row_bytes |
| 673 | raw_ptr_type = ctypes.POINTER(ctypes.c_uint8) |
| 674 | |
| 675 | if isinstance(raw_bytes, np.ndarray): |
| 676 | base_ptr = raw_bytes.ctypes.data_as(raw_ptr_type) |
| 677 | else: |
| 678 | base_ptr = raw_bytes |
| 679 | |
| 680 | offsets = [] |
| 681 | for e in range(n_experts): |
| 682 | off = e * expert_bytes |
| 683 | ptr = ctypes.cast(ctypes.addressof(base_ptr.contents) + off, raw_ptr_type) |
| 684 | offsets.append(ptr) |
| 685 | return offsets |
| 686 | |
| 687 | def _preload_pointers(self): |
| 688 | """Pre-compute ALL weight pointers — zero dict lookups in forward pass.""" |
| 689 | cf = ctypes.POINTER(ctypes.c_float) |
| 690 | cu = ctypes.POINTER(ctypes.c_uint8) |
| 691 | |
| 692 | self._layers = [] |
| 693 | self._moe_layers = [] if self.is_moe else None |
| 694 | |
| 695 | for i in range(self.n_layers): |
| 696 | lw = LayerWeights() |
| 697 | pfx = f'blk.{i}' |
| 698 | |
| 699 | # Architecture-specific pointer setup |
| 700 | if self._arch_forward is not None: |
| 701 | self._arch_forward.init_pointers(i, pfx, lw) |
| 702 | |
| 703 | # Dense projection weights |
| 704 | proj_names = { |
| 705 | 'attn_q': 'attn_q', 'attn_k': 'attn_k', 'attn_v': 'attn_v', |
| 706 | 'attn_out': 'attn_output', |
| 707 | 'ffn_gate': 'ffn_gate', 'ffn_up': 'ffn_up', 'ffn_down': 'ffn_down', |
| 708 | } |
| 709 | for attr, wname_suffix in proj_names.items(): |
| 710 | name = f'{pfx}.{wname_suffix}.weight' |
| 711 | info = self.weight_info.get(name) |
| 712 | if info is not None: |
| 713 | raw = self.raw_weights[name] |
| 714 | setattr(lw, f'{attr}_raw', raw.ctypes.data_as(cu)) |
| 715 | setattr(lw, f'{attr}_nr', ctypes.c_int(info[0])) |
| 716 | setattr(lw, f'{attr}_nc', ctypes.c_int(info[1])) |
| 717 | setattr(lw, f'{attr}_qt', ctypes.c_int(info[3])) |
| 718 | setattr(lw, f'{attr}_use_c', True) |
| 719 | else: |
| 720 | if name not in self.weights: |
| 721 | for t in self.reader.tensors: |
| 722 | if t.name == name: |
| 723 | f32 = gguf.dequantize(t.data, t.tensor_type).astype(np.float32) |
| 724 | if len(t.shape) == 2: |
| 725 | f32 = f32.reshape(int(t.shape[1]), int(t.shape[0])) |
| 726 | self.weights[name] = np.ascontiguousarray(f32) |
| 727 | break |
| 728 | setattr(lw, f'{attr}_f32', self.weights.get(name)) |
| 729 | setattr(lw, f'{attr}_use_c', False) |
| 730 | |
| 731 | lw.attn_norm_w = self.weights[f'{pfx}.attn_norm.weight'] |
| 732 | # GPT-OSS and some other architectures call this post_attention_norm |
| 733 | if f'{pfx}.ffn_norm.weight' in self.weights: |
| 734 | lw.ffn_norm_w = self.weights[f'{pfx}.ffn_norm.weight'] |
| 735 | elif f'{pfx}.post_attention_norm.weight' in self.weights: |
| 736 | lw.ffn_norm_w = self.weights[f'{pfx}.post_attention_norm.weight'] |
| 737 | elif self._arch_forward is not None: |
| 738 | lw.ffn_norm_w = None |
| 739 | else: |
| 740 | raise KeyError(f'No FFN norm weight found for layer {i}') |
| 741 | |
| 742 | # Build fused Q+K weight if Q and K have same quant type |
| 743 | if (lw.attn_q_use_c and lw.attn_k_use_c and |
| 744 | lw.attn_q_qt.value == lw.attn_k_qt.value): |
| 745 | q_name = f'{pfx}.attn_q.weight' |
| 746 | k_name = f'{pfx}.attn_k.weight' |
| 747 | q_raw_arr = self.raw_weights.get(q_name) |
| 748 | k_raw_arr = self.raw_weights.get(k_name) |
| 749 | if q_raw_arr is not None and k_raw_arr is not None: |
| 750 | qk_raw_arr = np.concatenate([q_raw_arr, k_raw_arr]) |
| 751 | qk_raw_arr = np.ascontiguousarray(qk_raw_arr, dtype=np.uint8) |
| 752 | # Keep the fused buffer alive on the layer object |
| 753 | lw._attn_qk_raw_buf = qk_raw_arr |
| 754 | lw.attn_qk_raw = qk_raw_arr.ctypes.data_as(cu) |
| 755 | lw.attn_qk_nr = ctypes.c_int(lw.attn_q_nr.value + lw.attn_k_nr.value) |
| 756 | lw.attn_qk_nc = lw.attn_q_nc # same n_cols as Q |
| 757 | lw.attn_qk_qt = lw.attn_q_qt # same quant type as Q |
| 758 | lw.attn_qk_use_c = True |
| 759 | lw.has_q_norm = f'{pfx}.attn_q_norm.weight' in self.weights |
| 760 | lw.has_k_norm = f'{pfx}.attn_k_norm.weight' in self.weights |
| 761 | if lw.has_q_norm: |
| 762 | lw.q_norm_w = self.weights[f'{pfx}.attn_q_norm.weight'] |
| 763 | if lw.has_k_norm: |
| 764 | lw.k_norm_w = self.weights[f'{pfx}.attn_k_norm.weight'] |
| 765 | self._layers.append(lw) |
| 766 | |
| 767 | # ── Qwen3.6 hybrid SSM+attention: load additional tensors ── |
| 768 | if self.arch_prefix == 'qwen35moe': |
| 769 | # attn_qkv.weight [2048, 8192] Q8_0 |
| 770 | qkv_name = f'{pfx}.attn_qkv.weight' |
| 771 | qkv_info = self.weight_info.get(qkv_name) |
| 772 | if qkv_info is not None: |
| 773 | lw.attn_qkv_raw = self.raw_weights[qkv_name].ctypes.data_as(cu) |
| 774 | lw.attn_qkv_nr = ctypes.c_int(qkv_info[0]) # 8192 |
| 775 | lw.attn_qkv_nc = ctypes.c_int(qkv_info[1]) # 2048 |
| 776 | lw.attn_qkv_qt = ctypes.c_int(qkv_info[3]) |
| 777 | lw.attn_qkv_use_c = True |
| 778 | else: |
| 779 | lw.attn_qkv_use_c = False |
| 780 | lw.attn_qkv_raw = None |
| 781 | |
| 782 | # attn_gate.weight [2048, 4096] Q8_0 — N→inner projection |
| 783 | gate_name = f'{pfx}.attn_gate.weight' |
| 784 | gate_info = self.weight_info.get(gate_name) |
| 785 | if gate_info is not None: |
| 786 | lw.attn_gate_raw = self.raw_weights[gate_name].ctypes.data_as(cu) |
| 787 | lw.attn_gate_nr = ctypes.c_int(gate_info[0]) # 4096 = inner |
| 788 | lw.attn_gate_nc = ctypes.c_int(gate_info[1]) # 2048 = N |
| 789 | lw.attn_gate_qt = ctypes.c_int(gate_info[3]) |
| 790 | lw.attn_gate_use_c = True |
| 791 | else: |
| 792 | lw.attn_gate_use_c = False |
| 793 | |
| 794 | # SSM F32 tensors (store pointers to numpy arrays) |
| 795 | for ssm_attr, ssm_wname in [ |
| 796 | ('ssm_conv1d_ptr', 'ssm_conv1d.weight'), |
| 797 | ('ssm_a_ptr', 'ssm_a'), |
| 798 | ('ssm_dt_bias_ptr', 'ssm_dt.bias'), |
| 799 | ('ssm_alpha_ptr', 'ssm_alpha.weight'), |
| 800 | ('ssm_beta_ptr', 'ssm_beta.weight'), |
| 801 | ('ssm_norm_ptr', 'ssm_norm.weight'), |
| 802 | ]: |
| 803 | name = f'{pfx}.{ssm_wname}' |
| 804 | w = self.weights.get(name) |
| 805 | if w is not None: |
| 806 | setattr(lw, ssm_attr, w.ctypes.data_as(cf)) |
| 807 | else: |
| 808 | setattr(lw, ssm_attr, None) |
| 809 | |
| 810 | # ssm_out.weight [4096, 2048] Q8_0 — inner→N projection |
| 811 | ssm_out_name = f'{pfx}.ssm_out.weight' |
| 812 | ssm_out_info = self.weight_info.get(ssm_out_name) |
| 813 | if ssm_out_info is not None: |
| 814 | lw.ssm_out_raw = self.raw_weights[ssm_out_name].ctypes.data_as(cu) |
| 815 | lw.ssm_out_nr = ctypes.c_int(ssm_out_info[0]) # 2048 = N |
| 816 | lw.ssm_out_nc = ctypes.c_int(ssm_out_info[1]) # 4096 = inner |
| 817 | lw.ssm_out_qt = ctypes.c_int(ssm_out_info[3]) |
| 818 | lw.ssm_out_use_c = True |
| 819 | else: |
| 820 | lw.ssm_out_use_c = False |
| 821 | |
| 822 | # Shared expert weights |
| 823 | shexp_names = [ |
| 824 | ('shexp_gate', 'ffn_gate_shexp.weight', 512, 2048), |
| 825 | ('shexp_up', 'ffn_up_shexp.weight', 512, 2048), |
| 826 | ('shexp_down', 'ffn_down_shexp.weight', 2048, 512), |
| 827 | ] |
| 828 | for attr, wname, nr, nc_val in shexp_names: |
| 829 | name = f'{pfx}.{wname}' |
| 830 | info = self.weight_info.get(name) |
| 831 | if info is not None: |
| 832 | setattr(lw, f'{attr}_raw', self.raw_weights[name].ctypes.data_as(cu)) |
| 833 | setattr(lw, f'{attr}_nr', ctypes.c_int(info[0])) |
| 834 | setattr(lw, f'{attr}_nc', ctypes.c_int(info[1])) |
| 835 | setattr(lw, f'{attr}_qt', ctypes.c_int(info[3])) |
| 836 | setattr(lw, f'{attr}_use_c', True) |
| 837 | else: |
| 838 | setattr(lw, f'{attr}_use_c', False) |
| 839 | setattr(lw, f'{attr}_raw', None) |
| 840 | |
| 841 | # Shared expert router (1D F32 vector [2048]) |
| 842 | router_name = f'{pfx}.ffn_gate_inp_shexp.weight' |
| 843 | router_w = self.weights.get(router_name) |
| 844 | if router_w is not None: |
| 845 | lw.shexp_router_ptr = router_w.ctypes.data_as(cf) |
| 846 | lw.shexp_router_nr = ctypes.c_int(router_w.shape[0]) # 2048 |
| 847 | else: |
| 848 | lw.shexp_router_ptr = None |
| 849 | |
| 850 | # ── MoE pointers ── |
| 851 | if self.is_moe: |
| 852 | me = MoEExpertPointers() |
| 853 | me.n_experts = self.n_experts |
| 854 | me.n_ff_expert = self.n_ff_expert |
| 855 | me.n_embd = self.n_embd |
| 856 | |
| 857 | # Router (2D) |
| 858 | router_name = f'{pfx}.ffn_gate_inp.weight' |
| 859 | router_info = self.weight_info.get(router_name) |
| 860 | if router_info is not None: |
| 861 | me.router_raw = self.raw_weights[router_name].ctypes.data_as(cu) |
| 862 | me.router_nr = ctypes.c_int(router_info[0]) |
| 863 | me.router_nc = ctypes.c_int(router_info[1]) |
| 864 | me.router_qt = ctypes.c_int(router_info[3]) |
| 865 | else: |
| 866 | me.router_f32 = self.weights.get(router_name) |
| 867 | |
| 868 | # Expert gate/up/down - 3D tensors, store per-expert numpy slices |
| 869 | for attr, wname in [('gate', 'ffn_gate_exps'), ('up', 'ffn_up_exps'), ('down', 'ffn_down_exps')]: |
| 870 | name = f'{pfx}.{wname}.weight' |
| 871 | info = self.weight_info.get(name) |
| 872 | raw = self.raw_weights.get(name) |
| 873 | if info is not None and raw is not None: |
| 874 | out_dim, in_dim, bs, qt, n_exp = info |
| 875 | bv = BLOCK_VALS[qt] |
| 876 | n_blocks_per_row = (in_dim + bv - 1) // bv |
| 877 | row_bytes = n_blocks_per_row * bs |
| 878 | expert_bytes = out_dim * row_bytes |
| 879 | |
| 880 | # Store numpy views for each expert (zero copy slicing) |
| 881 | expert_views = [] |
| 882 | for e in range(n_exp): |
| 883 | start = e * expert_bytes |
| 884 | end = (e + 1) * expert_bytes |
| 885 | ev = raw[start:end] |
| 886 | expert_views.append(ev) # numpy ndarray view |
| 887 | |
| 888 | # Pre-compute ctypes pointers for fused MoE kernel |
| 889 | raw_ptr = raw.ctypes.data_as(cu) |
| 890 | expert_ptrs = [ |
| 891 | ctypes.cast(ctypes.addressof(raw_ptr.contents) + e * expert_bytes, cu) |
| 892 | for e in range(n_exp) |
| 893 | ] |
| 894 | |
| 895 | # Pre-build ctypes array for zero-cost dispatch |
| 896 | cu_arr_full = ctypes.POINTER(ctypes.c_uint8) * n_exp |
| 897 | expert_ptrs_arr = cu_arr_full(*expert_ptrs) |
| 898 | |
| 899 | setattr(me, f'{attr}_raw', expert_views) |
| 900 | setattr(me, f'{attr}_ptrs', expert_ptrs) |
| 901 | setattr(me, f'{attr}_ptrs_arr', expert_ptrs_arr) |
| 902 | setattr(me, f'{attr}_nr', ctypes.c_int(out_dim)) |
| 903 | setattr(me, f'{attr}_nc', ctypes.c_int(in_dim)) |
| 904 | setattr(me, f'{attr}_qt', ctypes.c_int(qt)) |
| 905 | setattr(me, f'{attr}_use_c', True) |
| 906 | else: |
| 907 | setattr(me, f'{attr}_use_c', False) |
| 908 | setattr(me, f'{attr}_nr', ctypes.c_int(0)) |
| 909 | setattr(me, f'{attr}_nc', ctypes.c_int(0)) |
| 910 | setattr(me, f'{attr}_qt', ctypes.c_int(0)) |
| 911 | |
| 912 | self._moe_layers.append(me) |
| 913 | |
| 914 | def _init_buffers(self): |
| 915 | """Pre-allocate ALL buffers — zero allocation in forward pass.""" |
| 916 | N = self.n_embd |
| 917 | NK = self.n_head * self.head_dim |
| 918 | NKH = self.n_kv_head * self.head_dim |
| 919 | MAX_POS = 4096 |
| 920 | FF_expert = self.n_ff_expert if self.is_moe else self.n_ff |
| 921 | |
| 922 | # KV cache |
| 923 | self.kv_k = np.zeros((self.n_layers, MAX_POS, NKH), dtype=np.float32) |
| 924 | self.kv_v = np.zeros((self.n_layers, MAX_POS, NKH), dtype=np.float32) |
| 925 | self.kv_len = np.zeros(self.n_layers, dtype=np.int32) |
| 926 | |
| 927 | self._x = np.zeros(N, dtype=np.float32) |
| 928 | self._x_norm = np.zeros(N, dtype=np.float32) |
| 929 | self._residual = np.zeros(N, dtype=np.float32) |
| 930 | # Fused Q+K buffer: _q = _qk[:NK], _k = _qk[NK:] for fused QK matmul |
| 931 | # For Qwen3.6 with attn_qkv (8192 dims), allocate extra space |
| 932 | # +8 pad: q8_0_matmul_omp's vectorized loop writes 1 element past the view end. |
| 933 | # The views stay original size; the padding is in the backing allocation only. |
| 934 | qkv_sz = max(NK + NKH + 8, 8192) if hasattr(self, 'arch_prefix') and self.arch_prefix == 'qwen35moe' else NK + NKH + 8 |
| 935 | self._qk = np.zeros(qkv_sz, dtype=np.float32) |
| 936 | self._q = self._qk[:NK] |
| 937 | self._k = self._qk[NK:NK+NKH] |
| 938 | self._v = np.zeros(NKH, dtype=np.float32) |
| 939 | self._att_out = np.zeros(NK, dtype=np.float32) |
| 940 | self._o_proj = np.zeros(N + 8, dtype=np.float32) |
| 941 | self._gate = np.zeros(self.n_ff, dtype=np.float32) |
| 942 | self._up = np.zeros(self.n_ff, dtype=np.float32) |
| 943 | self._silu_gate = np.zeros(self.n_ff, dtype=np.float32) |
| 944 | self._ffn_out = np.zeros(N + 8, dtype=np.float32) |
| 945 | |
| 946 | # MoE buffers |
| 947 | self._moe_router_scores = np.zeros(max(128, self.n_experts), dtype=np.float32) |
| 948 | self._moe_gate_out = np.zeros(FF_expert, dtype=np.float32) |
| 949 | self._moe_up_out = np.zeros(FF_expert, dtype=np.float32) |
| 950 | self._moe_silu_out = np.zeros(FF_expert, dtype=np.float32) |
| 951 | self._moe_expert_out = np.zeros(N, dtype=np.float32) |
| 952 | self._moe_combined = np.zeros(N, dtype=np.float32) |
| 953 | |
| 954 | # Pre-allocated buffers for C moe_forward_omp (no malloc/calloc in hot path) |
| 955 | max_top_k = max(8, self.n_experts_per_tok) |
| 956 | buf_sz = 3 * max_top_k * FF_expert |
| 957 | self._moe_prealloc_buf = np.zeros(buf_sz, dtype=np.float32) |
| 958 | n_blocks_x = N // 32 |
| 959 | # Buffers for Q8_0 activation on MoE down path: top_k experts × n_ff_expert blocks |
| 960 | self._moe_prealloc_q8 = np.zeros(self.n_experts_per_tok * FF_expert * 34 // 32, dtype=np.uint8) |
| 961 | |
| 962 | # GQA attention workspace: n_head * max_seq_len floats for scores |
| 963 | self._gqa_ws_size = self.n_head * 4096 |
| 964 | self._gqa_workspace = np.zeros(self._gqa_ws_size, dtype=np.float32) |
| 965 | |
| 966 | self._logits = np.zeros(self.vocab_size, dtype=np.float32) |
| 967 | |
| 968 | # SSM state buffer for Qwen3.6 hybrid model |
| 969 | if self.arch_prefix == 'qwen35moe': |
| 970 | n_layers = self.n_layers |
| 971 | groups = self.ssm_groups |
| 972 | state_size = self.ssm_state_size |
| 973 | self._ssm_state = np.zeros((n_layers, groups, state_size), dtype=np.float32) |
| 974 | self._ssm_intermediate = np.zeros(self.ssm_inner, dtype=np.float32) |
| 975 | self._gate_4096 = np.zeros(self.ssm_inner, dtype=np.float32) |
| 976 | print(f" SSM state: {n_layers}x{groups}x{state_size} = {n_layers*groups*state_size*4/1024/1024:.1f} MB", flush=True) |
| 977 | else: |
| 978 | self._ssm_state = None |
| 979 | self._ssm_intermediate = None |
| 980 | self._gate_4096 = None |
| 981 | |
| 982 | # ctypes pointers |
| 983 | cf = ctypes.POINTER(ctypes.c_float) |
| 984 | self._p_x = self._x.ctypes.data_as(cf) |
| 985 | self._p_x_norm = self._x_norm.ctypes.data_as(cf) |
| 986 | self._p_residual = self._residual.ctypes.data_as(cf) |
| 987 | self._p_q = self._q.ctypes.data_as(cf) |
| 988 | self._p_k = self._k.ctypes.data_as(cf) |
| 989 | self._p_v = self._v.ctypes.data_as(cf) |
| 990 | self._p_qk = self._qk.ctypes.data_as(cf) # fused QK output |
| 991 | self._p_att_out = self._att_out.ctypes.data_as(cf) |
| 992 | self._p_gate = self._gate.ctypes.data_as(cf) |
| 993 | self._p_up = self._up.ctypes.data_as(cf) |
| 994 | self._p_silu_gate = self._silu_gate.ctypes.data_as(cf) |
| 995 | self._p_o_proj = self._o_proj.ctypes.data_as(cf) |
| 996 | self._p_ffn = self._ffn_out.ctypes.data_as(cf) |
| 997 | self._p_logits = self._logits.ctypes.data_as(cf) |
| 998 | self._p_moe_router = self._moe_router_scores.ctypes.data_as(cf) |
| 999 | self._p_moe_gate = self._moe_gate_out.ctypes.data_as(cf) |
| 1000 | self._p_moe_up = self._moe_up_out.ctypes.data_as(cf) |
| 1001 | self._p_moe_silu = self._moe_silu_out.ctypes.data_as(cf) |
| 1002 | self._p_moe_expert = self._moe_expert_out.ctypes.data_as(cf) |
| 1003 | self._p_moe_combined = self._moe_combined.ctypes.data_as(cf) |
| 1004 | self._p_gqa_ws = self._gqa_workspace.ctypes.data_as(cf) |
| 1005 | |
| 1006 | # RoPE tables |
| 1007 | HD = self.head_dim |
| 1008 | self._rope_cos_table = {} |
| 1009 | self._rope_sin_table = {} |
| 1010 | self._eps_f = ctypes.c_float(self.eps) |
| 1011 | self._gqa_rep = self.n_head // self.n_kv_head if self.n_head != self.n_kv_head else 1 |
| 1012 | |
| 1013 | if self._arch_forward is not None: |
| 1014 | self._arch_forward.init_buffers() |
| 1015 | |
| 1016 | def _init_c_batch_caches(self): |
| 1017 | """Pre-compute per-layer pointer/dimension arrays for forward_c_batch. |
| 1018 | |
| 1019 | Assembles L-length arrays of pointers/int32 values needed by batch forward. |
| 1020 | Works for qwen35moe (fused QKV + SSM) and gpt-oss (separate Q/K/V + MoE). |
| 1021 | """ |
| 1022 | # Check C function availability |
| 1023 | if not hasattr(self, '_kern') or self._kern is None: |
| 1024 | self._c_batch_ready = False |
| 1025 | return |
| 1026 | |
| 1027 | L = self.n_layers |
| 1028 | cf = ctypes.POINTER(ctypes.c_float) |
| 1029 | cu = ctypes.POINTER(ctypes.c_uint8) |
| 1030 | |
| 1031 | # ── Detect GPT-OSS architecture ── |
| 1032 | is_gptoss = hasattr(self, 'arch_name') and self.arch_name in ('gpt-oss', 'gptoss') |
| 1033 | |
| 1034 | if is_gptoss: |
| 1035 | if not hasattr(self._kern, 'gptoss_batch_forward'): |
| 1036 | self._c_batch_ready = False |
| 1037 | return |
| 1038 | |
| 1039 | # Check that Q/K/V/O have quantized C-compatible weights |
| 1040 | if (self.n_layers == 0 |
| 1041 | or not getattr(self._layers[0], 'attn_q_use_c', False) |
| 1042 | or not getattr(self._layers[0], 'attn_k_use_c', False) |
| 1043 | or not getattr(self._layers[0], 'attn_v_use_c', False)): |
| 1044 | self._c_batch_ready = False |
| 1045 | return |
| 1046 | |
| 1047 | # ── Per-layer float pointer arrays (L-length) ── |
| 1048 | arr_cf = cf * L |
| 1049 | arr_cu = cu * L |
| 1050 | |
| 1051 | # attn_norm_w / post_attn_norm_w (F32 norm vectors) |
| 1052 | self._c_gptoss_attn_norm_w = arr_cf() |
| 1053 | self._c_gptoss_post_attn_norm_w = arr_cf() |
| 1054 | for i, lw in enumerate(self._layers): |
| 1055 | self._c_gptoss_attn_norm_w[i] = lw.attn_norm_w.ctypes.data_as(cf) |
| 1056 | self._c_gptoss_post_attn_norm_w[i] = lw.ffn_norm_w.ctypes.data_as(cf) |
| 1057 | |
| 1058 | # ── Quantized weight pointer arrays (Q, K, V, O) ── |
| 1059 | def _make_ptr_arr(attr_prefix): |
| 1060 | ptr_arr = arr_cu() |
| 1061 | nr_arr = np.zeros(L, dtype=np.int32) |
| 1062 | nc_arr = np.zeros(L, dtype=np.int32) |
| 1063 | qt_arr = np.zeros(L, dtype=np.int32) |
| 1064 | for i, lw in enumerate(self._layers): |
| 1065 | ptr_arr[i] = getattr(lw, f'{attr_prefix}_raw', None) or ctypes.cast(0, cu) |
| 1066 | nr = getattr(lw, f'{attr_prefix}_nr', None) |
| 1067 | nc = getattr(lw, f'{attr_prefix}_nc', None) |
| 1068 | qt = getattr(lw, f'{attr_prefix}_qt', None) |
| 1069 | if nr is not None: nr_arr[i] = nr.value |
| 1070 | if nc is not None: nc_arr[i] = nc.value |
| 1071 | if qt is not None: qt_arr[i] = qt.value |
| 1072 | return ptr_arr, nr_arr, nc_arr, qt_arr |
| 1073 | |
| 1074 | (self._c_gptoss_wQ, self._c_gptoss_q_nr, |
| 1075 | self._c_gptoss_q_nc, self._c_gptoss_q_qt) = _make_ptr_arr('attn_q') |
| 1076 | (self._c_gptoss_wK, self._c_gptoss_k_nr, |
| 1077 | self._c_gptoss_k_nc, self._c_gptoss_k_qt) = _make_ptr_arr('attn_k') |
| 1078 | (self._c_gptoss_wV, self._c_gptoss_v_nr, |
| 1079 | self._c_gptoss_v_nc, self._c_gptoss_v_qt) = _make_ptr_arr('attn_v') |
| 1080 | (self._c_gptoss_wO, self._c_gptoss_o_nr, |
| 1081 | self._c_gptoss_o_nc, self._c_gptoss_o_qt) = _make_ptr_arr('attn_out') |
| 1082 | |
| 1083 | # ── MoE router (F32 per layer: [n_experts, N]) ── |
| 1084 | self._c_gptoss_w_gate_inp = arr_cf() |
| 1085 | for i, me in enumerate(self._moe_layers): |
| 1086 | if me.router_f32 is not None: |
| 1087 | self._c_gptoss_w_gate_inp[i] = me.router_f32.ctypes.data_as(cf) |
| 1088 | else: |
| 1089 | self._c_gptoss_w_gate_inp[i] = ctypes.cast(0, cf) |
| 1090 | |
| 1091 | # ── MoE expert weights ── |
| 1092 | def _make_moe_ptr_array(exp_name): |
| 1093 | ptr_arr = arr_cu() |
| 1094 | for i in range(L): |
| 1095 | me = self._moe_layers[i] |
| 1096 | raw_list = getattr(me, f'{exp_name}_raw', None) |
| 1097 | if raw_list is not None and len(raw_list) > 0: |
| 1098 | ptr_arr[i] = raw_list[0].ctypes.data_as(cu) |
| 1099 | else: |
| 1100 | ptr_arr[i] = ctypes.cast(0, cu) |
| 1101 | return ptr_arr |
| 1102 | |
| 1103 | def _make_moe_qt_array(exp_name, default_val=12): |
| 1104 | arr = np.zeros(L, dtype=np.int32) |
| 1105 | for i in range(L): |
| 1106 | me = self._moe_layers[i] |
| 1107 | qt = getattr(me, f'{exp_name}_qt', None) |
| 1108 | arr[i] = qt.value if qt is not None else default_val |
| 1109 | return arr |
| 1110 | |
| 1111 | self._c_gptoss_gate_exp_raw = _make_moe_ptr_array('gate') |
| 1112 | self._c_gptoss_up_exp_raw = _make_moe_ptr_array('up') |
| 1113 | self._c_gptoss_down_exp_raw = _make_moe_ptr_array('down') |
| 1114 | self._c_gptoss_gate_exp_qt = _make_moe_qt_array('gate', 12) |
| 1115 | self._c_gptoss_up_exp_qt = _make_moe_qt_array('up', 12) |
| 1116 | self._c_gptoss_down_exp_qt = _make_moe_qt_array('down', 14) |
| 1117 | |
| 1118 | # ── RoPE tables ── |
| 1119 | max_ctx = 4096 |
| 1120 | rope_dim = self.rope_dim if hasattr(self, 'rope_dim') and self.rope_dim > 0 else self.head_dim |
| 1121 | hd2 = rope_dim // 2 |
| 1122 | if hd2 > 0: |
| 1123 | cos_table = np.zeros(max_ctx * hd2, dtype=np.float32) |
| 1124 | sin_table = np.zeros(max_ctx * hd2, dtype=np.float32) |
| 1125 | inv_freq = 10000.0 ** (-np.arange(0, rope_dim, 2, dtype=np.float64) / rope_dim) |
| 1126 | for pos in range(max_ctx): |
| 1127 | theta = pos * inv_freq |
| 1128 | cos_table[pos * hd2:(pos + 1) * hd2] = np.cos(theta).astype(np.float32) |
| 1129 | sin_table[pos * hd2:(pos + 1) * hd2] = np.sin(theta).astype(np.float32) |
| 1130 | self._c_gptoss_cos_table = cos_table |
| 1131 | self._c_gptoss_sin_table = sin_table |
| 1132 | else: |
| 1133 | self._c_gptoss_cos_table = np.zeros(1, dtype=np.float32) |
| 1134 | self._c_gptoss_sin_table = np.zeros(1, dtype=np.float32) |
| 1135 | |
| 1136 | # ── Workspace S value ── |
| 1137 | N = self.n_embd |
| 1138 | NH = self.n_head |
| 1139 | HD = self.head_dim |
| 1140 | inner = NH * HD |
| 1141 | n_kv = self.n_kv_head * HD |
| 1142 | n_ff_expert = self.n_ff_expert if self.is_moe else self.n_ff |
| 1143 | S = max(N, inner, n_kv, n_ff_expert, 8192) |
| 1144 | self._c_gptoss_ws_S = S |
| 1145 | |
| 1146 | # ── q8 workspace ── |
| 1147 | q8_sz = self.n_experts_per_tok * n_ff_expert * 34 // 32 + 1024 |
| 1148 | self._c_gptoss_q8_ws = np.zeros(max(1, q8_sz), dtype=np.uint8) |
| 1149 | |
| 1150 | # ── Token array ── |
| 1151 | self._c_gptoss_tokens = np.zeros(64, dtype=np.int32) |
| 1152 | |
| 1153 | # ── Int array pointers ── |
| 1154 | pi = ctypes.POINTER(ctypes.c_int) |
| 1155 | self._c_gptoss_pi_type = pi |
| 1156 | self._c_gptoss_p_q_nr = self._c_gptoss_q_nr.ctypes.data_as(pi) |
| 1157 | self._c_gptoss_p_q_nc = self._c_gptoss_q_nc.ctypes.data_as(pi) |
| 1158 | self._c_gptoss_p_q_qt = self._c_gptoss_q_qt.ctypes.data_as(pi) |
| 1159 | self._c_gptoss_p_k_nr = self._c_gptoss_k_nr.ctypes.data_as(pi) |
| 1160 | self._c_gptoss_p_k_nc = self._c_gptoss_k_nc.ctypes.data_as(pi) |
| 1161 | self._c_gptoss_p_k_qt = self._c_gptoss_k_qt.ctypes.data_as(pi) |
| 1162 | self._c_gptoss_p_v_nr = self._c_gptoss_v_nr.ctypes.data_as(pi) |
| 1163 | self._c_gptoss_p_v_nc = self._c_gptoss_v_nc.ctypes.data_as(pi) |
| 1164 | self._c_gptoss_p_v_qt = self._c_gptoss_v_qt.ctypes.data_as(pi) |
| 1165 | self._c_gptoss_p_o_nr = self._c_gptoss_o_nr.ctypes.data_as(pi) |
| 1166 | self._c_gptoss_p_o_nc = self._c_gptoss_o_nc.ctypes.data_as(pi) |
| 1167 | self._c_gptoss_p_o_qt = self._c_gptoss_o_qt.ctypes.data_as(pi) |
| 1168 | self._c_gptoss_p_gate_exp_qt = self._c_gptoss_gate_exp_qt.ctypes.data_as(pi) |
| 1169 | self._c_gptoss_p_up_exp_qt = self._c_gptoss_up_exp_qt.ctypes.data_as(pi) |
| 1170 | self._c_gptoss_p_down_exp_qt = self._c_gptoss_down_exp_qt.ctypes.data_as(pi) |
| 1171 | |
| 1172 | # ── Store ctypes shorthand ── |
| 1173 | self._c_ci = ctypes.c_int |
| 1174 | self._c_cf = ctypes.c_float |
| 1175 | self._c_eps_val = ctypes.c_float(self.eps) |
| 1176 | |
| 1177 | self._c_batch_ready = True |
| 1178 | return |
| 1179 | |
| 1180 | # ── Detect ZAYA architecture ── |
| 1181 | is_zaya = hasattr(self, 'arch_name') and self.arch_name == 'zaya' |
| 1182 | |
| 1183 | if is_zaya: |
| 1184 | # ZAYA uses Python forward (17+ tok/s after MoE residual fix — exceeds 15 tok/s target). |
| 1185 | # zaya_batch_forward C function exists but has pre-existing compatibility issues. |
| 1186 | # Python forward is fast enough and produces correct output. |
| 1187 | self._c_batch_ready = False |
| 1188 | return |
| 1189 | |
| 1190 | # ── Original qwen35moe logic below ── |
| 1191 | |
| 1192 | # ── Original qwen35moe logic below ── |
| 1193 | if not hasattr(self._kern, 'qwen36_batch_forward'): |
| 1194 | self._c_batch_ready = False |
| 1195 | return |
| 1196 | |
| 1197 | # Check model has fused QKV weights (required by C function's attention path) |
| 1198 | if (self.n_layers == 0 |
| 1199 | or not getattr(self._layers[0], 'attn_qkv_use_c', False)): |
| 1200 | self._c_batch_ready = False |
| 1201 | return |
| 1202 | |
| 1203 | L = self.n_layers |
| 1204 | cf = ctypes.POINTER(ctypes.c_float) |
| 1205 | cu = ctypes.POINTER(ctypes.c_uint8) |
| 1206 | |
| 1207 | # ── Layer type flags ── |
| 1208 | self._c_layer_types = np.array(self.layer_types, dtype=np.int32) |
| 1209 | c_layer_types_ptr = self._c_layer_types.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 1210 | |
| 1211 | # ── Per-layer float pointer arrays (L-length) ── |
| 1212 | arr_cf = cf * L |
| 1213 | arr_cu = cu * L |
| 1214 | |
| 1215 | # attn_norm_w / ffn_norm_w (F32 norm vectors) |
| 1216 | self._c_attn_norm_w = arr_cf() |
| 1217 | self._c_ffn_norm_w = arr_cf() |
| 1218 | for i, lw in enumerate(self._layers): |
| 1219 | self._c_attn_norm_w[i] = lw.attn_norm_w.ctypes.data_as(cf) |
| 1220 | self._c_ffn_norm_w[i] = lw.ffn_norm_w.ctypes.data_as(cf) |
| 1221 | |
| 1222 | # quantized weight pointer arrays + dimension int arrays |
| 1223 | def _make_quant_pointers(attr_prefix, has_use_c=True): |
| 1224 | """Build uint8_t** pointer array and dim/quant int arrays.""" |
| 1225 | ptr_arr = arr_cu() |
| 1226 | nr_arr = np.zeros(L, dtype=np.int32) |
| 1227 | nc_arr = np.zeros(L, dtype=np.int32) |
| 1228 | qt_arr = np.zeros(L, dtype=np.int32) |
| 1229 | for i, lw in enumerate(self._layers): |
| 1230 | raw_attr = getattr(lw, f'{attr_prefix}_raw', None) |
| 1231 | use_attr = getattr(lw, f'{attr_prefix}_use_c', False) if has_use_c else True |
| 1232 | nr = getattr(lw, f'{attr_prefix}_nr', None) |
| 1233 | nc = getattr(lw, f'{attr_prefix}_nc', None) |
| 1234 | qt = getattr(lw, f'{attr_prefix}_qt', None) |
| 1235 | if raw_attr is not None and use_attr: |
| 1236 | ptr_arr[i] = raw_attr |
| 1237 | if nr is not None: nr_arr[i] = nr.value |
| 1238 | if nc is not None: nc_arr[i] = nc.value |
| 1239 | if qt is not None: qt_arr[i] = qt.value |
| 1240 | return ptr_arr, nr_arr, nc_arr, qt_arr |
| 1241 | |
| 1242 | # attn_qkv |
| 1243 | (self._c_attn_qkv_raw, |
| 1244 | self._c_qkv_nr, self._c_qkv_nc, self._c_qkv_qt) = _make_quant_pointers('attn_qkv') |
| 1245 | |
| 1246 | # attn_gate (SSM gate, N→inner) |
| 1247 | (self._c_attn_gate_raw, |
| 1248 | self._c_gate_nr, self._c_gate_nc, self._c_gate_qt) = _make_quant_pointers('attn_gate') |
| 1249 | |
| 1250 | # ssm_out (inner→N) |
| 1251 | (self._c_ssm_out_raw, |
| 1252 | self._c_ssm_out_nr, self._c_ssm_out_nc, self._c_ssm_out_qt) = _make_quant_pointers('ssm_out') |
| 1253 | |
| 1254 | # attn_out (standard attention output projection) |
| 1255 | (self._c_attn_out_raw, |
| 1256 | self._c_out_nr, self._c_out_nc, self._c_out_qt) = _make_quant_pointers('attn_out') |
| 1257 | |
| 1258 | # ── SSM per-layer F32 pointer arrays ── |
| 1259 | def _make_ssm_ptr_array(attr_name): |
| 1260 | """Build const float** array for SSM F32 parameters.""" |
| 1261 | ptr_arr = arr_cf() |
| 1262 | for i, lw in enumerate(self._layers): |
| 1263 | val = getattr(lw, attr_name, None) |
| 1264 | ptr_arr[i] = val if val is not None else ctypes.cast(0, cf) |
| 1265 | return ptr_arr |
| 1266 | |
| 1267 | self._c_ssm_conv1d = _make_ssm_ptr_array('ssm_conv1d_ptr') |
| 1268 | self._c_ssm_a = _make_ssm_ptr_array('ssm_a_ptr') |
| 1269 | self._c_ssm_dt_bias = _make_ssm_ptr_array('ssm_dt_bias_ptr') |
| 1270 | self._c_ssm_alpha = _make_ssm_ptr_array('ssm_alpha_ptr') |
| 1271 | self._c_ssm_beta = _make_ssm_ptr_array('ssm_beta_ptr') |
| 1272 | self._c_ssm_norm = _make_ssm_ptr_array('ssm_norm_ptr') |
| 1273 | |
| 1274 | # ── MoE expert weights (raw uint8_t**) ── |
| 1275 | def _make_moe_ptr_array(exp_name): |
| 1276 | """Build uint8_t** array for MoE expert weights. |
| 1277 | |
| 1278 | Each element points to the base of the flat raw uint8 buffer |
| 1279 | containing all experts' weights for that layer (concatenated). |
| 1280 | """ |
| 1281 | ptr_arr = arr_cu() |
| 1282 | for i in range(L): |
| 1283 | me = self._moe_layers[i] |
| 1284 | raw_list = getattr(me, f'{exp_name}_raw', None) |
| 1285 | if raw_list is not None and len(raw_list) > 0: |
| 1286 | # First expert view starts at offset 0 in the raw buffer |
| 1287 | ptr_arr[i] = raw_list[0].ctypes.data_as(cu) |
| 1288 | else: |
| 1289 | ptr_arr[i] = ctypes.cast(0, cu) |
| 1290 | return ptr_arr |
| 1291 | |
| 1292 | def _make_moe_qt_array(exp_name, default_val=12): |
| 1293 | """Build int array for MoE expert quant types.""" |
| 1294 | arr = np.zeros(L, dtype=np.int32) |
| 1295 | for i in range(L): |
| 1296 | me = self._moe_layers[i] |
| 1297 | qt = getattr(me, f'{exp_name}_qt', None) |
| 1298 | arr[i] = qt.value if qt is not None else default_val |
| 1299 | return arr |
| 1300 | |
| 1301 | self._c_gate_exp_raw = _make_moe_ptr_array('gate') |
| 1302 | self._c_up_exp_raw = _make_moe_ptr_array('up') |
| 1303 | self._c_down_exp_raw = _make_moe_ptr_array('down') |
| 1304 | self._c_gate_exp_qt = _make_moe_qt_array('gate', 12) |
| 1305 | self._c_up_exp_qt = _make_moe_qt_array('up', 12) |
| 1306 | self._c_down_exp_qt = _make_moe_qt_array('down', 14) |
| 1307 | |
| 1308 | # ── MoE router ── |
| 1309 | def _make_router_ptr_array(): |
| 1310 | """Build uint8_t** array for MoE router weights.""" |
| 1311 | ptr_arr = arr_cu() |
| 1312 | qt_arr = np.zeros(L, dtype=np.int32) |
| 1313 | for i in range(L): |
| 1314 | me = self._moe_layers[i] |
| 1315 | ptr_arr[i] = me.router_raw if me.router_raw is not None else ctypes.cast(0, cu) |
| 1316 | qt_arr[i] = getattr(me, 'router_qt', ctypes.c_int(0)).value if hasattr(me, 'router_qt') and me.router_qt is not None else 0 |
| 1317 | return ptr_arr, qt_arr |
| 1318 | |
| 1319 | (self._c_moe_router_raw, self._c_moe_router_qt) = _make_router_ptr_array() |
| 1320 | |
| 1321 | # ── Shared expert (quantized weights cast as float** in C) ── |
| 1322 | def _make_shexp_ptr_array(attr_name): |
| 1323 | """Build const float** array for shared expert weights. |
| 1324 | |
| 1325 | The weights are quantized (uint8_t*) but passed as float* in C interface. |
| 1326 | """ |
| 1327 | ptr_arr = arr_cf() |
| 1328 | for i, lw in enumerate(self._layers): |
| 1329 | raw = getattr(lw, f'{attr_name}', None) |
| 1330 | if raw is not None: |
| 1331 | # Cast uint8_t* → float* (C code casts back internally) |
| 1332 | ptr_arr[i] = ctypes.cast(raw, cf) |
| 1333 | else: |
| 1334 | ptr_arr[i] = ctypes.cast(0, cf) |
| 1335 | return ptr_arr |
| 1336 | |
| 1337 | def _make_shexp_qt_array(attr_name, default_val=39): |
| 1338 | arr = np.zeros(L, dtype=np.int32) |
| 1339 | for i, lw in enumerate(self._layers): |
| 1340 | qt = getattr(lw, f'{attr_name}', None) |
| 1341 | arr[i] = qt.value if qt is not None else default_val |
| 1342 | return arr |
| 1343 | |
| 1344 | self._c_shexp_gate_raw = _make_shexp_ptr_array('shexp_gate_raw') |
| 1345 | self._c_shexp_up_raw = _make_shexp_ptr_array('shexp_up_raw') |
| 1346 | self._c_shexp_down_raw = _make_shexp_ptr_array('shexp_down_raw') |
| 1347 | self._c_shexp_gate_qt = _make_shexp_qt_array('shexp_gate_qt', 39) |
| 1348 | self._c_shexp_up_qt = _make_shexp_qt_array('shexp_up_qt', 39) |
| 1349 | self._c_shexp_down_qt = _make_shexp_qt_array('shexp_down_qt', 39) |
| 1350 | |
| 1351 | # ── Shared expert router (1D F32 vector per layer) ── |
| 1352 | self._c_shexp_router = arr_cf() |
| 1353 | shexp_int_arr = np.zeros(L, dtype=np.int32) |
| 1354 | for i, lw in enumerate(self._layers): |
| 1355 | rptr = getattr(lw, 'shexp_router_ptr', None) |
| 1356 | if rptr is not None: |
| 1357 | self._c_shexp_router[i] = rptr |
| 1358 | else: |
| 1359 | self._c_shexp_router[i] = ctypes.cast(0, cf) |
| 1360 | # shexp_int = shared expert intermediate dim (gate output dim) |
| 1361 | nr = getattr(lw, 'shexp_gate_nr', None) |
| 1362 | shexp_int_arr[i] = nr.value if nr is not None else 512 |
| 1363 | self._c_shexp_int = shexp_int_arr |
| 1364 | |
| 1365 | # ── RoPE tables (precompute for max_ctx positions) ── |
| 1366 | max_ctx = 4096 |
| 1367 | rope_dim = self.rope_dim if hasattr(self, 'rope_dim') and self.rope_dim > 0 else self.head_dim |
| 1368 | hd2 = rope_dim // 2 |
| 1369 | if hd2 > 0: |
| 1370 | cos_table = np.zeros(max_ctx * hd2, dtype=np.float32) |
| 1371 | sin_table = np.zeros(max_ctx * hd2, dtype=np.float32) |
| 1372 | inv_freq = self.rope_freq_base ** (-np.arange(0, rope_dim, 2, dtype=np.float64) / rope_dim) |
| 1373 | for pos in range(max_ctx): |
| 1374 | theta = pos * inv_freq |
| 1375 | cos_table[pos * hd2:(pos + 1) * hd2] = np.cos(theta).astype(np.float32) |
| 1376 | sin_table[pos * hd2:(pos + 1) * hd2] = np.sin(theta).astype(np.float32) |
| 1377 | self._c_cos_table = cos_table |
| 1378 | self._c_sin_table = sin_table |
| 1379 | else: |
| 1380 | self._c_cos_table = np.zeros(1, dtype=np.float32) |
| 1381 | self._c_sin_table = np.zeros(1, dtype=np.float32) |
| 1382 | |
| 1383 | # ── C pointer for all L-length int arrays ── |
| 1384 | pi = ctypes.POINTER(ctypes.c_int) |
| 1385 | |
| 1386 | def _int_ptr(arr): |
| 1387 | return arr.ctypes.data_as(pi) |
| 1388 | |
| 1389 | # ── Workspace buffer ── |
| 1390 | # Compute S = max(N, inner, FF, n_kv, qk_dim, n_ff_expert, shexp_inner) |
| 1391 | N = self.n_embd |
| 1392 | NH = self.n_head |
| 1393 | HD = self.head_dim |
| 1394 | inner = NH * HD # 4096 |
| 1395 | n_kv = self.n_kv_head * HD # 512 |
| 1396 | qk_dim = inner + 2 * n_kv # 5120 |
| 1397 | FF = self.n_ff |
| 1398 | n_ff_expert = self.n_ff_expert if self.is_moe else FF |
| 1399 | shexp_inner = int(shexp_int_arr[0]) if shexp_int_arr[0] > 0 else 512 |
| 1400 | S = max(N, inner, FF, n_kv, qk_dim, n_ff_expert, shexp_inner, 8192) |
| 1401 | self._c_ws_S = S |
| 1402 | # The workspace is allocated per-call in forward_c_batch based on B |
| 1403 | # (since B varies). We cache S and the formula only. |
| 1404 | |
| 1405 | # q8_ws for moe_forward_omp (enough for one MoE call) |
| 1406 | q8_sz = self.n_experts_per_tok * n_ff_expert * 34 // 32 + 1024 |
| 1407 | self._c_q8_ws = np.zeros(max(1, q8_sz), dtype=np.uint8) |
| 1408 | |
| 1409 | # ── Token array (reusable, will be filled per-call) ── |
| 1410 | self._c_tokens = np.zeros(64, dtype=np.int32) # will resize if needed |
| 1411 | |
| 1412 | # Store int array pointers as ctypes for quick access |
| 1413 | self._c_pi_type = pi |
| 1414 | self._c_p_layer_types = _int_ptr(self._c_layer_types) |
| 1415 | self._c_p_qkv_nr = _int_ptr(self._c_qkv_nr) |
| 1416 | self._c_p_qkv_nc = _int_ptr(self._c_qkv_nc) |
| 1417 | self._c_p_qkv_qt = _int_ptr(self._c_qkv_qt) |
| 1418 | self._c_p_gate_nr = _int_ptr(self._c_gate_nr) |
| 1419 | self._c_p_gate_nc = _int_ptr(self._c_gate_nc) |
| 1420 | self._c_p_gate_qt = _int_ptr(self._c_gate_qt) |
| 1421 | self._c_p_ssm_out_nr = _int_ptr(self._c_ssm_out_nr) |
| 1422 | self._c_p_ssm_out_nc = _int_ptr(self._c_ssm_out_nc) |
| 1423 | self._c_p_ssm_out_qt = _int_ptr(self._c_ssm_out_qt) |
| 1424 | self._c_p_out_nr = _int_ptr(self._c_out_nr) |
| 1425 | self._c_p_out_nc = _int_ptr(self._c_out_nc) |
| 1426 | self._c_p_out_qt = _int_ptr(self._c_out_qt) |
| 1427 | self._c_p_gate_exp_qt = _int_ptr(self._c_gate_exp_qt) |
| 1428 | self._c_p_up_exp_qt = _int_ptr(self._c_up_exp_qt) |
| 1429 | self._c_p_down_exp_qt = _int_ptr(self._c_down_exp_qt) |
| 1430 | self._c_p_moe_router_qt = _int_ptr(self._c_moe_router_qt) |
| 1431 | self._c_p_shexp_int = _int_ptr(self._c_shexp_int) |
| 1432 | self._c_p_shexp_gate_qt = _int_ptr(self._c_shexp_gate_qt) |
| 1433 | self._c_p_shexp_up_qt = _int_ptr(self._c_shexp_up_qt) |
| 1434 | self._c_p_shexp_down_qt = _int_ptr(self._c_shexp_down_qt) |
| 1435 | |
| 1436 | # ── Store scalars as ctypes ints for fast access ── |
| 1437 | self._c_ci = ctypes.c_int |
| 1438 | self._c_cf = ctypes.c_float |
| 1439 | self._c_eps = ctypes.c_float(self.eps) |
| 1440 | |
| 1441 | self._c_batch_ready = True |
| 1442 | |
| 1443 | def reset(self): |
| 1444 | self.kv_len[:] = 0 |
| 1445 | self.pos = 0 |
| 1446 | self.reset_state() |
| 1447 | |
| 1448 | def reset_state(self): |
| 1449 | """Reset SSM state to zeros (call between sequences).""" |
| 1450 | if self._ssm_state is not None: |
| 1451 | self._ssm_state.fill(0.0) |
| 1452 | if self._arch_forward is not None: |
| 1453 | self._arch_forward.reset_state() |
| 1454 | |
| 1455 | def _apply_rope_fast(self, x, pos, n_heads, rope_dim=None): |
| 1456 | hd = self.head_dim |
| 1457 | if rope_dim is None or rope_dim <= 0: |
| 1458 | rope_dim = hd |
| 1459 | half = rope_dim // 2 |
| 1460 | key = (pos, rope_dim) |
| 1461 | if key not in self._rope_cos_table: |
| 1462 | freq = self.rope_freq_base ** (np.arange(0, rope_dim, 2, dtype=np.float32) / rope_dim) |
| 1463 | angle = pos / freq |
| 1464 | self._rope_cos_table[key] = np.cos(angle).astype(np.float32) |
| 1465 | self._rope_sin_table[key] = np.sin(angle).astype(np.float32) |
| 1466 | cos_a = self._rope_cos_table[key] |
| 1467 | sin_a = self._rope_sin_table[key] |
| 1468 | x2d = x.reshape(n_heads, hd) |
| 1469 | out = x2d.copy() |
| 1470 | # Only rotate first rope_dim dimensions |
| 1471 | out[:, :half] = x2d[:, :half] * cos_a - x2d[:, half:rope_dim] * sin_a |
| 1472 | out[:, half:rope_dim] = x2d[:, half:rope_dim] * cos_a + x2d[:, :half] * sin_a |
| 1473 | # Dimensions beyond rope_dim are unchanged |
| 1474 | return out.reshape(-1) |
| 1475 | |
| 1476 | def forward(self, token_id): |
| 1477 | """Single-token forward pass.""" |
| 1478 | # Architecture-specific dispatch |
| 1479 | if self._arch_forward is not None: |
| 1480 | return self._arch_forward.forward(token_id) |
| 1481 | b_x = self._x; b_r = self._residual; b_qn = self._x_norm |
| 1482 | b_q = self._q; b_k = self._k; b_v = self._v |
| 1483 | b_att = self._att_out; b_gate = self._gate; b_up = self._up |
| 1484 | b_silu = self._silu_gate; b_ffn = self._ffn_out |
| 1485 | b_oproj = self._o_proj |
| 1486 | N = self.n_embd; NH = self.n_head; NKH = self.n_kv_head * self.head_dim; HD = self.head_dim |
| 1487 | FF = self.n_ff; L = self.n_layers |
| 1488 | kern = self._kern; simd = self._simd |
| 1489 | eps_f = self._eps_f |
| 1490 | p_x = self._p_x; p_xn = self._p_x_norm; p_r = self._p_residual |
| 1491 | p_q = self._p_q; p_k = self._p_k; p_v = self._p_v |
| 1492 | p_qk = self._p_qk # fused QK output buffer |
| 1493 | p_att = self._p_att_out; p_gate = self._p_gate; p_up = self._p_up |
| 1494 | p_silu = self._p_silu_gate; p_oproj = self._p_o_proj |
| 1495 | p_ffn = self._p_ffn; p_logits = self._p_logits |
| 1496 | |
| 1497 | # Embedding lookup |
| 1498 | np.copyto(b_x, self.emb[token_id]) |
| 1499 | |
| 1500 | cf = ctypes.POINTER(ctypes.c_float) |
| 1501 | cu = ctypes.POINTER(ctypes.c_uint8) |
| 1502 | ci = ctypes.c_int |
| 1503 | |
| 1504 | # Qwen3.6 constants |
| 1505 | ssm_inner = self.ssm_inner if hasattr(self, 'ssm_inner') else (NH * HD) |
| 1506 | |
| 1507 | for i in range(L): |
| 1508 | lw = self._layers[i] |
| 1509 | is_ssm_layer = (self.layer_types is not None and self.layer_types[i] == 1) |
| 1510 | |
| 1511 | # V2: Replace np.copyto with slice assignment (faster, avoids function call). |
| 1512 | # Removed np.clip — Qwen3-30B doesn't need it at Q4_K_M precision. |
| 1513 | b_r[:] = b_x |
| 1514 | |
| 1515 | # RMS norm 1 |
| 1516 | simd.rms_norm(p_xn, p_x, |
| 1517 | lw.attn_norm_w.ctypes.data_as(cf), |
| 1518 | N, eps_f) |
| 1519 | |
| 1520 | if is_ssm_layer and self._cengine is not None and lw.ssm_conv1d_ptr is not None: |
| 1521 | # ═══ FUSED SSM path ═══ (one C call replaces 3 ctypes calls) |
| 1522 | state_ptr = self._ssm_state[i].ctypes.data_as(cf) |
| 1523 | kern.ssm_layer_fused( |
| 1524 | p_xn, p_r, p_x, # x, residual, output (in-place) |
| 1525 | lw.ssm_conv1d_ptr, lw.ssm_a_ptr, lw.ssm_dt_bias_ptr, |
| 1526 | lw.ssm_alpha_ptr, lw.ssm_beta_ptr, lw.ssm_norm_ptr, |
| 1527 | state_ptr, |
| 1528 | lw.attn_gate_raw, lw.attn_gate_nr, lw.attn_gate_nc, lw.attn_gate_qt, |
| 1529 | lw.ssm_out_raw, lw.ssm_out_nr, lw.ssm_out_nc, lw.ssm_out_qt, |
| 1530 | ci(1), ci(N), ci(ssm_inner), |
| 1531 | ci(self.ssm_groups), ci(self.ssm_state_size), |
| 1532 | ci(self.ssm_conv_kernel), ci(self.ssm_dt_rank)) |
| 1533 | |
| 1534 | else: |
| 1535 | # ═══ Full Attention path ═══ |
| 1536 | |
| 1537 | # QKV using attn_qkv (fused) if available, else separate Q/K/V |
| 1538 | if hasattr(lw, 'attn_qkv_use_c') and lw.attn_qkv_use_c: |
| 1539 | # attn_qkv: N→8192 (Q:4096, K:2048, V:2048) |
| 1540 | qkv_buf = self._qk # reuse _qk buffer for full QKV output (needs 8192 floats) |
| 1541 | # Ensure buffer is large enough — _qk was allocated as NK + NKH = 4096+512=4608 |
| 1542 | # For 8192 we need larger buffer, so use a temp allocation |
| 1543 | if len(self._qk) < 8192: |
| 1544 | self._qk = np.zeros(8192, dtype=np.float32) |
| 1545 | self._p_qk = self._qk.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1546 | p_qkv = self._p_qk |
| 1547 | kern.quant_matmul_omp(lw.attn_qkv_raw, p_xn, p_qkv, |
| 1548 | lw.attn_qkv_nr, lw.attn_qkv_nc, lw.attn_qkv_qt) |
| 1549 | # Split: first NH*HD = Q, next N = K, next N = V |
| 1550 | nq_vals = NH * HD # 4096 |
| 1551 | b_q[:] = self._qk[:nq_vals] |
| 1552 | b_k[:NKH] = self._qk[nq_vals:nq_vals + NKH] # first NKH*HD from K section |
| 1553 | b_v[:NKH] = self._qk[nq_vals + N:nq_vals + N + NKH] # first NKH*HD from V section |
| 1554 | elif hasattr(lw, 'attn_qk_use_c') and lw.attn_qk_use_c: |
| 1555 | # Fused Q+K matmul into _qk buffer |
| 1556 | kern.quant_matmul_omp( |
| 1557 | lw.attn_qk_raw, p_xn, p_qk, |
| 1558 | lw.attn_qk_nr, lw.attn_qk_nc, lw.attn_qk_qt) |
| 1559 | # Separate V matmul |
| 1560 | kern.quant_matmul_omp( |
| 1561 | lw.attn_v_raw, p_xn, p_v, |
| 1562 | lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt) |
| 1563 | elif lw.attn_q_use_c and lw.attn_k_use_c and lw.attn_v_use_c: |
| 1564 | kern.batch_qkv_omp( |
| 1565 | lw.attn_q_raw, lw.attn_k_raw, lw.attn_v_raw, |
| 1566 | p_xn, p_q, p_k, p_v, |
| 1567 | lw.attn_q_nr, lw.attn_k_nr, lw.attn_v_nr, |
| 1568 | lw.attn_q_nc, |
| 1569 | lw.attn_q_qt, lw.attn_k_qt, lw.attn_v_qt) |
| 1570 | else: |
| 1571 | if lw.attn_q_use_c: |
| 1572 | kern.quant_matmul_omp(lw.attn_q_raw, p_xn, p_q, lw.attn_q_nr, lw.attn_q_nc, lw.attn_q_qt) |
| 1573 | if lw.attn_k_use_c: |
| 1574 | kern.quant_matmul_omp(lw.attn_k_raw, p_xn, p_k, lw.attn_k_nr, lw.attn_k_nc, lw.attn_k_qt) |
| 1575 | if lw.attn_v_use_c: |
| 1576 | kern.quant_matmul_omp(lw.attn_v_raw, p_xn, p_v, lw.attn_v_nr, lw.attn_v_nc, lw.attn_v_qt) |
| 1577 | |
| 1578 | # Q/K norm |
| 1579 | if lw.has_q_norm: |
| 1580 | q_2d = b_q.reshape(NH, HD) |
| 1581 | q_rms = np.sqrt(np.mean(q_2d * q_2d, axis=1, keepdims=True) + self.eps) |
| 1582 | q_2d[:] = q_2d / q_rms * lw.q_norm_w.reshape(1, HD) |
| 1583 | if lw.has_k_norm: |
| 1584 | k_2d = b_k[:NKH].reshape(self.n_kv_head, HD) |
| 1585 | k_rms = np.sqrt(np.mean(k_2d * k_2d, axis=1, keepdims=True) + self.eps) |
| 1586 | k_2d[:] = k_2d / k_rms * lw.k_norm_w.reshape(1, HD) |
| 1587 | |
| 1588 | # RoPE with partial rotary (rope_dim) |
| 1589 | rope_d = self.rope_dim if hasattr(self, 'rope_dim') and self.rope_dim > 0 else HD |
| 1590 | b_q[:] = self._apply_rope_fast(b_q, self.pos, NH, rope_dim=rope_d) |
| 1591 | b_k[:] = self._apply_rope_fast(b_k, self.pos, self.n_kv_head, rope_dim=rope_d) |
| 1592 | |
| 1593 | # KV cache |
| 1594 | self.kv_k[i, self.kv_len[i], :NKH] = b_k[:NKH] |
| 1595 | self.kv_v[i, self.kv_len[i], :NKH] = b_v[:NKH] |
| 1596 | |
| 1597 | # GQA Attention |
| 1598 | seq_len = self.kv_len[i] + 1 |
| 1599 | if self._gqa_attn is not None and seq_len <= 4096: |
| 1600 | self._gqa_attn.gqa_attention_decode( |
| 1601 | b_q.ctypes.data_as(cf), |
| 1602 | self.kv_k[i].ctypes.data_as(cf), |
| 1603 | self.kv_v[i].ctypes.data_as(cf), |
| 1604 | b_att.ctypes.data_as(cf), |
| 1605 | ci(seq_len), ci(NH), ci(self.n_kv_head), ci(HD), |
| 1606 | self._p_gqa_ws) |
| 1607 | else: |
| 1608 | k_cache = self.kv_k[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) |
| 1609 | v_cache = self.kv_v[i, :seq_len].reshape(seq_len, self.n_kv_head, HD) |
| 1610 | q_2d = b_q.reshape(NH, HD) |
| 1611 | nk = self.n_kv_head; gqa = self._gqa_rep |
| 1612 | q_g = q_2d.reshape(nk, gqa, HD) |
| 1613 | k_T = k_cache.transpose(1, 0, 2) |
| 1614 | scores = np.einsum('khd,ksd->khs', q_g, k_T) / np.sqrt(float(HD)) |
| 1615 | scores = scores.reshape(NH, seq_len) |
| 1616 | scores -= np.max(scores, axis=1, keepdims=True) |
| 1617 | np.exp(scores, out=scores) |
| 1618 | scores /= np.sum(scores, axis=1, keepdims=True) |
| 1619 | v_T = v_cache.transpose(1, 0, 2) |
| 1620 | att = np.einsum('khs,ksd->khd', scores.reshape(nk, gqa, seq_len), v_T) |
| 1621 | b_att[:] = att.reshape(-1) |
| 1622 | self.kv_len[i] += 1 |
| 1623 | |
| 1624 | # Output projection: attn_gate (if available) else standard O proj |
| 1625 | if hasattr(lw, 'attn_gate_use_c') and lw.attn_gate_use_c: |
| 1626 | # Qwen3.6: attn_gate maps inner→N (produced by attn_qkv GQA) |
| 1627 | kern.quant_matmul_omp( |
| 1628 | lw.attn_gate_raw, p_att, p_oproj, |
| 1629 | lw.attn_gate_nr, lw.attn_gate_nc, lw.attn_gate_qt) |
| 1630 | b_x[:N] = b_r[:N] + b_oproj[:N] |
| 1631 | else: |
| 1632 | if lw.attn_out_use_c: |
| 1633 | kern.quant_matmul_omp(lw.attn_out_raw, p_att, p_oproj, |
| 1634 | lw.attn_out_nr, lw.attn_out_nc, lw.attn_out_qt) |
| 1635 | b_x[:N] = b_r[:N] + b_oproj[:N] |
| 1636 | else: |
| 1637 | b_x[:N] = b_r[:N] + (lw.attn_out_f32 @ b_att)[:N] |
| 1638 | |
| 1639 | # ── FFN ── |
| 1640 | b_r[:] = b_x |
| 1641 | simd.rms_norm(p_xn, p_x, |
| 1642 | lw.ffn_norm_w.ctypes.data_as(cf), |
| 1643 | N, eps_f) |
| 1644 | |
| 1645 | if self.is_moe and self._moe_layers: |
| 1646 | me = self._moe_layers[i] |
| 1647 | if me.router_f32 is not None or me.router_raw is not None: |
| 1648 | # MoE path — has router and expert weights |
| 1649 | self._forward_moe(i, p_xn, b_ffn, b_r, N) |
| 1650 | # Residual add: MoE FFN output + residual → hidden state |
| 1651 | b_x[:N] = b_r[:N] + b_ffn[:N] |
| 1652 | # Shared expert (Qwen3.6) — add on top |
| 1653 | else: |
| 1654 | # Dense FFN fallback for MoE models that have leading dense layers |
| 1655 | # (e.g., ERNIE 4.5, DeepSeek with leading_dense_block_count > 0) |
| 1656 | if lw.ffn_gate_use_c and lw.ffn_up_use_c: |
| 1657 | kern.batch_gate_up_omp( |
| 1658 | lw.ffn_gate_raw, lw.ffn_up_raw, p_xn, p_gate, p_up, |
| 1659 | lw.ffn_gate_nr, lw.ffn_up_nr, |
| 1660 | lw.ffn_gate_nc, lw.ffn_gate_qt, lw.ffn_up_qt) |
| 1661 | else: |
| 1662 | if lw.ffn_gate_use_c: |
| 1663 | kern.quant_matmul_omp(lw.ffn_gate_raw, p_xn, p_gate, |
| 1664 | lw.ffn_gate_nr, lw.ffn_gate_nc, lw.ffn_gate_qt) |
| 1665 | if lw.ffn_up_use_c: |
| 1666 | kern.quant_matmul_omp(lw.ffn_up_raw, p_xn, p_up, |
| 1667 | lw.ffn_up_nr, lw.ffn_up_nc, lw.ffn_up_qt) |
| 1668 | simd.silu(p_silu, p_gate, ci(FF)) |
| 1669 | b_silu[:FF] *= b_up[:FF] |
| 1670 | if lw.ffn_down_use_c: |
| 1671 | kern.quant_matmul_omp(lw.ffn_down_raw, p_silu, p_ffn, |
| 1672 | lw.ffn_down_nr, lw.ffn_down_nc, lw.ffn_down_qt) |
| 1673 | b_x[:N] = b_r[:N] + b_ffn[:N] |
| 1674 | else: |
| 1675 | b_x[:N] = b_r[:N] + (lw.ffn_down_f32 @ b_silu[:lw.ffn_down_nc.value])[:N] |
| 1676 | # Shared expert (Qwen3.6) — add on top (for MoE layers) |
| 1677 | if (hasattr(lw, 'shexp_router_ptr') and lw.shexp_router_ptr is not None |
| 1678 | and hasattr(lw, 'shexp_gate_use_c') and lw.shexp_gate_use_c): |
| 1679 | # Router score: dot product with 1D vector |
| 1680 | shexp_score = float(np.dot(self._x_norm, |
| 1681 | np.ctypeslib.as_array(lw.shexp_router_ptr, shape=(N,)))) |
| 1682 | if shexp_score > 0: |
| 1683 | shexp_int = lw.shexp_gate_nr.value # 512 |
| 1684 | kern.quant_matmul_omp(lw.shexp_gate_raw, p_xn, p_gate, |
| 1685 | lw.shexp_gate_nr, lw.shexp_gate_nc, lw.shexp_gate_qt) |
| 1686 | kern.quant_matmul_omp(lw.shexp_up_raw, p_xn, p_up, |
| 1687 | lw.shexp_up_nr, lw.shexp_up_nc, lw.shexp_up_qt) |
| 1688 | simd.silu(p_silu, p_gate, ci(shexp_int)) |
| 1689 | b_silu[:shexp_int] *= b_up[:shexp_int] |
| 1690 | kern.quant_matmul_omp(lw.shexp_down_raw, p_silu, p_ffn, |
| 1691 | lw.shexp_down_nr, lw.shexp_down_nc, lw.shexp_down_qt) |
| 1692 | b_x[:N] += shexp_score * b_ffn[:N] |
| 1693 | else: |
| 1694 | if lw.ffn_gate_use_c and lw.ffn_up_use_c: |
| 1695 | kern.batch_gate_up_omp( |
| 1696 | lw.ffn_gate_raw, lw.ffn_up_raw, p_xn, p_gate, p_up, |
| 1697 | lw.ffn_gate_nr, lw.ffn_up_nr, |
| 1698 | lw.ffn_gate_nc, lw.ffn_gate_qt, lw.ffn_up_qt) |
| 1699 | else: |
| 1700 | if lw.ffn_gate_use_c: |
| 1701 | kern.quant_matmul_omp(lw.ffn_gate_raw, p_xn, p_gate, |
| 1702 | lw.ffn_gate_nr, lw.ffn_gate_nc, lw.ffn_gate_qt) |
| 1703 | if lw.ffn_up_use_c: |
| 1704 | kern.quant_matmul_omp(lw.ffn_up_raw, p_xn, p_up, |
| 1705 | lw.ffn_up_nr, lw.ffn_up_nc, lw.ffn_up_qt) |
| 1706 | simd.silu(p_silu, p_gate, ci(FF)) |
| 1707 | b_silu[:FF] *= b_up[:FF] |
| 1708 | if lw.ffn_down_use_c: |
| 1709 | kern.quant_matmul_omp(lw.ffn_down_raw, p_silu, p_ffn, |
| 1710 | lw.ffn_down_nr, lw.ffn_down_nc, lw.ffn_down_qt) |
| 1711 | b_x[:N] = b_r[:N] + b_ffn[:N] |
| 1712 | else: |
| 1713 | b_x[:N] = b_r[:N] + (lw.ffn_down_f32 @ b_silu[:lw.ffn_down_nc.value])[:N] |
| 1714 | |
| 1715 | # Final norm |
| 1716 | simd.rms_norm(p_xn, p_x, |
| 1717 | self._out_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 1718 | N, eps_f) |
| 1719 | |
| 1720 | # Output projection |
| 1721 | if self._out_use_c: |
| 1722 | kern.quant_matmul_omp(self._out_raw, p_xn, p_logits, |
| 1723 | self._out_nr, self._out_nc, self._out_qt) |
| 1724 | else: |
| 1725 | self._logits[:] = self._out_f32 @ b_qn |
| 1726 | |
| 1727 | self.pos += 1 |
| 1728 | return self._logits |
| 1729 | |
| 1730 | def forward_c_batch(self, token_ids): |
| 1731 | """Process B tokens in a single C call via batch forward function. |
| 1732 | |
| 1733 | Supports qwen35moe (fused QKV + SSM) via qwen36_batch_forward and |
| 1734 | gpt-oss (separate Q/K/V + MoE) via gptoss_batch_forward. |
| 1735 | |
| 1736 | Args: |
| 1737 | token_ids: list or 1D array of token IDs (length B) |
| 1738 | |
| 1739 | Returns: |
| 1740 | np.ndarray of shape (B, vocab_size) with logits for each token |
| 1741 | """ |
| 1742 | if not self._c_batch_ready: |
| 1743 | raise RuntimeError( |
| 1744 | "forward_c_batch requires compatible architecture with combined_engine.so") |
| 1745 | |
| 1746 | B = len(token_ids) |
| 1747 | L = self.n_layers |
| 1748 | N = self.n_embd |
| 1749 | NH = self.n_head |
| 1750 | n_kv_h = self.n_kv_head |
| 1751 | HD = self.head_dim |
| 1752 | FF = self.n_ff |
| 1753 | n_experts = self.n_experts if self.is_moe else 0 |
| 1754 | top_k = self.n_experts_per_tok if self.is_moe else 0 |
| 1755 | n_ff_expert = self.n_ff_expert if self.is_moe else FF |
| 1756 | eps = self.eps |
| 1757 | rope_dim = self.rope_dim if hasattr(self, 'rope_dim') else 0 |
| 1758 | max_ctx = 4096 |
| 1759 | |
| 1760 | emb_ptr = self.emb.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) if hasattr(self, 'emb') else None |
| 1761 | if emb_ptr is None: |
| 1762 | raise RuntimeError("No embedding table loaded") |
| 1763 | |
| 1764 | # Determine if we're using GPT-OSS C forward |
| 1765 | is_gptoss = hasattr(self, 'arch_name') and self.arch_name in ('gpt-oss', 'gptoss') |
| 1766 | |
| 1767 | if is_gptoss: |
| 1768 | return self._forward_c_batch_gptoss( |
| 1769 | B, L, N, NH, n_kv_h, HD, FF, n_experts, top_k, |
| 1770 | n_ff_expert, eps, rope_dim, max_ctx, emb_ptr, token_ids) |
| 1771 | |
| 1772 | # Determine if we're using ZAYA C forward |
| 1773 | is_zaya = hasattr(self, 'arch_name') and self.arch_name == 'zaya' |
| 1774 | |
| 1775 | if is_zaya: |
| 1776 | return self._forward_c_batch_zaya(B, token_ids) |
| 1777 | |
| 1778 | # ── Original qwen35moe path below ── |
| 1779 | ssm_inner = self.ssm_inner if hasattr(self, 'ssm_inner') else (NH * HD) |
| 1780 | ssm_groups = self.ssm_groups if hasattr(self, 'ssm_groups') else 32 |
| 1781 | ssm_state_size = self.ssm_state_size if hasattr(self, 'ssm_state_size') else 128 |
| 1782 | ssm_conv_kernel = self.ssm_conv_kernel if hasattr(self, 'ssm_conv_kernel') else 4 |
| 1783 | ssm_dt_rank = self.ssm_dt_rank if hasattr(self, 'ssm_dt_rank') else 32 |
| 1784 | |
| 1785 | emb_quant = 0 # 0 = F32 embedding |
| 1786 | |
| 1787 | # Ensure token array is big enough |
| 1788 | if len(self._c_tokens) < B: |
| 1789 | self._c_tokens = np.zeros(B + 64, dtype=np.int32) |
| 1790 | self._c_tokens[:B] = token_ids |
| 1791 | tokens_ptr = self._c_tokens.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 1792 | |
| 1793 | # Logits buffer |
| 1794 | if not hasattr(self, '_c_logits_batch') or self._c_logits_batch.shape[0] < B: |
| 1795 | self._c_logits_batch = np.zeros((B + 8, self.vocab_size), dtype=np.float32) |
| 1796 | logits_ptr = self._c_logits_batch.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1797 | |
| 1798 | # Workspace buffer (float) |
| 1799 | S = self._c_ws_S |
| 1800 | ws_needed = B * S * 12 |
| 1801 | if not hasattr(self, '_c_ws') or len(self._c_ws) < ws_needed: |
| 1802 | self._c_ws = np.zeros(max(ws_needed, 1), dtype=np.float32) |
| 1803 | ws_ptr = self._c_ws.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1804 | |
| 1805 | # q8 workspace (uint8) |
| 1806 | q8_ptr = self._c_q8_ws.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 1807 | |
| 1808 | ci = ctypes.c_int |
| 1809 | cf = ctypes.POINTER(ctypes.c_float) |
| 1810 | |
| 1811 | # SSM state pointer (flat: [L][groups][state_size]) |
| 1812 | ssm_state_ptr = self._ssm_state.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) if self._ssm_state is not None else None |
| 1813 | |
| 1814 | # KV cache pointers |
| 1815 | kv_k_ptr = self.kv_k.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1816 | kv_v_ptr = self.kv_v.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1817 | kv_lens_ptr = self.kv_len.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 1818 | |
| 1819 | # RoPE tables |
| 1820 | cos_ptr = self._c_cos_table.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1821 | sin_ptr = self._c_sin_table.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1822 | |
| 1823 | # Output norm + output weight |
| 1824 | out_norm_ptr = self._out_norm_w.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) if self._out_norm_w is not None else None |
| 1825 | if self._out_use_c: |
| 1826 | out_w_ptr = self._out_raw |
| 1827 | out_nr_final = self._out_nr.value if hasattr(self._out_nr, 'value') else self._out_nr |
| 1828 | out_nc_final = self._out_nc.value if hasattr(self._out_nc, 'value') else self._out_nc |
| 1829 | out_qt_final = self._out_qt.value if hasattr(self._out_qt, 'value') else self._out_qt |
| 1830 | else: |
| 1831 | out_w_ptr = self._out_f32.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)) |
| 1832 | out_nr_final = self.vocab_size |
| 1833 | out_nc_final = N |
| 1834 | out_qt_final = 0 |
| 1835 | |
| 1836 | kern = self._kern |
| 1837 | |
| 1838 | # ── Call C function ── |
| 1839 | kern.qwen36_batch_forward( |
| 1840 | # Scalars |
| 1841 | ci(B), ci(L), ci(N), ci(NH), ci(n_kv_h), ci(HD), ci(FF), |
| 1842 | ci(n_experts), ci(top_k), ci(n_ff_expert), ctypes.c_float(eps), |
| 1843 | ci(rope_dim), ci(max_ctx), ci(ssm_inner), ci(ssm_groups), |
| 1844 | ci(ssm_state_size), ci(ssm_conv_kernel), ci(ssm_dt_rank), |
| 1845 | # Embedding |
| 1846 | emb_ptr, ci(emb_quant), |
| 1847 | # Layer types |
| 1848 | self._c_p_layer_types, |
| 1849 | # Token IDs |
| 1850 | tokens_ptr, |
| 1851 | # Logits output |
| 1852 | logits_ptr, |
| 1853 | # Per-layer weight arrays |
| 1854 | self._c_attn_norm_w, self._c_ffn_norm_w, |
| 1855 | self._c_attn_qkv_raw, |
| 1856 | self._c_p_qkv_nr, self._c_p_qkv_nc, self._c_p_qkv_qt, |
| 1857 | self._c_attn_gate_raw, |
| 1858 | self._c_p_gate_nr, self._c_p_gate_nc, self._c_p_gate_qt, |
| 1859 | self._c_ssm_out_raw, |
| 1860 | self._c_p_ssm_out_nr, self._c_p_ssm_out_nc, self._c_p_ssm_out_qt, |
| 1861 | self._c_attn_out_raw, |
| 1862 | self._c_p_out_nr, self._c_p_out_nc, self._c_p_out_qt, |
| 1863 | # MoE expert weights |
| 1864 | self._c_gate_exp_raw, self._c_p_gate_exp_qt, |
| 1865 | self._c_up_exp_raw, self._c_p_up_exp_qt, |
| 1866 | self._c_down_exp_raw, self._c_p_down_exp_qt, |
| 1867 | # Shared expert |
| 1868 | self._c_shexp_gate_raw, self._c_shexp_up_raw, self._c_shexp_down_raw, |
| 1869 | self._c_shexp_router, |
| 1870 | self._c_p_shexp_int, |
| 1871 | # MoE router + shexp quant types |
| 1872 | self._c_moe_router_raw, self._c_p_moe_router_qt, |
| 1873 | self._c_p_shexp_gate_qt, self._c_p_shexp_up_qt, self._c_p_shexp_down_qt, |
| 1874 | # Output norm + projection |
| 1875 | out_norm_ptr, |
| 1876 | out_w_ptr, ci(out_nr_final), ci(out_nc_final), ci(out_qt_final), |
| 1877 | # SSM per-layer pointers |
| 1878 | self._c_ssm_conv1d, self._c_ssm_a, self._c_ssm_dt_bias, |
| 1879 | self._c_ssm_alpha, self._c_ssm_beta, self._c_ssm_norm, |
| 1880 | ssm_state_ptr, |
| 1881 | # KV cache |
| 1882 | kv_k_ptr, kv_v_ptr, kv_lens_ptr, |
| 1883 | cos_ptr, sin_ptr, |
| 1884 | # Workspace |
| 1885 | ws_ptr, q8_ptr |
| 1886 | ) |
| 1887 | |
| 1888 | # C function uses but does NOT increment kv_lens — we do it here |
| 1889 | self.kv_len[:] += 1 |
| 1890 | self.pos += 1 |
| 1891 | |
| 1892 | # Return logits for all B tokens |
| 1893 | return self._c_logits_batch[:B] |
| 1894 | |
| 1895 | def _forward_c_batch_gptoss(self, B, L, N, NH, n_kv_h, HD, FF, |
| 1896 | n_experts, top_k, n_ff_expert, |
| 1897 | eps, rope_dim, max_ctx, emb_ptr, token_ids): |
| 1898 | """GPT-OSS batch forward via gptoss_batch_forward (separate Q/K/V, no SSM).""" |
| 1899 | kern = self._kern |
| 1900 | ci = ctypes.c_int |
| 1901 | cf_type = ctypes.POINTER(ctypes.c_float) |
| 1902 | cu_type = ctypes.POINTER(ctypes.c_uint8) |
| 1903 | |
| 1904 | # Ensure token array is big enough |
| 1905 | if len(self._c_gptoss_tokens) < B: |
| 1906 | self._c_gptoss_tokens = np.zeros(B + 64, dtype=np.int32) |
| 1907 | self._c_gptoss_tokens[:B] = token_ids |
| 1908 | tokens_ptr = self._c_gptoss_tokens.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 1909 | |
| 1910 | # Logits buffer |
| 1911 | if not hasattr(self, '_c_gptoss_logits') or self._c_gptoss_logits.shape[0] < B: |
| 1912 | self._c_gptoss_logits = np.zeros((B + 8, self.vocab_size), dtype=np.float32) |
| 1913 | logits_ptr = self._c_gptoss_logits.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 1914 | |
| 1915 | # Workspace buffer (float) — 11 slices of B*S |
| 1916 | S = self._c_gptoss_ws_S |
| 1917 | ws_needed = B * S * 11 |
| 1918 | if not hasattr(self, '_c_gptoss_ws') or len(self._c_gptoss_ws) < ws_needed: |
| 1919 | self._c_gptoss_ws = np.zeros(max(ws_needed, 1), dtype=np.float32) |
| 1920 | ws_ptr = self._c_gptoss_ws.ctypes.data_as(cf_type) |
| 1921 | |
| 1922 | # q8 workspace (uint8) |
| 1923 | q8_ptr = self._c_gptoss_q8_ws.ctypes.data_as(cu_type) |
| 1924 | |
| 1925 | # KV cache pointers |
| 1926 | kv_k_ptr = self.kv_k.ctypes.data_as(cf_type) |
| 1927 | kv_v_ptr = self.kv_v.ctypes.data_as(cf_type) |
| 1928 | kv_lens_ptr = self.kv_len.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 1929 | |
| 1930 | # RoPE tables |
| 1931 | cos_ptr = self._c_gptoss_cos_table.ctypes.data_as(cf_type) |
| 1932 | sin_ptr = self._c_gptoss_sin_table.ctypes.data_as(cf_type) |
| 1933 | |
| 1934 | # Output norm + output weight |
| 1935 | out_norm_ptr = self._out_norm_w.ctypes.data_as(cf_type) if self._out_norm_w is not None else ctypes.cast(0, cf_type) |
| 1936 | if self._out_use_c: |
| 1937 | out_w_ptr = self._out_raw |
| 1938 | out_nr_final = self._out_nr.value if hasattr(self._out_nr, 'value') else self._out_nr |
| 1939 | out_nc_final = self._out_nc.value if hasattr(self._out_nc, 'value') else self._out_nc |
| 1940 | out_qt_final = self._out_qt.value if hasattr(self._out_qt, 'value') else self._out_qt |
| 1941 | else: |
| 1942 | out_w_ptr = self._out_f32.ctypes.data_as(cu_type) |
| 1943 | out_nr_final = self.vocab_size |
| 1944 | out_nc_final = N |
| 1945 | out_qt_final = 0 |
| 1946 | |
| 1947 | # ── Call gptoss_batch_forward ── |
| 1948 | kern.gptoss_batch_forward( |
| 1949 | # Scalars |
| 1950 | ci(B), ci(L), ci(N), ci(NH), ci(n_kv_h), ci(HD), ci(FF), |
| 1951 | ci(n_experts), ci(top_k), ci(n_ff_expert), ctypes.c_float(eps), |
| 1952 | ci(rope_dim), ci(max_ctx), |
| 1953 | # Embedding |
| 1954 | emb_ptr, |
| 1955 | # Token IDs |
| 1956 | tokens_ptr, |
| 1957 | # Logits output |
| 1958 | logits_ptr, |
| 1959 | # Per-layer weight pointer arrays |
| 1960 | self._c_gptoss_attn_norm_w, self._c_gptoss_post_attn_norm_w, |
| 1961 | # Q |
| 1962 | self._c_gptoss_wQ, |
| 1963 | self._c_gptoss_p_q_nr, self._c_gptoss_p_q_nc, self._c_gptoss_p_q_qt, |
| 1964 | # K |
| 1965 | self._c_gptoss_wK, |
| 1966 | self._c_gptoss_p_k_nr, self._c_gptoss_p_k_nc, self._c_gptoss_p_k_qt, |
| 1967 | # V |
| 1968 | self._c_gptoss_wV, |
| 1969 | self._c_gptoss_p_v_nr, self._c_gptoss_p_v_nc, self._c_gptoss_p_v_qt, |
| 1970 | # O |
| 1971 | self._c_gptoss_wO, |
| 1972 | self._c_gptoss_p_o_nr, self._c_gptoss_p_o_nc, self._c_gptoss_p_o_qt, |
| 1973 | # MoE router + experts |
| 1974 | self._c_gptoss_w_gate_inp, |
| 1975 | self._c_gptoss_gate_exp_raw, self._c_gptoss_p_gate_exp_qt, |
| 1976 | self._c_gptoss_up_exp_raw, self._c_gptoss_p_up_exp_qt, |
| 1977 | self._c_gptoss_down_exp_raw, self._c_gptoss_p_down_exp_qt, |
| 1978 | # Output norm + projection |
| 1979 | out_norm_ptr, |
| 1980 | out_w_ptr, ci(out_nr_final), ci(out_nc_final), ci(out_qt_final), |
| 1981 | # KV cache |
| 1982 | kv_k_ptr, kv_v_ptr, kv_lens_ptr, |
| 1983 | cos_ptr, sin_ptr, |
| 1984 | # Workspace |
| 1985 | ws_ptr, q8_ptr |
| 1986 | ) |
| 1987 | |
| 1988 | # C function does NOT increment kv_lens — we do it here |
| 1989 | self.kv_len[:] += 1 |
| 1990 | self.pos += 1 |
| 1991 | |
| 1992 | return self._c_gptoss_logits[:B] |
| 1993 | |
| 1994 | def _forward_c_batch_zaya(self, B, token_ids): |
| 1995 | """ZAYA batch forward via zaya_batch_forward (BC struct based).""" |
| 1996 | ce = self._kern |
| 1997 | ci = ctypes.c_int |
| 1998 | cf_type = ctypes.POINTER(ctypes.c_float) |
| 1999 | |
| 2000 | # Ensure token array is big enough |
| 2001 | if len(self._c_zaya_tokens) < B: |
| 2002 | self._c_zaya_tokens = np.zeros(B + 64, dtype=np.int32) |
| 2003 | self._c_zaya_tokens[:B] = token_ids |
| 2004 | tokens_ptr = self._c_zaya_tokens.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) |
| 2005 | |
| 2006 | # Logits buffer |
| 2007 | if not hasattr(self, '_c_zaya_logits') or self._c_zaya_logits.shape[0] < B: |
| 2008 | self._c_zaya_logits = np.zeros((B + 8, self.vocab_size), dtype=np.float32) |
| 2009 | |
| 2010 | # Update BC struct with current logits pointer |
| 2011 | bc = self._c_zaya_bc |
| 2012 | bc.logits = self._c_zaya_logits.ctypes.data_as(cf_type) |
| 2013 | |
| 2014 | # Workspace |
| 2015 | ws_ptr = self._c_zaya_ws.ctypes.data_as(cf_type) |
| 2016 | |
| 2017 | # Call C function |
| 2018 | ce.zaya_batch_forward( |
| 2019 | ctypes.byref(bc), |
| 2020 | tokens_ptr, |
| 2021 | ci(B), |
| 2022 | ws_ptr |
| 2023 | ) |
| 2024 | |
| 2025 | # C function does NOT increment kv_lens — we do it here |
| 2026 | self.kv_len[:] += 1 |
| 2027 | self.pos += 1 |
| 2028 | |
| 2029 | return self._c_zaya_logits[:B] |
| 2030 | |
| 2031 | def _forward_moe(self, layer, p_xn, b_ffn_out, b_residual, N): |
| 2032 | """C-accelerated MoE FFN — quant matmul for expert dispatch.""" |
| 2033 | me = self._moe_layers[layer] |
| 2034 | n_exp = me.n_experts |
| 2035 | top_k = self.n_experts_per_tok |
| 2036 | FF = me.n_ff_expert |
| 2037 | kern = self._kern |
| 2038 | |
| 2039 | # Router |
| 2040 | if me.router_raw is not None: |
| 2041 | kern.quant_matmul_omp( |
| 2042 | me.router_raw, p_xn, self._p_moe_router, |
| 2043 | me.router_nr, me.router_nc, me.router_qt) |
| 2044 | else: |
| 2045 | np.copyto(self._moe_router_scores[:n_exp], |
| 2046 | (me.router_f32 @ self._x_norm)[:n_exp]) |
| 2047 | |
| 2048 | # Softmax + Top-K |
| 2049 | scores = self._moe_router_scores[:n_exp] |
| 2050 | scores -= np.max(scores) |
| 2051 | np.exp(scores, out=scores) |
| 2052 | scores /= np.sum(scores) |
| 2053 | top_indices = np.argpartition(scores, -top_k)[-top_k:] |
| 2054 | top_weights = scores[top_indices] |
| 2055 | top_weights /= np.sum(top_weights) |
| 2056 | |
| 2057 | # Fused MoE dispatch — single C call replaces 24 ctypes calls |
| 2058 | # Use pre-built full-pointer arrays (zero construction cost) |
| 2059 | gate_ptrs = me.gate_ptrs_arr |
| 2060 | up_ptrs = me.up_ptrs_arr |
| 2061 | down_ptrs = me.down_ptrs_arr |
| 2062 | |
| 2063 | top_idx_arr = np.ascontiguousarray(top_indices.astype(np.int32)) |
| 2064 | top_wt_arr = np.ascontiguousarray(top_weights.astype(np.float32)) |
| 2065 | |
| 2066 | self._moe_combined[:] = 0.0 |
| 2067 | kern.moe_forward_omp( |
| 2068 | gate_ptrs, up_ptrs, down_ptrs, |
| 2069 | p_xn, |
| 2070 | ctypes.c_int(FF), ctypes.c_int(N), |
| 2071 | me.gate_qt, me.up_qt, me.down_qt, |
| 2072 | top_idx_arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), |
| 2073 | top_wt_arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 2074 | ctypes.c_int(top_k), |
| 2075 | self._p_moe_combined, |
| 2076 | self._moe_prealloc_buf.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), |
| 2077 | self._moe_prealloc_q8.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))) |
| 2078 | |
| 2079 | b_ffn_out[:N] = self._moe_combined[:N] |
| 2080 | # NaN guard: MXFP4 MoE experts produce NaN for 2880-dim experts (GPT-OSS). |
| 2081 | # Zero them to prevent NaN propagation through residual connection. |
| 2082 | if np.isnan(self._moe_combined[0]): |
| 2083 | mask = np.isnan(b_ffn_out[:N]) |
| 2084 | if np.any(mask): |
| 2085 | b_ffn_out[:N][mask] = 0.0 |
| 2086 | |
| 2087 | def _silu(self, x): |
| 2088 | return x / (1.0 + np.exp(-x)) |
| 2089 | |
| 2090 | |
| 2091 | if __name__ == '__main__': |
| 2092 | import sys |
| 2093 | model = sys.argv[1] if len(sys.argv) > 1 else '/onedev-workspace/work/Qwen3-30B-A3B-Q4_K_M.gguf' |
| 2094 | t = int(sys.argv[2]) if len(sys.argv) > 2 else 32 |
| 2095 | n_gen = int(sys.argv[3]) if len(sys.argv) > 3 else 20 |
| 2096 | |
| 2097 | engine = TurboEngineV7MoE(model, n_threads=t) |
| 2098 | |
| 2099 | # Warmup |
| 2100 | engine.reset() |
| 2101 | logits = engine.forward(0) |
| 2102 | tok = int(np.argmax(logits)) |
| 2103 | for _ in range(5): |
| 2104 | logits = engine.forward(tok) |
| 2105 | tok = int(np.argmax(logits)) |
| 2106 | |
| 2107 | # Benchmark |
| 2108 | times = [] |
| 2109 | for _ in range(n_gen): |
| 2110 | t0 = time.perf_counter() |
| 2111 | logits = engine.forward(tok) |
| 2112 | elapsed = time.perf_counter() - t0 |
| 2113 | times.append(elapsed * 1000) |
| 2114 | tok = int(np.argmax(logits)) |
| 2115 | |
| 2116 | times.sort() |
| 2117 | median = times[len(times)//2] |
| 2118 | avg = sum(times) / len(times) |
| 2119 | print(f"\n{'='*60}") |
| 2120 | print(f"TurboEngine v7-MoE Benchmark") |
| 2121 | print(f"{'='*60}") |
| 2122 | print(f"Model: {model}") |
| 2123 | print(f"Threads: {t}") |
| 2124 | print(f"Tokens gen: {n_gen}") |
| 2125 | print(f"{'─'*60}") |
| 2126 | print(f"Median: {median:.1f} ms/tok ({1000.0/median:.1f} tok/s)") |
| 2127 | print(f"Average: {avg:.1f} ms/tok ({1000.0/avg:.1f} tok/s)") |
| 2128 | print(f"Min: {min(times):.1f} ms/tok ({1000.0/min(times):.1f} tok/s)") |
| 2129 | print(f"Max: {max(times):.1f} ms/tok ({1000.0/max(times):.1f} tok/s)") |
| 2130 | print(f"{'='*60}") |
| 2131 | |
| 2132 | # Compare with llama.cpp baseline |
| 2133 | print(f"\nllama.cpp reference (Qwen3-30B-A3B Q4_K_M, 32t): ~28.5 tok/s") |
| 2134 | ratio = 1000.0/median / 28.5 |
| 2135 | print(f"MojoLlama custom engine: {ratio*100:.0f}% of llama.cpp speed") |