MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / sampling.mojo
| 1 | """MojoLlama Sampling — top-k, top-p, min-p, temperature, repetition penalty. |
| 2 | |
| 3 | llama.cpp's sampling pipeline (ordered as applied): |
| 4 | 1. Repetition penalty: penalize tokens that appeared recently |
| 5 | 2. Temperature: scale logits before sampling |
| 6 | 3. Top-k: keep only top k candidates |
| 7 | 4. Top-p (nucleus): keep smallest set with cumulative prob >= p |
| 8 | 5. Min-p: filter tokens with prob < min_p * max_prob |
| 9 | 6. Greedy/argmax: for temperature=0 |
| 10 | |
| 11 | All operations are SIMD-friendly where possible. |
| 12 | This module provides both F32 array operations (for Mojo kernels) |
| 13 | and Python-callable wrappers (for the server). |
| 14 | """ |
| 15 | |
| 16 | from std.math import exp, log, sqrt |
| 17 | from std.memory.unsafe_pointer import alloc |
| 18 | |
| 19 | |
| 20 | # ─── Temperature Scaling ─────────────────────────────────────────────── |
| 21 | |
| 22 | fn apply_temperature( |
| 23 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 24 | n: Int, |
| 25 | temperature: Float32, |
| 26 | ): |
| 27 | """Scale logits by 1/temperature. temperature=0 → greedy (handled by caller). |
| 28 | Temperature < 1.0 = sharper (more peaked), > 1.0 = flatter (more random). |
| 29 | """ |
| 30 | if temperature < 1e-10: |
| 31 | return # Caller should use argmax for greedy |
| 32 | |
| 33 | var inv_temp = 1.0 / temperature |
| 34 | var inv_v = SIMD[DType.float32, 1](inv_temp) |
| 35 | var i = 0 |
| 36 | while i + 8 <= n: |
| 37 | var v = logits.load[width=8](i) |
| 38 | logits.store[width=8](i, v * inv_v) |
| 39 | i += 8 |
| 40 | while i < n: |
| 41 | logits.store(i, logits.load(i) * inv_temp) |
| 42 | i += 1 |
| 43 | |
| 44 | |
| 45 | # ─── Softmax ──────────────────────────────────────────────────────────── |
| 46 | |
| 47 | fn softmax_inplace( |
| 48 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 49 | n: Int, |
| 50 | ): |
| 51 | """In-place softmax: converts logits to probabilities. |
| 52 | Uses online max for numerical stability. |
| 53 | """ |
| 54 | # Find max |
| 55 | var max_val: Float32 = -1e30 |
| 56 | var i = 0 |
| 57 | while i + 8 <= n: |
| 58 | var v = logits.load[width=8](i) |
| 59 | var m = v.reduce_max() |
| 60 | if m > max_val: max_val = m |
| 61 | i += 8 |
| 62 | while i < n: |
| 63 | if logits.load(i) > max_val: max_val = logits.load(i) |
| 64 | i += 1 |
| 65 | |
| 66 | # Exp and sum |
| 67 | var sum: Float32 = 0.0 |
| 68 | i = 0 |
| 69 | while i + 8 <= n: |
| 70 | var v = logits.load[width=8](i) |
| 71 | var result = SIMD[DType.float32, 8]() |
| 72 | for j in range(8): |
| 73 | result[j] = exp(v[j] - max_val) |
| 74 | logits.store[width=8](i, result) |
| 75 | sum += result.reduce_add() |
| 76 | i += 8 |
| 77 | while i < n: |
| 78 | var val = exp(logits.load(i) - max_val) |
| 79 | logits.store(i, val) |
| 80 | sum += val |
| 81 | i += 1 |
| 82 | |
| 83 | # Normalize |
| 84 | var inv_sum = 1.0 / sum |
| 85 | var inv_v = SIMD[DType.float32, 8](inv_sum) |
| 86 | i = 0 |
| 87 | while i + 8 <= n: |
| 88 | var v = logits.load[width=8](i) |
| 89 | logits.store[width=8](i, v * inv_v) |
| 90 | i += 8 |
| 91 | while i < n: |
| 92 | logits.store(i, logits.load(i) * inv_sum) |
| 93 | i += 1 |
| 94 | |
| 95 | |
| 96 | # ─── Repetition Penalty ──────────────────────────────────────────────── |
| 97 | |
| 98 | fn apply_repetition_penalty( |
| 99 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 100 | n: Int, |
| 101 | recent_tokens: UnsafePointer[Int32, MutAnyOrigin], # recently generated token IDs |
| 102 | n_recent: Int, # number of recent tokens |
| 103 | penalty: Float32, # >1.0 reduces repetition, <1.0 increases |
| 104 | ): |
| 105 | """Apply repetition penalty to logits of recently seen tokens. |
| 106 | penalty > 1.0: makes recent tokens less likely (default: 1.0 = no effect) |
| 107 | penalty < 1.0: makes recent tokens more likely (dangerous!) |
| 108 | |
| 109 | llama.cpp-style: divide positive logits by penalty, multiply negative by penalty. |
| 110 | This makes recently seen tokens with positive logits much less likely. |
| 111 | """ |
| 112 | if penalty < 1e-10 or penalty == 1.0: |
| 113 | return |
| 114 | |
| 115 | for i in range(n_recent): |
| 116 | var token_id = recent_tokens.load(i) |
| 117 | if token_id >= 0 and token_id < n: |
| 118 | var logit = logits.load(token_id) |
| 119 | if logit > 0.0: |
| 120 | logits.store(token_id, logit / penalty) |
| 121 | else: |
| 122 | logits.store(token_id, logit * penalty) |
| 123 | |
| 124 | |
| 125 | # ─── Top-K Filtering ──────────────────────────────────────────────────── |
| 126 | |
| 127 | struct TokenScore: |
| 128 | var id: Int |
| 129 | var score: Float32 |
| 130 | |
| 131 | fn top_k_filter( |
| 132 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 133 | candidates: UnsafePointer[TokenScore, MutAnyOrigin], |
| 134 | n: Int, |
| 135 | k: Int, |
| 136 | ) -> Int: |
| 137 | """Filter to top-k candidates. Sets logits below top-k to -inf. |
| 138 | Returns number of valid candidates (min(k, n)). |
| 139 | |
| 140 | Uses partial sort for O(n) average case instead of O(n log n) full sort. |
| 141 | """ |
| 142 | if k <= 0 or k >= n: |
| 143 | # No filtering needed |
| 144 | for i in range(n): |
| 145 | candidates.store(i, TokenScore(i, logits.load(i))) |
| 146 | return n |
| 147 | |
| 148 | # Find the k-th largest score using selection |
| 149 | # Simple approach: collect all scores, then partial sort |
| 150 | var all_scores = alloc[TokenScore](n) |
| 151 | for i in range(n): |
| 152 | all_scores.store(i, TokenScore(i, logits.load(i))) |
| 153 | |
| 154 | # Partial selection sort: find top k |
| 155 | for i in range(k): |
| 156 | var best_idx = i |
| 157 | var best_score = all_scores.load(i).score |
| 158 | for j in range(i + 1, n): |
| 159 | var s = all_scores.load(j).score |
| 160 | if s > best_score: |
| 161 | best_score = s |
| 162 | best_idx = j |
| 163 | # Swap |
| 164 | if best_idx != i: |
| 165 | var tmp = all_scores.load(i) |
| 166 | all_scores.store(i, all_scores.load(best_idx)) |
| 167 | all_scores.store(best_idx, tmp) |
| 168 | |
| 169 | # Set logits below top-k to -inf |
| 170 | var kth_score = all_scores.load(k - 1).score |
| 171 | for i in range(n): |
| 172 | if logits.load(i) < kth_score: |
| 173 | logits.store(i, -1e30) |
| 174 | |
| 175 | # Copy top-k candidates |
| 176 | for i in range(k): |
| 177 | candidates.store(i, all_scores.load(i)) |
| 178 | |
| 179 | return k |
| 180 | |
| 181 | |
| 182 | # ─── Top-P (Nucleus) Filtering ────────────────────────────────────────── |
| 183 | |
| 184 | fn top_p_filter( |
| 185 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 186 | n: Int, |
| 187 | p: Float32, |
| 188 | ) -> Int: |
| 189 | """Filter to smallest set of tokens with cumulative probability >= p. |
| 190 | Applies AFTER softmax. Sets remaining tokens to -inf, requires re-softmax. |
| 191 | |
| 192 | Returns number of tokens in the nucleus. |
| 193 | """ |
| 194 | if p >= 1.0 or p < 0.0: |
| 195 | return n |
| 196 | |
| 197 | # First apply softmax to get probabilities |
| 198 | softmax_inplace(logits, n) |
| 199 | |
| 200 | # Simple approach: find tokens sorted by probability |
| 201 | # Then find cutoff where cumulative probability >= p |
| 202 | # For efficiency, we sort token IDs by probability |
| 203 | |
| 204 | var indices = alloc[Int](n) |
| 205 | var probs = alloc[Float32](n) |
| 206 | for i in range(n): |
| 207 | indices.store(i, i) |
| 208 | probs.store(i, logits.load(i)) |
| 209 | |
| 210 | # Sort by probability descending (selection sort for small vocab) |
| 211 | for i in range(n): |
| 212 | var best = i |
| 213 | for j in range(i + 1, n): |
| 214 | if probs.load(j) > probs.load(best): |
| 215 | best = j |
| 216 | # Swap |
| 217 | var tmp_idx = indices.load(i) |
| 218 | var tmp_prob = probs.load(i) |
| 219 | indices.store(i, indices.load(best)) |
| 220 | probs.store(i, probs.load(best)) |
| 221 | indices.store(best, tmp_idx) |
| 222 | probs.store(best, tmp_prob) |
| 223 | |
| 224 | # Find nucleus cutoff |
| 225 | var cumsum: Float32 = 0.0 |
| 226 | var cutoff = n |
| 227 | for i in range(n): |
| 228 | cumsum += probs.load(i) |
| 229 | if cumsum >= p: |
| 230 | cutoff = i + 1 |
| 231 | break |
| 232 | |
| 233 | # Set all tokens outside nucleus to -inf |
| 234 | # First, build a set of nucleus token IDs |
| 235 | for i in range(n): |
| 236 | logits.store(i, -1e30) # zero all |
| 237 | |
| 238 | for i in range(cutoff): |
| 239 | var idx = indices.load(i) |
| 240 | logits.store(idx, probs.load(i)) |
| 241 | |
| 242 | # Re-normalize (don't need full softmax, just divide by sum) |
| 243 | var nucleus_sum: Float32 = 0.0 |
| 244 | for i in range(n): |
| 245 | if logits.load(i) > -1e29: |
| 246 | nucleus_sum += logits.load(i) |
| 247 | |
| 248 | var inv_sum = 1.0 / nucleus_sum |
| 249 | for i in range(n): |
| 250 | if logits.load(i) > -1e29: |
| 251 | logits.store(i, logits.load(i) * inv_sum) |
| 252 | else: |
| 253 | logits.store(i, 0.0) |
| 254 | |
| 255 | return cutoff |
| 256 | |
| 257 | |
| 258 | # ─── Min-P Filtering ──────────────────────────────────────────────────── |
| 259 | |
| 260 | fn min_p_filter( |
| 261 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 262 | n: Int, |
| 263 | min_p: Float32, |
| 264 | ) -> Int: |
| 265 | """Filter tokens with probability < min_p * max_probability. |
| 266 | min_p=0.05 means: remove all tokens with prob < 5% of the top token's prob. |
| 267 | Must be called AFTER softmax. |
| 268 | """ |
| 269 | if min_p <= 0.0 or min_p >= 1.0: |
| 270 | return n |
| 271 | |
| 272 | # Find max probability |
| 273 | softmax_inplace(logits, n) |
| 274 | var max_prob: Float32 = 0.0 |
| 275 | for i in range(n): |
| 276 | var p = logits.load(i) |
| 277 | if p > max_prob: max_prob = p |
| 278 | |
| 279 | var threshold = max_prob * min_p |
| 280 | var count = 0 |
| 281 | |
| 282 | # Zero out tokens below threshold |
| 283 | for i in range(n): |
| 284 | if logits.load(i) >= threshold: |
| 285 | count += 1 |
| 286 | else: |
| 287 | logits.store(i, 0.0) |
| 288 | |
| 289 | # Re-normalize |
| 290 | var sum: Float32 = 0.0 |
| 291 | for i in range(n): |
| 292 | sum += logits.load(i) |
| 293 | var inv_sum = 1.0 / sum |
| 294 | for i in range(n): |
| 295 | if logits.load(i) > 0.0: |
| 296 | logits.store(i, logits.load(i) * inv_sum) |
| 297 | |
| 298 | return count |
| 299 | |
| 300 | |
| 301 | # ─── Greedy Sampling (argmax) ─────────────────────────────────────────── |
| 302 | |
| 303 | fn sample_greedy( |
| 304 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 305 | n: Int, |
| 306 | ) -> Int: |
| 307 | """Return the token with the highest logit (greedy/argmax decoding).""" |
| 308 | var best_id = 0 |
| 309 | var best_score = logits.load(0) |
| 310 | for i in range(1, n): |
| 311 | var s = logits.load(i) |
| 312 | if s > best_score: |
| 313 | best_score = s |
| 314 | best_id = i |
| 315 | return best_id |
| 316 | |
| 317 | |
| 318 | # ─── Random Sampling ──────────────────────────────────────────────────── |
| 319 | |
| 320 | fn sample_random( |
| 321 | probs: UnsafePointer[Float32, MutAnyOrigin], # must be softmaxed |
| 322 | n: Int, |
| 323 | rng_state: UInt64, |
| 324 | ) -> (Int, UInt64): |
| 325 | """Sample from probability distribution using PCG-style LCG. |
| 326 | Returns (token_id, new_rng_state). |
| 327 | """ |
| 328 | # Simple LCG: state = state * 6364136223846793005 + 1442695040888963407 |
| 329 | rng_state = rng_state * 6364136223846793005 + 1442695040888963407 |
| 330 | # Convert to float in [0, 1) |
| 331 | var rand_val = Float32((rng_state >> 11) & 0x1FFFFF) / Float32(0x1FFFFF) |
| 332 | |
| 333 | # Cumulative sampling |
| 334 | var cumsum: Float32 = 0.0 |
| 335 | for i in range(n): |
| 336 | cumsum += probs.load(i) |
| 337 | if cumsum >= rand_val: |
| 338 | return (i, rng_state) |
| 339 | |
| 340 | # Fallback: last token |
| 341 | return (n - 1, rng_state) |
| 342 | |
| 343 | |
| 344 | # ─── Full Sampling Pipeline ──────────────────────────────────────────── |
| 345 | |
| 346 | struct SamplingConfig: |
| 347 | var temperature: Float32 |
| 348 | var top_k: Int |
| 349 | var top_p: Float32 |
| 350 | var min_p: Float32 |
| 351 | var repetition_penalty: Float32 |
| 352 | var repeat_last_n: Int # how many recent tokens to penalize |
| 353 | var seed: UInt64 # RNG seed (0 = random) |
| 354 | |
| 355 | struct SamplingResult: |
| 356 | var token_id: Int |
| 357 | var prob: Float32 # probability of chosen token |
| 358 | var n_candidates: Int # tokens considered after filtering |
| 359 | |
| 360 | |
| 361 | fn sample( |
| 362 | logits: UnsafePointer[Float32, MutAnyOrigin], |
| 363 | n: Int, |
| 364 | config: SamplingConfig, |
| 365 | recent_tokens: UnsafePointer[Int32, MutAnyOrigin], |
| 366 | n_recent: Int, |
| 367 | ) -> SamplingResult: |
| 368 | """Complete sampling pipeline matching llama.cpp's sampling order: |
| 369 | 1. Repetition penalty |
| 370 | 2. Temperature scaling |
| 371 | 3. Top-k filtering |
| 372 | 4. Softmax |
| 373 | 5. Top-p (nucleus) filtering |
| 374 | 6. Min-p filtering |
| 375 | 7. Sample (greedy if temperature=0, random otherwise) |
| 376 | """ |
| 377 | var result = SamplingResult(0, 0.0, n) |
| 378 | |
| 379 | # 1. Repetition penalty |
| 380 | apply_repetition_penalty(logits, n, recent_tokens, n_recent, config.repetition_penalty) |
| 381 | |
| 382 | # 2. Temperature |
| 383 | if config.temperature < 1e-10: |
| 384 | # Greedy: just argmax |
| 385 | result.token_id = sample_greedy(logits, n) |
| 386 | result.prob = 1.0 |
| 387 | result.n_candidates = 1 |
| 388 | return result |
| 389 | |
| 390 | apply_temperature(logits, n, config.temperature) |
| 391 | |
| 392 | # 3. Top-k (before softmax for efficiency) |
| 393 | var candidates = alloc[TokenScore](n) |
| 394 | var n_valid = top_k_filter(logits, candidates, n, config.top_k) |
| 395 | result.n_candidates = n_valid |
| 396 | |
| 397 | # 4. Softmax |
| 398 | softmax_inplace(logits, n) |
| 399 | |
| 400 | # 5. Top-p (nucleus) |
| 401 | if config.top_p < 1.0: |
| 402 | n_valid = top_p_filter(logits, n, config.top_p) |
| 403 | result.n_candidates = n_valid |
| 404 | |
| 405 | # 6. Min-p |
| 406 | if config.min_p > 0.0: |
| 407 | n_valid = min_p_filter(logits, n, config.min_p) |
| 408 | result.n_candidates = n_valid |
| 409 | |
| 410 | # 7. Sample |
| 411 | var rng = config.seed |
| 412 | if rng == 0: |
| 413 | rng = 42 # Default seed |
| 414 | |
| 415 | var (token_id, new_rng) = sample_random(logits, n, rng) |
| 416 | result.token_id = token_id |
| 417 | result.prob = logits.load(token_id) |
| 418 | |
| 419 | return result |