MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / speculative.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Speculative decoding — draft (TinyLlama 1.1B) + target (Qwen3-30B-A3B). |
| 3 | |
| 4 | Both models run in the SAME tokenizer space (Qwen3 tokenizer). |
| 5 | Draft output is clamped to [0, 31999] to stay within TinyLlama's embedding range. |
| 6 | Accepted tokens are decoded via Qwen3 tokenizer. |
| 7 | |
| 8 | Algorithm: |
| 9 | 1. Draft model generates K candidate tokens autoregressively. |
| 10 | 2. Target model verifies each candidate via argmax comparison on its logits. |
| 11 | 3. Accept the longest prefix that matches (draft token == target argmax). |
| 12 | 4. If all K accepted, draft generates K more (bonus speculation). |
| 13 | 5. If rejected at position i, target takes over from position i. |
| 14 | |
| 15 | Usage: |
| 16 | OMP_NUM_THREADS=32 python3 -u speculative.py "Your prompt" [max_tokens] [K] |
| 17 | |
| 18 | Prints: "Draft: X tok, Accepted: Y tok, Acceptance rate: Z%" |
| 19 | """ |
| 20 | import sys, os, time |
| 21 | import numpy as np |
| 22 | |
| 23 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "kernels")) |
| 24 | from turbo_engine_v77 import TurboEngineV77 |
| 25 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 26 | |
| 27 | DRAFT_PATH = "/tmp/tl-Q4_0.gguf" |
| 28 | TARGET_PATH = "/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf" |
| 29 | TOKENIZER_PATH = "/tmp/qwen3-tokenizer/" |
| 30 | DRAFT_CLAMP_MAX = 31999 # TinyLlama vocab = 32000, safe clamp |
| 31 | |
| 32 | |
| 33 | def _ensure_imports(): |
| 34 | """Lazy-load tokenizer after path setup.""" |
| 35 | from transformers import AutoTokenizer |
| 36 | return AutoTokenizer.from_pretrained(TOKENIZER_PATH) |
| 37 | |
| 38 | |
| 39 | def speculative_generate( |
| 40 | prompt: str, |
| 41 | max_tokens: int = 100, |
| 42 | K: int = 5, |
| 43 | draft_model_path: str = DRAFT_PATH, |
| 44 | target_model_path: str = TARGET_PATH, |
| 45 | n_threads: int = 32, |
| 46 | verbose: bool = True, |
| 47 | ) -> str: |
| 48 | """Speculative decoding: draft proposes, target verifies. |
| 49 | |
| 50 | Key design decisions: |
| 51 | - Both models loaded in-process as TurboEngine* instances. |
| 52 | - Target's tokenizer (Qwen3) is used for all text <-> token conversion. |
| 53 | - Draft receives tokens clipped to its vocabulary range [0, 31999]. |
| 54 | - KV cache is checkpointed before verification for clean rollback. |
| 55 | """ |
| 56 | os.environ["OMP_NUM_THREADS"] = str(n_threads) |
| 57 | |
| 58 | tokenizer = _ensure_imports() |
| 59 | bos = tokenizer.bos_token_id or 1 |
| 60 | eos = tokenizer.eos_token_id or 2 |
| 61 | |
| 62 | # ---- Load engines ------------------------------------------------------------ |
| 63 | if verbose: |
| 64 | print(f"Loading draft model from {draft_model_path}...", flush=True) |
| 65 | t0 = time.perf_counter() |
| 66 | draft = TurboEngineV77(draft_model_path, n_threads) |
| 67 | draft_vocab = draft.vocab_size |
| 68 | if verbose: |
| 69 | print(f" Draft loaded in {time.perf_counter()-t0:.1f}s (vocab={draft_vocab})", flush=True) |
| 70 | |
| 71 | if verbose: |
| 72 | print(f"Loading target model from {target_model_path}...", flush=True) |
| 73 | t0 = time.perf_counter() |
| 74 | target = TurboEngineV7MoE(target_model_path, n_threads) |
| 75 | target_vocab = target.vocab_size |
| 76 | if verbose: |
| 77 | print(f" Target loaded in {time.perf_counter()-t0:.1f}s (vocab={target_vocab})", flush=True) |
| 78 | |
| 79 | # ---- Tokenize prompt with Qwen3 tokenizer (same space for both models) -------- |
| 80 | ids = tokenizer.encode(prompt) |
| 81 | if not ids: |
| 82 | ids = [bos] |
| 83 | prompt_len = len(ids) |
| 84 | |
| 85 | if verbose: |
| 86 | print(f" Prompt: {prompt_len} tokens, max_gen={max_tokens}, K={K}", flush=True) |
| 87 | |
| 88 | # ---- Helpers ------------------------------------------------------------------ |
| 89 | def _safe_clamp(tid: int, clamp_max: int = DRAFT_CLAMP_MAX, fallback: int = 0) -> int: |
| 90 | """Clamp token id to valid range for TinyLlama embedding.""" |
| 91 | if 0 <= tid <= clamp_max: |
| 92 | return tid |
| 93 | return fallback |
| 94 | |
| 95 | def _safe_tid(tid: int, vocab_size: int, fallback: int = 0) -> int: |
| 96 | """Clamp token id to valid range for the given model's vocabulary.""" |
| 97 | if 0 <= tid < vocab_size: |
| 98 | return tid |
| 99 | return fallback |
| 100 | |
| 101 | def _sample(logits: np.ndarray) -> int: |
| 102 | """Greedy argmax sampling with NaN handling.""" |
| 103 | safe = np.nan_to_num(logits, nan=-1e10, posinf=1e10, neginf=-1e10) |
| 104 | return int(np.argmax(safe)) |
| 105 | |
| 106 | def _prefill_draft(engine, token_ids): |
| 107 | """Prefill draft engine with Qwen3 token IDs, safely clipped to draft vocab.""" |
| 108 | engine.reset() |
| 109 | for tid in token_ids: |
| 110 | # Clip to TinyLlama's embedding range |
| 111 | safe = _safe_clamp(tid) |
| 112 | engine.forward(safe) |
| 113 | |
| 114 | def _prefill_target(engine, token_ids): |
| 115 | """Prefill target engine with Qwen3 token IDs.""" |
| 116 | engine.reset() |
| 117 | for tid in token_ids: |
| 118 | safe = _safe_tid(tid, engine.vocab_size) |
| 119 | engine.forward(safe) |
| 120 | |
| 121 | def _save_target_state(): |
| 122 | """Checkpoint target KV cache for potential rollback.""" |
| 123 | return { |
| 124 | "kv_k": target.kv_k.copy(), |
| 125 | "kv_v": target.kv_v.copy(), |
| 126 | "kv_len": target.kv_len.copy(), |
| 127 | "pos": target.pos, |
| 128 | } |
| 129 | |
| 130 | def _restore_target_state(state): |
| 131 | """Restore target KV cache from a checkpoint.""" |
| 132 | target.kv_k[:] = state["kv_k"] |
| 133 | target.kv_v[:] = state["kv_v"] |
| 134 | target.kv_len[:] = state["kv_len"] |
| 135 | target.pos = state["pos"] |
| 136 | |
| 137 | # Prefill both engines with the SAME prompt IDs (Qwen3 tokenizer space) |
| 138 | _prefill_draft(draft, ids) |
| 139 | _prefill_target(target, ids) |
| 140 | |
| 141 | generated_ids = [] |
| 142 | total_draft = 0 |
| 143 | total_accepted = 0 |
| 144 | |
| 145 | # Track the last token ID that both models agree on |
| 146 | last_prompt_tid = ids[-1] if ids else bos |
| 147 | |
| 148 | # ---- Main loop ---------------------------------------------------------------- |
| 149 | while len(generated_ids) < max_tokens: |
| 150 | k_this = min(K, max_tokens - len(generated_ids)) |
| 151 | |
| 152 | # ---- Step 1: Draft proposes K candidates ---------------------------------- |
| 153 | candidates = [] |
| 154 | for _ in range(k_this): |
| 155 | # Use the last accepted/generated token as input to draft |
| 156 | prev_tid = _safe_clamp( |
| 157 | candidates[-1] if candidates else last_prompt_tid |
| 158 | ) |
| 159 | logits = draft.forward(prev_tid) |
| 160 | tok = _sample(logits) |
| 161 | # Clamp draft output to TinyLlama's embedding range |
| 162 | tok = _safe_clamp(tok) |
| 163 | candidates.append(tok) |
| 164 | total_draft += 1 |
| 165 | if tok == eos: |
| 166 | break |
| 167 | |
| 168 | if not candidates: |
| 169 | break |
| 170 | |
| 171 | # ---- Step 2: Target verifies candidates ----------------------------------- |
| 172 | saved_state = _save_target_state() |
| 173 | |
| 174 | n_accepted = 0 |
| 175 | target_override = None |
| 176 | |
| 177 | for i, cand in enumerate(candidates): |
| 178 | # Forward the candidate through target (interpreted in Qwen3 space) |
| 179 | safe_cand = _safe_tid(cand, target_vocab) |
| 180 | logits = target.forward(safe_cand) |
| 181 | target_best = _sample(logits) |
| 182 | |
| 183 | if target_best == cand: |
| 184 | n_accepted += 1 |
| 185 | else: |
| 186 | # Rejected at position i |
| 187 | _restore_target_state(saved_state) |
| 188 | |
| 189 | # Re-process the accepted prefix |
| 190 | for accepted_tok in candidates[:i]: |
| 191 | target.forward(_safe_tid(accepted_tok, target_vocab)) |
| 192 | |
| 193 | # Process the target's own correction token |
| 194 | target_override = target_best |
| 195 | target.forward(_safe_tid(target_best, target_vocab)) |
| 196 | break |
| 197 | |
| 198 | # ---- Step 3: Update generated text ---------------------------------------- |
| 199 | if n_accepted == len(candidates): |
| 200 | # All K accepted |
| 201 | generated_ids.extend(candidates) |
| 202 | total_accepted += n_accepted |
| 203 | elif n_accepted > 0: |
| 204 | # Partial acceptance: use accepted prefix + target's override |
| 205 | generated_ids.extend(candidates[:n_accepted]) |
| 206 | total_accepted += n_accepted |
| 207 | if target_override is not None: |
| 208 | generated_ids.append(target_override) |
| 209 | total_accepted += 1 |
| 210 | else: |
| 211 | # No candidate accepted |
| 212 | if target_override is not None: |
| 213 | generated_ids.append(target_override) |
| 214 | total_accepted += 1 |
| 215 | else: |
| 216 | # Fallback: generate one token with target directly |
| 217 | logits = target.forward(_safe_tid(0, target_vocab)) |
| 218 | tok = _sample(logits) |
| 219 | generated_ids.append(tok) |
| 220 | |
| 221 | # Update last_prompt_tid for the next round |
| 222 | if generated_ids: |
| 223 | last_prompt_tid = _safe_clamp(generated_ids[-1]) |
| 224 | |
| 225 | # Stop on EOS |
| 226 | if eos in generated_ids: |
| 227 | break |
| 228 | |
| 229 | # ---- Report ------------------------------------------------------------------- |
| 230 | text = tokenizer.decode(generated_ids, skip_special_tokens=True) |
| 231 | |
| 232 | acceptance_rate = ( |
| 233 | (total_accepted / total_draft * 100) if total_draft > 0 else 0 |
| 234 | ) |
| 235 | print( |
| 236 | f"Draft: {total_draft} tok, Accepted: {total_accepted} tok, " |
| 237 | f"Acceptance rate: {acceptance_rate:.0f}%", |
| 238 | flush=True, |
| 239 | ) |
| 240 | return text |
| 241 | |
| 242 | |
| 243 | if __name__ == "__main__": |
| 244 | prompt = sys.argv[1] if len(sys.argv) > 1 else "The capital of France is" |
| 245 | max_tokens = int(sys.argv[2]) if len(sys.argv) > 2 else 50 |
| 246 | K = int(sys.argv[3]) if len(sys.argv) > 3 else 5 |
| 247 | |
| 248 | t0 = time.perf_counter() |
| 249 | text = speculative_generate(prompt, max_tokens, K, verbose=True) |
| 250 | elapsed = time.perf_counter() - t0 |
| 251 | print(f"\nGenerated ({len(text.split())} words) in {elapsed:.1f}s:") |
| 252 | print(text[:500]) |