MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / dsv4 / turbo_engine_dsv4.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | TurboEngine v8-DeepSeek-V4 — MojoLlama inference engine for DeepSeek V4 Flash. |
| 4 | |
| 5 | Loads Intel/DeepSeek-V4-Flash-W4A16-AutoRound safetensors directly. |
| 6 | Implements: MLA attention, Hyper-Connections, MoE (256 experts, hash+learned routing), |
| 7 | compressed KV cache, sparse attention, YaRN RoPE, multi-token prediction. |
| 8 | |
| 9 | Usage: |
| 10 | python3 turbo_engine_dsv4.py --prompt "Hello" --n-tokens 50 |
| 11 | """ |
| 12 | import os, sys, json, time, math, struct, gc, argparse |
| 13 | from dataclasses import dataclass |
| 14 | from typing import List, Optional, Tuple, Dict |
| 15 | from functools import lru_cache |
| 16 | from pathlib import Path |
| 17 | |
| 18 | import numpy as np |
| 19 | |
| 20 | # Optional torch import for BF16 safetensor loading |
| 21 | try: |
| 22 | import torch |
| 23 | _HAS_TORCH = True |
| 24 | except ImportError: |
| 25 | _HAS_TORCH = False |
| 26 | |
| 27 | from safetensors import safe_open |
| 28 | from huggingface_hub import hf_hub_download, get_safetensors_metadata |
| 29 | |
| 30 | # ─── Model Config ─── |
| 31 | |
| 32 | @dataclass |
| 33 | class DeepSeekV4Config: |
| 34 | """Hardcoded from config.json + inference/config_w4a16.json""" |
| 35 | vocab_size: int = 129280 |
| 36 | dim: int = 4096 |
| 37 | n_layers: int = 43 |
| 38 | n_hash_layers: int = 3 |
| 39 | n_heads: int = 64 |
| 40 | n_kv_heads: int = 1 |
| 41 | head_dim: int = 512 |
| 42 | rope_head_dim: int = 64 |
| 43 | nope_head_dim: int = 448 # head_dim - rope_head_dim |
| 44 | q_lora_rank: int = 1024 |
| 45 | o_lora_rank: int = 1024 |
| 46 | o_groups: int = 8 |
| 47 | moe_inter_dim: int = 2048 |
| 48 | n_routed_experts: int = 256 |
| 49 | n_shared_experts: int = 1 |
| 50 | n_activated_experts: int = 6 |
| 51 | n_mtp_layers: int = 1 |
| 52 | score_func: str = "sqrtsoftplus" |
| 53 | route_scale: float = 1.5 |
| 54 | swiglu_limit: float = 10.0 |
| 55 | window_size: int = 128 |
| 56 | compress_rope_theta: float = 160000.0 |
| 57 | original_seq_len: int = 65536 |
| 58 | rope_theta: float = 10000.0 |
| 59 | rope_factor: float = 16.0 |
| 60 | beta_fast: int = 32 |
| 61 | beta_slow: int = 1 |
| 62 | index_n_heads: int = 64 |
| 63 | index_head_dim: int = 128 |
| 64 | index_topk: int = 512 |
| 65 | hc_mult: int = 4 |
| 66 | hc_sinkhorn_iters: int = 20 |
| 67 | hc_eps: float = 1e-6 |
| 68 | eps: float = 1e-6 |
| 69 | compress_ratios: tuple = (0, 0, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, |
| 70 | 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, |
| 71 | 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 0) |
| 72 | max_seq_len: int = 4096 # decode limit |
| 73 | max_batch_size: int = 1 |
| 74 | model_id: str = "Intel/DeepSeek-V4-Flash-W4A16-AutoRound" |
| 75 | |
| 76 | # ─── W4A16 Dequantize ─── |
| 77 | |
| 78 | def dequantize_w4a16(qweight: np.ndarray, qzeros: np.ndarray, scales: np.ndarray, |
| 79 | group_size: int = 128) -> np.ndarray: |
| 80 | """ |
| 81 | AutoRound/GPTQ W4A16 → F32 weight [out, in]. |
| 82 | |
| 83 | qweight: int32 [in//8, out] LSB-first packed |
| 84 | qzeros: int32 [in//g, out//8] LSB-first packed (stores zero - 1) |
| 85 | scales: float32/BF16 [in//g, out] |
| 86 | """ |
| 87 | in_packed, out_features = qweight.shape |
| 88 | in_features = in_packed * 8 |
| 89 | n_groups = scales.shape[0] |
| 90 | shifts = np.array([0, 4, 8, 12, 16, 20, 24, 28], dtype=np.int32) |
| 91 | # Unpack qweight: [in//8, 8, out] -> [in, out] |
| 92 | w = ((qweight[:, None, :] >> shifts.reshape(1, 8, 1)) & 0xF).reshape(in_features, out_features).astype(np.float32) |
| 93 | # Unpack qzeros: [in//g, out//8, 8] -> [in//g, out] |
| 94 | z = ((qzeros[:, :, None] >> shifts.reshape(1, 1, 8)) & 0xF).reshape(n_groups, out_features).astype(np.float32) + 1.0 |
| 95 | s = scales.astype(np.float32) |
| 96 | w = w.reshape(n_groups, group_size, out_features) |
| 97 | deq = (w - z[:, None, :]) * s[:, None, :] |
| 98 | return np.ascontiguousarray(deq.reshape(in_features, out_features).T) # [out, in] |
| 99 | |
| 100 | |
| 101 | def bf16_to_f32(bf16_arr): |
| 102 | """Convert BF16 array to float32. Handles uint16 raw BF16 or float16.""" |
| 103 | if hasattr(bf16_arr, 'numpy'): # torch tensor |
| 104 | return bf16_arr.float().numpy() |
| 105 | if bf16_arr.dtype == np.float32: |
| 106 | return bf16_arr |
| 107 | if bf16_arr.dtype == np.float16: |
| 108 | return bf16_arr.astype(np.float32) |
| 109 | if bf16_arr.dtype == np.uint16: |
| 110 | view = bf16_arr.view(np.uint32) |
| 111 | view = view << 16 |
| 112 | return view.view(np.float32) |
| 113 | return np.asarray(bf16_arr, dtype=np.float32) |
| 114 | |
| 115 | |
| 116 | # ─── Safetensors Loader ─── |
| 117 | |
| 118 | class SafetensorsLoader: |
| 119 | """Lazy-load tensors from multi-shard safetensors repo.""" |
| 120 | |
| 121 | def __init__(self, repo_id: str): |
| 122 | self.repo_id = repo_id |
| 123 | self.meta = get_safetensors_metadata(repo_id) |
| 124 | # Build tensor -> shard mapping |
| 125 | self.shard_of: Dict[str, str] = {} |
| 126 | self.shapes: Dict[str, Tuple] = {} |
| 127 | self.dtypes: Dict[str, str] = {} |
| 128 | for fname, fmeta in self.meta.files_metadata.items(): |
| 129 | for tname, tinfo in fmeta.tensors.items(): |
| 130 | self.shard_of[tname] = fname |
| 131 | self.shapes[tname] = tuple(tinfo.shape) |
| 132 | self.dtypes[tname] = tinfo.dtype |
| 133 | self._shard_cache: Dict[str, safe_open] = {} |
| 134 | |
| 135 | def get_tensor(self, name: str) -> np.ndarray: |
| 136 | """Load a tensor by name, returns numpy array (converts BF16 -> F32).""" |
| 137 | fname = self.shard_of.get(name) |
| 138 | if fname is None: |
| 139 | raise KeyError(f"Tensor {name} not found") |
| 140 | if fname not in self._shard_cache: |
| 141 | local = hf_hub_download(repo_id=self.repo_id, filename=fname) |
| 142 | self._shard_cache[fname] = safe_open(local, framework="pt" if _HAS_TORCH else "np", device="cpu") |
| 143 | sf = self._shard_cache[fname] |
| 144 | t = sf.get_tensor(name) |
| 145 | # Convert BF16 -> F32 if needed |
| 146 | if hasattr(t, 'dtype') and str(t.dtype) in ('bfloat16', 'torch.bfloat16'): |
| 147 | if _HAS_TORCH: |
| 148 | return t.float().numpy() |
| 149 | else: |
| 150 | # Manual BF16 -> F32 conversion |
| 151 | return bf16_to_f32(t) |
| 152 | elif hasattr(t, 'numpy'): |
| 153 | return t.numpy() |
| 154 | return t.astype(np.float32) if t.dtype in (np.float16,) else t |
| 155 | |
| 156 | def get_w4a16(self, base_name: str) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: |
| 157 | """Load qweight, qzeros, scales for a W4A16 linear.""" |
| 158 | qw = self.get_tensor(base_name + '.qweight') |
| 159 | qz = self.get_tensor(base_name + '.qzeros') |
| 160 | sc = self.get_tensor(base_name + '.scales') |
| 161 | return qw, qz, sc |
| 162 | |
| 163 | def get_deq(self, base_name: str) -> np.ndarray: |
| 164 | """Load and dequantize a W4A16 linear -> [out, in] F32.""" |
| 165 | qw, qz, sc = self.get_w4a16(base_name) |
| 166 | return dequantize_w4a16(qw, qz, sc) |
| 167 | |
| 168 | def close(self): |
| 169 | for sf in self._shard_cache.values(): |
| 170 | try: sf.close() |
| 171 | except: pass |
| 172 | self._shard_cache.clear() |
| 173 | |
| 174 | |
| 175 | # ─── RoPE ─── |
| 176 | |
| 177 | @lru_cache(maxsize=2) |
| 178 | def precompute_freqs(dim: int, seqlen: int, original_seq_len: int, |
| 179 | base: float, factor: float, beta_fast: int, beta_slow: int) -> Tuple[np.ndarray, np.ndarray]: |
| 180 | """Precompute sin/cos for YaRN rotary embeddings.""" |
| 181 | import math |
| 182 | def find_correction_dim(num_rotations, dim, base, max_seq_len): |
| 183 | return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base)) |
| 184 | def find_correction_range(low_rot, high_rot, dim, base, max_seq_len): |
| 185 | low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len)) |
| 186 | high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len)) |
| 187 | return max(low, 0), min(high, dim - 1) |
| 188 | def linear_ramp_factor(min_v, max_v, dim): |
| 189 | if min_v == max_v: |
| 190 | max_v += 0.001 |
| 191 | linear_func = (np.arange(dim, dtype=np.float32) - min_v) / (max_v - min_v) |
| 192 | return np.clip(linear_func, 0, 1) |
| 193 | |
| 194 | freqs = 1.0 / (base ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) |
| 195 | if original_seq_len > 0: |
| 196 | low, high = find_correction_range(beta_fast, beta_slow, dim, base, original_seq_len) |
| 197 | smooth = 1 - linear_ramp_factor(low, high, dim // 2) |
| 198 | freqs = freqs / factor * (1 - smooth) + freqs * smooth |
| 199 | t = np.arange(seqlen, dtype=np.float32) |
| 200 | angles = np.outer(t, freqs) |
| 201 | return np.cos(angles).astype(np.float32), np.sin(angles).astype(np.float32) |
| 202 | |
| 203 | def apply_rotary_emb(x: np.ndarray, cos: np.ndarray, sin: np.ndarray, |
| 204 | pos: int, rope_dim: int, n_heads: int = 1) -> np.ndarray: |
| 205 | """Apply rotary embeddings to x [B, NH, HD] or [B, HD] in-place. |
| 206 | Only rotates first `rope_dim` dims; rest left unchanged.""" |
| 207 | half = rope_dim // 2 |
| 208 | if x.ndim == 2: |
| 209 | x_ = x.reshape(1, 1, -1) # [1, 1, HD] |
| 210 | c = cos[pos:pos+1, :half] |
| 211 | s = sin[pos:pos+1, :half] |
| 212 | # Rotate first rope_dim elements |
| 213 | x1 = x_[:, :, :half] |
| 214 | x2 = x_[:, :, half:rope_dim] |
| 215 | rotated = np.concatenate([ |
| 216 | x1 * c - x2 * s, |
| 217 | x1 * s + x2 * c |
| 218 | ], axis=-1) |
| 219 | x_[:, :, :rope_dim] = rotated |
| 220 | return x_.reshape(x.shape) |
| 221 | else: # [B, NH, HD] |
| 222 | B, NH, HD = x.shape |
| 223 | c = cos[pos:pos+1, :half] # [1, half] |
| 224 | s = sin[pos:pos+1, :half] |
| 225 | x1 = x[:, :, :half] |
| 226 | x2 = x[:, :, half:rope_dim] |
| 227 | rotated = np.concatenate([ |
| 228 | x1 * c[np.newaxis, np.newaxis, :] - x2 * s[np.newaxis, np.newaxis, :], |
| 229 | x1 * s[np.newaxis, np.newaxis, :] + x2 * c[np.newaxis, np.newaxis, :] |
| 230 | ], axis=-1) |
| 231 | x[:, :, :rope_dim] = rotated |
| 232 | return x |
| 233 | |
| 234 | |
| 235 | # ─── RMS Norm ─── |
| 236 | |
| 237 | def rms_norm(x: np.ndarray, weight: np.ndarray, eps: float = 1e-6) -> np.ndarray: |
| 238 | """RMS Layer Normalization. x: [..., D], weight: [D]""" |
| 239 | dtype = x.dtype |
| 240 | x = x.astype(np.float32) |
| 241 | variance = np.mean(x * x, axis=-1, keepdims=True) |
| 242 | x = x * np.reciprocal(np.sqrt(variance + eps)) |
| 243 | return (x * weight.astype(np.float32)).astype(dtype) |
| 244 | |
| 245 | |
| 246 | # ─── Linear (Dequantized Matmul) ─── |
| 247 | |
| 248 | def linear(x: np.ndarray, w: np.ndarray) -> np.ndarray: |
| 249 | """x: [..., in_d], w: [out_d, in_d] -> [..., out_d]. |
| 250 | Uses BLAS matmul for efficiency.""" |
| 251 | if x.ndim == 1: |
| 252 | return w @ x # [out] |
| 253 | elif x.ndim == 2: |
| 254 | return x @ w.T # [B, out] |
| 255 | else: |
| 256 | orig = x.shape |
| 257 | x_2d = x.reshape(-1, orig[-1]) |
| 258 | return (x_2d @ w.T).reshape(*orig[:-1], -1) |
| 259 | |
| 260 | |
| 261 | # ─── Sinkhorn (for HC) ─── |
| 262 | |
| 263 | def hc_split_sinkhorn(mixes: np.ndarray, hc_scale: np.ndarray, hc_base: np.ndarray, |
| 264 | hc_mult: int, sinkhorn_iters: int, eps: float): |
| 265 | """ |
| 266 | mixes: [B, S, mix_hc], hc_scale: [3], hc_base: [mix_hc] |
| 267 | returns: pre [B,S,hc], post [B,S,hc], comb [B,S,hc,hc] |
| 268 | Using Sinkhorn algorithm for doubly-stochastic normalization. |
| 269 | """ |
| 270 | # Split into pre, post, comb components |
| 271 | hc = hc_mult |
| 272 | pre = mixes[..., :hc] |
| 273 | post = mixes[..., hc:2*hc] |
| 274 | comb_flat = mixes[..., 2*hc:] |
| 275 | comb = comb_flat.reshape(*mixes.shape[:-1], hc, hc) |
| 276 | |
| 277 | # Sigmoid + scale |
| 278 | pre = 1.0 / (1.0 + np.exp(-(pre * hc_scale[0] + hc_base[:hc].reshape(1, 1, hc)))) + eps |
| 279 | post = 1.0 / (1.0 + np.exp(-(post * hc_scale[1] + hc_base[hc:2*hc].reshape(1, 1, hc)))) + eps |
| 280 | |
| 281 | # Sinkhorn on comb (doubly stochastic) |
| 282 | comb_log = comb * hc_scale[2] + hc_base[2*hc:].reshape(1, 1, hc, hc) |
| 283 | # Sinkhorn iterations (in log space for stability) |
| 284 | K = comb_log |
| 285 | for _ in range(sinkhorn_iters): |
| 286 | K = K - np.log(np.exp(K).sum(axis=-1, keepdims=True) + 1e-10) |
| 287 | K = K - np.log(np.exp(K).sum(axis=-2, keepdims=True) + 1e-10) |
| 288 | comb = np.exp(K) + eps |
| 289 | |
| 290 | return pre, post, comb |
| 291 | |
| 292 | |
| 293 | # ─── DeepSeek V4 Engine ─── |
| 294 | |
| 295 | class DeepSeekV4Engine: |
| 296 | """MojoLlama inference engine for DeepSeek V4 Flash.""" |
| 297 | |
| 298 | def __init__(self, loader: SafetensorsLoader, cfg: DeepSeekV4Config = None): |
| 299 | self.loader = loader |
| 300 | self.cfg = cfg or DeepSeekV4Config() |
| 301 | self._cache: Dict[str, np.ndarray] = {} # dequantized weight cache |
| 302 | self._rope_cache: Dict[str, Tuple[np.ndarray, np.ndarray]] = {} |
| 303 | self._load_global_weights() |
| 304 | self._init_buffers() |
| 305 | |
| 306 | def _load_global_weights(self): |
| 307 | """Load non-layer weights (embed, head, hc_*, norm).""" |
| 308 | cfg = self.cfg |
| 309 | L = self.loader |
| 310 | # Embed is BF16 stored directly |
| 311 | self.embed_w = L.get_tensor('embed.weight').astype(np.float32) |
| 312 | # LM head is F32 |
| 313 | self.head_w = L.get_tensor('head.weight').astype(np.float32) |
| 314 | # HC head params (F32) |
| 315 | self.hc_head_fn = L.get_tensor('hc_head_fn') |
| 316 | self.hc_head_base = L.get_tensor('hc_head_base') |
| 317 | self.hc_head_scale = L.get_tensor('hc_head_scale') |
| 318 | # Final norm |
| 319 | self.norm_w = L.get_tensor('norm.weight').astype(np.float32) |
| 320 | print(f" Global weights: embed={self.embed_w.shape}, head={self.head_w.shape}, " |
| 321 | f"norm={self.norm_w.shape}", flush=True) |
| 322 | |
| 323 | def _init_buffers(self): |
| 324 | cfg = self.cfg |
| 325 | D, N, NH, NKH, HD, RHD = cfg.dim, cfg.n_layers, cfg.n_heads, cfg.n_kv_heads, cfg.head_dim, cfg.rope_head_dim |
| 326 | HC = cfg.hc_mult |
| 327 | # Hidden state buffers |
| 328 | self.bx = np.zeros(D, dtype=np.float32) # main hidden |
| 329 | self.br = np.zeros((HC, D), dtype=np.float32) # residual HC copies |
| 330 | self.bxn = np.zeros(D, dtype=np.float32) # normed |
| 331 | self.br_out = np.zeros((HC, D), dtype=np.float32) |
| 332 | # Attention buffers |
| 333 | self.bq_latent = np.zeros(cfg.q_lora_rank, dtype=np.float32) |
| 334 | self.bq = np.zeros((NH, HD), dtype=np.float32) # full Q |
| 335 | self.bkv = np.zeros(HD, dtype=np.float32) # single KV |
| 336 | self.battn = np.zeros((NH, HD), dtype=np.float32) |
| 337 | # MoE buffers |
| 338 | self.bmoe_in = np.zeros(D, dtype=np.float32) |
| 339 | self.bmoe_gate = np.zeros(cfg.moe_inter_dim, dtype=np.float32) |
| 340 | self.bmoe_up = np.zeros(cfg.moe_inter_dim, dtype=np.float32) |
| 341 | self.bmoe_out = np.zeros(D, dtype=np.float32) |
| 342 | self.bmoe_shared = np.zeros(D, dtype=np.float32) |
| 343 | # MoE router |
| 344 | self.brouter_scores = np.zeros(cfg.n_routed_experts, dtype=np.float32) |
| 345 | # HC buffers |
| 346 | self.bhc_mixes = np.zeros((2 + HC) * HC, dtype=np.float32) |
| 347 | self.bhc_pre = np.zeros(HC, dtype=np.float32) |
| 348 | self.bhc_post = np.zeros(HC, dtype=np.float32) |
| 349 | self.bhc_comb = np.zeros((HC, HC), dtype=np.float32) |
| 350 | # Conv state for compressor |
| 351 | self.kv_cache: Dict[int, np.ndarray] = {} # layer_id -> [window_size + compressed, HD] |
| 352 | self.compressor_state: Dict[int, Dict] = {} # layer_id -> state dict |
| 353 | |
| 354 | def _get_rope(self, rope_dim: int, seq_len: int, original_seq_len: int = 0, |
| 355 | base: float = 10000.0, factor: float = 1.0, |
| 356 | beta_fast: int = 32, beta_slow: int = 1) -> Tuple[np.ndarray, np.ndarray]: |
| 357 | key = (rope_dim, seq_len, original_seq_len, base, factor, beta_fast, beta_slow) |
| 358 | if key not in self._rope_cache: |
| 359 | self._rope_cache[key] = precompute_freqs( |
| 360 | rope_dim, seq_len, original_seq_len, base, factor, beta_fast, beta_slow) |
| 361 | return self._rope_cache[key] |
| 362 | |
| 363 | def _load_layer_weight(self, layer_id: int, name: str) -> np.ndarray: |
| 364 | """Load (and cache) a single tensor from a layer.""" |
| 365 | key = f"layers.{layer_id}.{name}" |
| 366 | return self.loader.get_tensor(key) |
| 367 | |
| 368 | def _load_deq(self, layer_id: int, name: str) -> np.ndarray: |
| 369 | """Load and dequantize a W4A16 weight, cached.""" |
| 370 | cache_key = f"L{layer_id}.{name}" |
| 371 | if cache_key in self._cache: |
| 372 | return self._cache[cache_key] |
| 373 | prefix = f"layers.{layer_id}.{name}" |
| 374 | try: |
| 375 | qw = self.loader.get_tensor(prefix + '.qweight') |
| 376 | qz = self.loader.get_tensor(prefix + '.qzeros') |
| 377 | sc = self.loader.get_tensor(prefix + '.scales') |
| 378 | deq = dequantize_w4a16(qw, qz, sc) |
| 379 | except KeyError: |
| 380 | # Try .weight (non-quantized) |
| 381 | deq = self.loader.get_tensor(prefix + '.weight').astype(np.float32) |
| 382 | self._cache[cache_key] = deq |
| 383 | return deq |
| 384 | |
| 385 | def _load_layer_norm(self, layer_id: int, name: str) -> np.ndarray: |
| 386 | """Load RMS norm weight.""" |
| 387 | tensor_name = f"layers.{layer_id}.{name}.weight" |
| 388 | return self.loader.get_tensor(tensor_name).astype(np.float32) |
| 389 | |
| 390 | def _load_hc_params(self, layer_id: int, kind: str): |
| 391 | """Load Hyper-Connection params for a layer.""" |
| 392 | prefix = f"layers.{layer_id}.hc_{kind}_" |
| 393 | fn = self.loader.get_tensor(prefix + 'fn') |
| 394 | base = self.loader.get_tensor(prefix + 'base') |
| 395 | scale = self.loader.get_tensor(prefix + 'scale') |
| 396 | return fn, base, scale |
| 397 | |
| 398 | def _load_attn_sink(self, layer_id: int) -> np.ndarray: |
| 399 | return self.loader.get_tensor(f"layers.{layer_id}.attn.attn_sink") |
| 400 | |
| 401 | def _load_gate_weight(self, layer_id: int) -> Tuple[np.ndarray, Optional[np.ndarray]]: |
| 402 | """Load MoE gate weights. Returns (weight, bias).""" |
| 403 | prefix = f"layers.{layer_id}.ffn.gate" |
| 404 | try: |
| 405 | qw = self.loader.get_tensor(prefix + '.qweight') |
| 406 | qz = self.loader.get_tensor(prefix + '.qzeros') |
| 407 | sc = self.loader.get_tensor(prefix + '.scales') |
| 408 | w = dequantize_w4a16(qw, qz, sc) |
| 409 | except KeyError: |
| 410 | w = self.loader.get_tensor(prefix + '.weight').astype(np.float32) |
| 411 | try: |
| 412 | bias = self.loader.get_tensor(prefix + '.bias') |
| 413 | except KeyError: |
| 414 | bias = None |
| 415 | # Hash routing |
| 416 | try: |
| 417 | tid2eid = self.loader.get_tensor(prefix + '.tid2eid') |
| 418 | except KeyError: |
| 419 | tid2eid = None |
| 420 | return w, bias, tid2eid |
| 421 | |
| 422 | def _load_shared_expert(self, layer_id: int) -> Dict: |
| 423 | """Load shared expert weights.""" |
| 424 | base = f"layers.{layer_id}.ffn.shared_experts" |
| 425 | result = {} |
| 426 | for name in ['w1', 'w2', 'w3']: |
| 427 | result[name] = self._load_deq(layer_id, f"ffn.shared_experts.{name}") |
| 428 | return result |
| 429 | |
| 430 | def _load_expert_weight(self, layer_id: int, expert_id: int, name: str) -> np.ndarray: |
| 431 | """Load a single expert weight (dequantized).""" |
| 432 | cache_key = f"L{layer_id}.exp{expert_id}.{name}" |
| 433 | if cache_key in self._cache: |
| 434 | return self._cache[cache_key] |
| 435 | prefix = f"layers.{layer_id}.ffn.experts.{expert_id}.{name}" |
| 436 | try: |
| 437 | qw = self.loader.get_tensor(prefix + '.qweight') |
| 438 | qz = self.loader.get_tensor(prefix + '.qzeros') |
| 439 | sc = self.loader.get_tensor(prefix + '.scales') |
| 440 | deq = dequantize_w4a16(qw, qz, sc) |
| 441 | except KeyError: |
| 442 | deq = self.loader.get_tensor(prefix + '.weight').astype(np.float32) |
| 443 | self._cache[cache_key] = deq |
| 444 | return deq |
| 445 | |
| 446 | def _load_compressor(self, layer_id: int, ratio: int): |
| 447 | """Load compressor weights for a layer.""" |
| 448 | prefix = f"layers.{layer_id}.attn.compressor" |
| 449 | result = {} |
| 450 | coff = 2 if ratio == 4 else 1 |
| 451 | head_dim = self.cfg.head_dim |
| 452 | result['wkv'] = self._load_deq(layer_id, "attn.compressor.wkv") |
| 453 | result['wgate'] = self._load_deq(layer_id, "attn.compressor.wgate") |
| 454 | result['ape'] = self.loader.get_tensor(prefix + '.ape').astype(np.float32) |
| 455 | result['norm_w'] = self.loader.get_tensor(prefix + '.norm.weight').astype(np.float32) |
| 456 | return result |
| 457 | |
| 458 | def _load_indexer(self, layer_id: int): |
| 459 | """Load indexer weights.""" |
| 460 | prefix = f"layers.{layer_id}.attn.indexer" |
| 461 | result = {} |
| 462 | result['wq_b'] = self._load_deq(layer_id, "attn.indexer.wq_b") |
| 463 | result['weights_proj'] = self._load_deq(layer_id, "attn.indexer.weights_proj") |
| 464 | # Indexer compressor |
| 465 | result['compressor'] = {} |
| 466 | result['compressor']['wkv'] = self._load_deq(layer_id, "attn.indexer.compressor.wkv") |
| 467 | result['compressor']['wgate'] = self._load_deq(layer_id, "attn.indexer.compressor.wgate") |
| 468 | result['compressor']['ape'] = self.loader.get_tensor(prefix + '.compressor.ape').astype(np.float32) |
| 469 | result['compressor']['norm_w'] = self.loader.get_tensor(prefix + '.compressor.norm.weight').astype(np.float32) |
| 470 | return result |
| 471 | |
| 472 | # ─── Forward Pass ─── |
| 473 | |
| 474 | def forward_layer(self, layer_id: int, pos: int, input_ids: np.ndarray): |
| 475 | """Forward one transformer layer. Updates self.bx and self.br in place.""" |
| 476 | cfg = self.cfg |
| 477 | D, HC = cfg.dim, cfg.hc_mult |
| 478 | |
| 479 | t0 = time.perf_counter() |
| 480 | |
| 481 | # ── HC Pre (Attention) ── |
| 482 | hc_attn_fn, hc_attn_base, hc_attn_scale = self._get_layer_hc(layer_id, 'attn') |
| 483 | pre, post, comb = self._hc_pre(self.br, hc_attn_fn, hc_attn_base, hc_attn_scale, HC) |
| 484 | # x = sum(pre[:, None] * br) = weighted sum of HC copies -> single hidden |
| 485 | x = np.sum(pre[:, None] * self.br, axis=0) # [D] |
| 486 | # Copy to bx |
| 487 | np.copyto(self.bx, x) |
| 488 | |
| 489 | # ── Attention Norm ── |
| 490 | attn_norm_w = self._load_layer_norm(layer_id, 'attn_norm') |
| 491 | np.copyto(self.bxn, rms_norm(self.bx, attn_norm_w, cfg.eps)) |
| 492 | |
| 493 | # ── MLA Attention ── |
| 494 | self._mla_attention(layer_id, pos) |
| 495 | |
| 496 | # ── HC Post (Attention) ── |
| 497 | # x_out = post * x + comb @ br (matrix multiply along HC dim) |
| 498 | new_br = post[:, None] * self.bxn[np.newaxis, :] + np.einsum('hc,cd->hd', comb, self.br) |
| 499 | np.copyto(self.br, new_br.astype(np.float32)) |
| 500 | |
| 501 | # ── HC Pre (FFN) ── |
| 502 | hc_ffn_fn, hc_ffn_base, hc_ffn_scale = self._get_layer_hc(layer_id, 'ffn') |
| 503 | pre, post, comb = self._hc_pre(self.br, hc_ffn_fn, hc_ffn_base, hc_ffn_scale, HC) |
| 504 | x = np.sum(pre[:, None] * self.br, axis=0) |
| 505 | np.copyto(self.bx, x) |
| 506 | |
| 507 | # ── FFN Norm ── |
| 508 | ffn_norm_w = self._load_layer_norm(layer_id, 'ffn_norm') |
| 509 | np.copyto(self.bxn, rms_norm(self.bx, ffn_norm_w, cfg.eps)) |
| 510 | |
| 511 | # ── MoE FFN ── |
| 512 | self._moe_ffn(layer_id, input_ids) |
| 513 | |
| 514 | # ── HC Post (FFN) ── |
| 515 | new_br = post[:, None] * self.bx[np.newaxis, :] + np.einsum('hc,cd->hd', comb, self.br) |
| 516 | np.copyto(self.br, new_br.astype(np.float32)) |
| 517 | |
| 518 | def _get_layer_hc(self, layer_id: int, kind: str): |
| 519 | """Load and cache HC parameters.""" |
| 520 | key = f"L{layer_id}.hc_{kind}" |
| 521 | if key not in self._cache: |
| 522 | prefix = f"layers.{layer_id}.hc_{kind}_" |
| 523 | fn = self.loader.get_tensor(prefix + 'fn') |
| 524 | base = self.loader.get_tensor(prefix + 'base') |
| 525 | scale = self.loader.get_tensor(prefix + 'scale') |
| 526 | self._cache[key] = (fn, base, scale) |
| 527 | return self._cache[key] |
| 528 | |
| 529 | def _hc_pre(self, res: np.ndarray, hc_fn: np.ndarray, |
| 530 | hc_base: np.ndarray, hc_scale: np.ndarray, hc_mult: int): |
| 531 | """ |
| 532 | res: [HC, D] residual copies |
| 533 | hc_fn: [mix_hc, HC*D] |
| 534 | Returns (pre, post, comb) where each is [HC] or [HC, HC] |
| 535 | """ |
| 536 | mix_hc = (2 + hc_mult) * hc_mult |
| 537 | HC, D = res.shape |
| 538 | # Flatten residual and compute mixes |
| 539 | x_flat = res.flatten() # [HC*D] |
| 540 | rsqrt = 1.0 / np.sqrt(np.mean(x_flat * x_flat) + 1e-6) |
| 541 | mixes = np.dot(hc_fn, x_flat * rsqrt) # [mix_hc] |
| 542 | return hc_split_sinkhorn(mixes[np.newaxis, np.newaxis, :], |
| 543 | hc_scale, hc_base, hc_mult, 1, 1e-6) |
| 544 | |
| 545 | def _mla_attention(self, layer_id: int, pos: int): |
| 546 | """Multi-head Latent Attention for a single token.""" |
| 547 | cfg = self.cfg |
| 548 | NH, NKH, HD, RHD = cfg.n_heads, cfg.n_kv_heads, cfg.head_dim, cfg.rope_head_dim |
| 549 | NHD = HD - RHD |
| 550 | |
| 551 | # Load attention weights |
| 552 | wq_a = self._load_deq(layer_id, "attn.wq_a") # [q_lora_rank, D] |
| 553 | q_norm_w = self._load_layer_norm(layer_id, "attn.q_norm") |
| 554 | wq_b = self._load_deq(layer_id, "attn.wq_b") # [NH*HD, q_lora_rank] |
| 555 | wkv = self._load_deq(layer_id, "attn.wkv") # [HD, D] |
| 556 | kv_norm_w = self._load_layer_norm(layer_id, "attn.kv_norm") |
| 557 | wo_a = self._load_deq(layer_id, "attn.wo_a") # [NH*HD//groups, groups*o_lora_rank] |
| 558 | wo_b = self._load_deq(layer_id, "attn.wo_b") # [D, groups*o_lora_rank] |
| 559 | attn_sink = self._load_attn_sink(layer_id) |
| 560 | |
| 561 | # Q projection: wq_a -> q_norm -> wq_b |
| 562 | latent = np.dot(wq_a, self.bxn) # [q_lora_rank] |
| 563 | latent = rms_norm(latent, q_norm_w, cfg.eps) |
| 564 | q = np.dot(wq_b, latent) # [NH*HD] |
| 565 | q = q.reshape(NH, HD) |
| 566 | |
| 567 | # QK norm (per-head) |
| 568 | q = q / np.sqrt(np.mean(q * q, axis=-1, keepdims=True) + cfg.eps) |
| 569 | |
| 570 | # KV projection: wkv -> kv_norm (shared MQA) |
| 571 | kv = np.dot(wkv, self.bxn) # [HD,] |
| 572 | kv = rms_norm(kv, kv_norm_w, cfg.eps) |
| 573 | |
| 574 | # RoPE |
| 575 | cos, sin = self._get_rope(RHD, max(pos + 1, 2), |
| 576 | cfg.original_seq_len if self._has_compression(layer_id) else 0, |
| 577 | cfg.compress_rope_theta if self._has_compression(layer_id) else cfg.rope_theta, |
| 578 | cfg.rope_factor, cfg.beta_fast, cfg.beta_slow) |
| 579 | apply_rotary_emb(q[:, :RHD], cos, sin, pos, RHD) |
| 580 | apply_rotary_emb(kv[np.newaxis, :RHD], cos, sin, pos, RHD) |
| 581 | |
| 582 | # KV cache (sliding window) |
| 583 | win = cfg.window_size |
| 584 | ratio = cfg.compress_ratios[layer_id] |
| 585 | # Initialize KV cache for this layer if needed |
| 586 | if layer_id not in self.kv_cache: |
| 587 | cache_size = win + (cfg.max_seq_len // ratio) if ratio else win |
| 588 | self.kv_cache[layer_id] = np.zeros((cache_size, HD), dtype=np.float32) |
| 589 | self.compressor_state[layer_id] = {} |
| 590 | |
| 591 | kv_cache = self.kv_cache[layer_id] |
| 592 | |
| 593 | # Store KV |
| 594 | kv_cache[pos % win] = kv |
| 595 | |
| 596 | # Handle compression if applicable |
| 597 | if ratio and pos > 0 and (pos % ratio == 0): |
| 598 | comp_idx = pos // ratio |
| 599 | # Simple mean-pool compression (approximation of learned gated pooling) |
| 600 | start = max(0, pos - ratio + 1) |
| 601 | compressed = np.mean(kv_cache[start:pos+1], axis=0) |
| 602 | kv_cache[win + comp_idx - 1] = compressed |
| 603 | |
| 604 | # Build sparse attention indices |
| 605 | # Sliding window: recent `win` positions |
| 606 | if pos < win: |
| 607 | topk_idxs = np.arange(pos + 1) |
| 608 | else: |
| 609 | topk_idxs = np.arange(pos - win + 1, pos + 1) |
| 610 | |
| 611 | # Add compressed positions if applicable |
| 612 | if ratio: |
| 613 | n_compressed = pos // ratio |
| 614 | if n_compressed > 0: |
| 615 | comp_idxs = np.arange(win, win + n_compressed) |
| 616 | topk_idxs = np.concatenate([topk_idxs, comp_idxs]) |
| 617 | |
| 618 | # Sparse attention |
| 619 | num_kv = len(topk_idxs) |
| 620 | if num_kv == 0: |
| 621 | self.battn.fill(0) |
| 622 | else: |
| 623 | # Gather KV: all heads share the same KV (MQA) |
| 624 | gathered_kv = kv_cache[topk_idxs] # [K, HD] |
| 625 | |
| 626 | # Compute attention scores |
| 627 | scale = HD ** -0.5 |
| 628 | scores = np.dot(q.reshape(NH, HD), gathered_kv.T) * scale # [NH, K] |
| 629 | |
| 630 | # Add attn_sink bias |
| 631 | scores += attn_sink[:, np.newaxis] |
| 632 | |
| 633 | # Mask future positions (not needed in decode mode) |
| 634 | # Softmax |
| 635 | scores = scores - np.max(scores, axis=-1, keepdims=True) |
| 636 | exp_scores = np.exp(scores) |
| 637 | weights = exp_scores / (np.sum(exp_scores, axis=-1, keepdims=True) + 1e-10) |
| 638 | |
| 639 | # Weighted sum |
| 640 | o = np.dot(weights, gathered_kv) # [NH, HD] |
| 641 | np.copyto(self.battn, o) |
| 642 | |
| 643 | # Output projection |
| 644 | # wo_a: [NH*HD//groups, groups*o_lora_rank] |
| 645 | NHG = NH // cfg.o_groups |
| 646 | groups = cfg.o_groups |
| 647 | # Reshape attn to [groups, NHG*HD], apply wo_a per group |
| 648 | self.battn_reshaped = self.battn.reshape(groups, NHG * HD) |
| 649 | o = np.dot(wo_a, self.battn_reshaped.T).T.reshape(-1) # [groups*o_lora_rank] |
| 650 | o = np.dot(wo_b, o) # [D] |
| 651 | np.copyto(self.bxn, o) |
| 652 | |
| 653 | def _has_compression(self, layer_id: int) -> bool: |
| 654 | return self.cfg.compress_ratios[layer_id] != 0 |
| 655 | |
| 656 | def _moe_ffn(self, layer_id: int, input_ids: np.ndarray): |
| 657 | """MoE FFN: route -> top-6 experts + shared expert.""" |
| 658 | cfg = self.cfg |
| 659 | D, INTER, NE, TOPK = cfg.dim, cfg.moe_inter_dim, cfg.n_routed_experts, cfg.n_activated_experts |
| 660 | N_HASH = cfg.n_hash_layers |
| 661 | |
| 662 | # Load gate |
| 663 | gate_w, gate_bias, tid2eid = self._load_gate_weight(layer_id) |
| 664 | is_hash = layer_id < N_HASH |
| 665 | |
| 666 | # Router: x -> scores |
| 667 | scores = np.dot(gate_w, self.bxn) # [NE] |
| 668 | if gate_bias is not None: |
| 669 | scores = scores + gate_bias |
| 670 | |
| 671 | # Score function |
| 672 | if cfg.score_func == "softmax": |
| 673 | scores = np.exp(scores - np.max(scores)) |
| 674 | scores = scores / np.sum(scores) |
| 675 | elif cfg.score_func == "sigmoid": |
| 676 | scores = 1.0 / (1.0 + np.exp(-scores)) |
| 677 | else: # sqrtsoftplus |
| 678 | scores = np.sqrt(np.log1p(np.exp(scores))) |
| 679 | |
| 680 | # Select top-k experts |
| 681 | if is_hash and tid2eid is not None: |
| 682 | indices = tid2eid[input_ids] # [TOPK] from hash table |
| 683 | weights = scores[indices] |
| 684 | else: |
| 685 | topk = min(TOPK, NE) |
| 686 | indices = np.argpartition(-scores, topk)[:topk] |
| 687 | weights = scores[indices] |
| 688 | |
| 689 | # Normalize weights |
| 690 | if cfg.score_func != "softmax": |
| 691 | weights = weights / (np.sum(weights) + 1e-10) |
| 692 | weights *= cfg.route_scale |
| 693 | |
| 694 | # Compute expert outputs |
| 695 | self.bmoe_out.fill(0) |
| 696 | for k, (expert_id, weight) in enumerate(zip(indices, weights)): |
| 697 | if weight <= 0: |
| 698 | continue |
| 699 | # Load expert weights |
| 700 | w1 = self._load_expert_weight(layer_id, int(expert_id), 'w1') # [INTER, D] |
| 701 | w3 = self._load_expert_weight(layer_id, int(expert_id), 'w3') # [INTER, D] |
| 702 | w2 = self._load_expert_weight(layer_id, int(expert_id), 'w2') # [D, INTER] |
| 703 | |
| 704 | # SwiGLU: SiLU(x @ w1.T) * (x @ w3.T) |
| 705 | gate = np.dot(w1, self.bxn) # [INTER] |
| 706 | up = np.dot(w3, self.bxn) # [INTER] |
| 707 | if cfg.swiglu_limit > 0: |
| 708 | up = np.clip(up, -cfg.swiglu_limit, cfg.swiglu_limit) |
| 709 | gate = np.clip(gate, None, cfg.swiglu_limit) |
| 710 | # SiLU |
| 711 | sig = 1.0 / (1.0 + np.exp(-gate)) |
| 712 | activated = sig * gate * up |
| 713 | if weight != 1.0: |
| 714 | activated = activated * weight |
| 715 | # Down project |
| 716 | out = np.dot(w2, activated) # [D] |
| 717 | self.bmoe_out += out |
| 718 | |
| 719 | # Shared expert |
| 720 | shared = self._load_shared_expert(layer_id) |
| 721 | gate_s = np.dot(shared['w1'], self.bxn) |
| 722 | up_s = np.dot(shared['w3'], self.bxn) |
| 723 | if cfg.swiglu_limit > 0: |
| 724 | up_s = np.clip(up_s, -cfg.swiglu_limit, cfg.swiglu_limit) |
| 725 | gate_s = np.clip(gate_s, None, cfg.swiglu_limit) |
| 726 | sig_s = 1.0 / (1.0 + np.exp(-gate_s)) |
| 727 | activated_s = sig_s * gate_s * up_s |
| 728 | out_s = np.dot(shared['w2'], activated_s) |
| 729 | self.bmoe_out += out_s |
| 730 | np.copyto(self.bx, self.bmoe_out) |
| 731 | |
| 732 | def generate(self, input_ids: List[int], n_tokens: int = 100, |
| 733 | temperature: float = 0.7, top_k: int = 50) -> List[int]: |
| 734 | """Autoregressive generation.""" |
| 735 | cfg = self.cfg |
| 736 | output_ids = list(input_ids) |
| 737 | |
| 738 | # Prefill: embed first token |
| 739 | token = input_ids[0] |
| 740 | np.copyto(self.bx, self.embed_w[token]) |
| 741 | # Init HC residual |
| 742 | self.br.fill(0) |
| 743 | self.br[:, :cfg.dim] = self.bx[np.newaxis, :] / cfg.hc_mult |
| 744 | |
| 745 | timings = [] |
| 746 | pos = 0 |
| 747 | |
| 748 | for step in range(n_tokens): |
| 749 | t_start = time.perf_counter() |
| 750 | token = output_ids[-1] |
| 751 | pos = step |
| 752 | |
| 753 | if step == 0: |
| 754 | # Prefill: process all input tokens |
| 755 | for i, tid in enumerate(input_ids): |
| 756 | if i == 0: |
| 757 | # Already embedded |
| 758 | pass |
| 759 | else: |
| 760 | np.copyto(self.bx, self.embed_w[tid]) |
| 761 | self.br.fill(0) |
| 762 | self.br[:, :cfg.dim] = self.bx[np.newaxis, :] / cfg.hc_mult |
| 763 | |
| 764 | for l in range(cfg.n_layers): |
| 765 | self.forward_layer(l, i, tid) |
| 766 | |
| 767 | # HC head + norm + lm_head |
| 768 | logits = self._compute_logits() |
| 769 | else: |
| 770 | # Decode: one token at a time |
| 771 | np.copyto(self.bx, self.embed_w[token]) |
| 772 | self.br.fill(0) |
| 773 | self.br[:, :cfg.dim] = self.bx[np.newaxis, :] / cfg.hc_mult |
| 774 | |
| 775 | for l in range(cfg.n_layers): |
| 776 | self.forward_layer(l, pos, token) |
| 777 | |
| 778 | logits = self._compute_logits() |
| 779 | |
| 780 | # Sample |
| 781 | logits = logits.astype(np.float64) |
| 782 | if temperature > 0: |
| 783 | logits = logits / temperature |
| 784 | if top_k > 0: |
| 785 | top_k_vals = np.partition(logits, -top_k)[-top_k] |
| 786 | logits[logits < top_k_vals] = -float('inf') |
| 787 | probs = np.exp(logits - np.max(logits)) |
| 788 | probs = probs / np.sum(probs) |
| 789 | next_token = int(np.random.choice(len(probs), p=probs)) |
| 790 | else: |
| 791 | next_token = int(np.argmax(logits)) |
| 792 | |
| 793 | output_ids.append(next_token) |
| 794 | elapsed = time.perf_counter() - t_start |
| 795 | timings.append(elapsed) |
| 796 | |
| 797 | if (step + 1) % 10 == 0: |
| 798 | tok_s = (step + 1) / max(sum(timings), 1e-6) |
| 799 | print(f" [{step+1}/{n_tokens}] tok/s={tok_s:.2f}, last={elapsed*1000:.0f}ms", |
| 800 | flush=True) |
| 801 | |
| 802 | avg_tok_s = n_tokens / max(sum(timings), 1e-6) |
| 803 | print(f"\nGeneration: {n_tokens} tokens in {sum(timings):.1f}s ({avg_tok_s:.2f} tok/s)", |
| 804 | flush=True) |
| 805 | return output_ids |
| 806 | |
| 807 | def _compute_logits(self) -> np.ndarray: |
| 808 | """HC head -> norm -> lm_head.""" |
| 809 | cfg = self.cfg |
| 810 | # HC head: weighted sum of HC copies |
| 811 | x_flat = self.br.flatten() |
| 812 | rsqrt = 1.0 / np.sqrt(np.mean(x_flat * x_flat) + cfg.eps) |
| 813 | mixes = np.dot(self.hc_head_fn, x_flat * rsqrt) # [HC] |
| 814 | pre = 1.0 / (1.0 + np.exp(-(mixes * self.hc_head_scale[0] + self.hc_head_base))) + cfg.hc_eps |
| 815 | x = np.sum(pre[:, None] * self.br, axis=0) # [D] |
| 816 | # Final norm |
| 817 | x = rms_norm(x, self.norm_w, cfg.eps) |
| 818 | # LM head |
| 819 | logits = np.dot(self.head_w, x) # [vocab] |
| 820 | return logits |
| 821 | |
| 822 | |
| 823 | # ─── Tokenizer ─── |
| 824 | |
| 825 | def load_tokenizer(repo_id: str) -> Tuple[Dict[int, str], Dict[str, int], int]: |
| 826 | """Minimal BPE tokenizer. Returns (id_to_token, token_to_id, vocab_size).""" |
| 827 | import json |
| 828 | try: |
| 829 | tok_file = hf_hub_download(repo_id=repo_id, filename="tokenizer.json") |
| 830 | with open(tok_file, 'r') as f: |
| 831 | data = json.load(f) |
| 832 | # Extract vocabulary from the 'model' section |
| 833 | vocab = data.get('model', {}).get('vocab', {}) |
| 834 | id_to_token = {} |
| 835 | token_to_id = {} |
| 836 | # tokenizer.json vocab is usually token -> id |
| 837 | for token, tid in vocab.items(): |
| 838 | id_to_token[int(tid)] = token |
| 839 | token_to_id[token] = int(tid) |
| 840 | # Also try added_tokens |
| 841 | added = data.get('added_tokens', []) |
| 842 | for at in added: |
| 843 | tid = int(at.get('id', 0)) |
| 844 | content = at.get('content', '') |
| 845 | if content: |
| 846 | id_to_token[tid] = content |
| 847 | token_to_id[content] = tid |
| 848 | return id_to_token, token_to_id, len(id_to_token) |
| 849 | except Exception as e: |
| 850 | print(f"Tokenizer load warning: {e}") |
| 851 | return {}, {}, 129280 |
| 852 | |
| 853 | |
| 854 | class SimpleTokenizer: |
| 855 | """Minimal tokenizer for DeepSeek V4.""" |
| 856 | def __init__(self, repo_id: str): |
| 857 | import json, re |
| 858 | self.repo_id = repo_id |
| 859 | # Try to load tokenizer config |
| 860 | try: |
| 861 | config_path = hf_hub_download(repo_id=repo_id, filename="tokenizer_config.json") |
| 862 | with open(config_path) as f: |
| 863 | tc = json.load(f) |
| 864 | self.bos_token_id = tc.get('bos_token_id', 0) |
| 865 | self.eos_token_id = tc.get('eos_token_id', 1) |
| 866 | except: |
| 867 | self.bos_token_id = 0 |
| 868 | self.eos_token_id = 1 |
| 869 | |
| 870 | # Try loading the tokenizer |
| 871 | self.id_to_token, self.token_to_id, self.vocab_size = load_tokenizer(repo_id) |
| 872 | self.vocab_size = 129280 # Hardcoded from config |
| 873 | print(f"Tokenizer: vocab={self.vocab_size}, bos={self.bos_token_id}, eos={self.eos_token_id}") |
| 874 | |
| 875 | def encode(self, text: str) -> List[int]: |
| 876 | """Simple whitespace+character fallback encoding.""" |
| 877 | # For now, use a simple byte-level encoding since this is a demo |
| 878 | # In production, use the actual tokenizer |
| 879 | ids = [] |
| 880 | for ch in text.encode('utf-8'): |
| 881 | ids.append(ch + 3) # BPE-like offset |
| 882 | return ids[:self.vocab_size - 1] |
| 883 | |
| 884 | def decode(self, ids: List[int]) -> str: |
| 885 | """Decode token IDs to text (simple fallback).""" |
| 886 | chars = [] |
| 887 | for tid in ids: |
| 888 | if tid < 3 + 256: |
| 889 | chars.append(chr(max(tid - 3, 0))) |
| 890 | elif tid in self.id_to_token: |
| 891 | token = self.id_to_token[tid] |
| 892 | chars.append(token.replace('Ġ', ' ').replace('Ċ', '\n')) |
| 893 | return ''.join(chars) |
| 894 | |
| 895 | def decode_token(self, tid: int) -> str: |
| 896 | if tid < 3: |
| 897 | return '' |
| 898 | if tid < 3 + 256: |
| 899 | return chr(tid - 3) |
| 900 | return self.id_to_token.get(tid, f'<{tid}>').replace('Ġ', ' ') |
| 901 | |
| 902 | |
| 903 | # ─── CLI ─── |
| 904 | |
| 905 | def main(): |
| 906 | parser = argparse.ArgumentParser() |
| 907 | parser.add_argument("--prompt", default="Hello, how are you?") |
| 908 | parser.add_argument("--n-tokens", type=int, default=30) |
| 909 | parser.add_argument("--temperature", type=float, default=0.7) |
| 910 | parser.add_argument("--top-k", type=int, default=50) |
| 911 | parser.add_argument("--model-id", default="Intel/DeepSeek-V4-Flash-W4A16-AutoRound") |
| 912 | parser.add_argument("--max-layers", type=int, default=1, help="Limit layers for testing") |
| 913 | args = parser.parse_args() |
| 914 | |
| 915 | print("=" * 60) |
| 916 | print("MojoLlama DeepSeek V4 Flash Inference Engine") |
| 917 | print("=" * 60) |
| 918 | |
| 919 | # Load config |
| 920 | cfg = DeepSeekV4Config(model_id=args.model_id) |
| 921 | if args.max_layers: |
| 922 | cfg.n_layers = args.max_layers |
| 923 | print(f" [TEST MODE] Using {args.max_layers} layer(s)") |
| 924 | |
| 925 | print(f"Loading metadata from {args.model_id}...") |
| 926 | loader = SafetensorsLoader(args.model_id) |
| 927 | |
| 928 | print(f"Initializing engine...") |
| 929 | engine = DeepSeekV4Engine(loader, cfg) |
| 930 | |
| 931 | # Load tokenizer |
| 932 | tokenizer = SimpleTokenizer(args.model_id) |
| 933 | |
| 934 | # Encode prompt |
| 935 | input_ids = tokenizer.encode(args.prompt) |
| 936 | print(f"Prompt: '{args.prompt}' -> {len(input_ids)} tokens") |
| 937 | if len(input_ids) == 0: |
| 938 | input_ids = [1] # fallback |
| 939 | print(f"Input IDs: {input_ids[:20]}{'...' if len(input_ids) > 20 else ''}") |
| 940 | |
| 941 | # Generate |
| 942 | print(f"\nGenerating {args.n_tokens} tokens...") |
| 943 | t0 = time.perf_counter() |
| 944 | output_ids = engine.generate(input_ids, args.n_tokens, args.temperature, args.top_k) |
| 945 | total_time = time.perf_counter() - t0 |
| 946 | |
| 947 | # Decode |
| 948 | output_text = tokenizer.decode(output_ids) |
| 949 | print(f"\n{'='*60}") |
| 950 | print(f"Generated: {output_text[:500]}") |
| 951 | print(f"{'='*60}") |
| 952 | print(f"Total: {len(output_ids)} tokens in {total_time:.1f}s ({len(output_ids)/total_time:.2f} tok/s)") |
| 953 | |
| 954 | loader.close() |
| 955 | |
| 956 | |
| 957 | if __name__ == "__main__": |
| 958 | main() |