Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/mojo_engine/sampling.mojo # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / mojo_engine / sampling.mojo` 120 lines ยท 5093 bytes Raw Blame History 1 # MojoLlama Sampling โ€” Pure Mojo top-k extraction + token sampling 2 # WHAT: quantize_row_q8_0 + top-k logits + sampling functions. 3 # WHY: Replaces logits_topk.c + logits_avx2.c + simd_ops.c. 4 # Final step in text generation โ€” selects which token to emit. 5 # WHEN: May 2026 โ€” pure Mojo port. 6 from std import math 7 from std.algorithm.backend.cpu.parallelize import parallelize 8 9 def encode_f16(f: Float32) -> UInt16: 10 if f == 0.0: return UInt16(0) 11 var sign: UInt16 = 0; var fd = Float64(f) 12 if fd < 0: sign = UInt16(1); fd = -fd 13 var e: Int = 0 14 if fd >= 1.0: 15 while fd >= 2.0: fd *= 0.5; e += 1 16 else: 17 while fd < 1.0: fd *= 2.0; e -= 1 18 var he = e + 15 19 if he < 0: he = 0 20 if he > 31: he = 31 21 var m = Int(fd * 2048.0) 22 if m > 1023: m = 1023 23 return UInt16(Int(sign) << 15 | he << 10 | m) 24 25 def quantize_row_q8_0(x: UnsafePointer[Float32, MutExternalOrigin], 26 q8: UnsafePointer[UInt8, MutExternalOrigin], n: Int): 27 """Quantize f32 vector to Q8_0 format (34 bytes per 32 values).""" 28 var nb = n // 32 29 for b in range(nb): 30 var xo = b * 32; var bo = b * 34 31 var amax: Float32 = 0.0 32 for j in range(32): 33 var v = x.load(xo + j) 34 if v < 0: v = -v 35 if v > amax: amax = v 36 if amax == 0.0: amax = 1.0 37 var d = amax / 127.0; var inv_d = 127.0 / amax 38 var su = encode_f16(d) 39 q8.store(bo, UInt8(su & 0xFF)); q8.store(bo+1, UInt8((su >> 8) & 0xFF)) 40 for j in range(32): 41 var qv = Int32(x.load(xo + j) * inv_d) 42 if qv > 127: qv = 127 43 if qv < -128: qv = -128 44 if qv < 0: qv += 256 45 q8.store(bo + 2 + j, UInt8(qv & 0xFF)) 46 47 def topk_extract(logits: UnsafePointer[Float32, MutExternalOrigin], 48 n_vocab: Int, k: Int, 49 tk_val: UnsafePointer[Float32, MutExternalOrigin], 50 tk_idx: UnsafePointer[Int32, MutExternalOrigin]): 51 """Extract top-k logits using min-heap (parallel arrays for compat).""" 52 var heap_size = 0 53 for i in range(n_vocab): 54 var v = logits.load(i) 55 if heap_size < k: 56 tk_val.store(heap_size, v); tk_idx.store(heap_size, i) 57 heap_size += 1 58 # Sift up 59 var j = heap_size - 1 60 while j > 0: 61 var p = (j - 1) // 2 62 if tk_val.load(j) < tk_val.load(p): 63 var tv = tk_val.load(j); var ti = tk_idx.load(j) 64 tk_val.store(j, tk_val.load(p)); tk_idx.store(j, tk_idx.load(p)) 65 tk_val.store(p, tv); tk_idx.store(p, ti) 66 j = p 67 else: break 68 elif v > tk_val.load(0): 69 tk_val.store(0, v); tk_idx.store(0, i) 70 # Sift down 71 var j = 0 72 while 2 * j + 1 < heap_size: 73 var c = 2 * j + 1 74 if c + 1 < heap_size and tk_val.load(c+1) < tk_val.load(c): c += 1 75 if tk_val.load(j) <= tk_val.load(c): break 76 var tv = tk_val.load(j); var ti = tk_idx.load(j) 77 tk_val.store(j, tk_val.load(c)); tk_idx.store(j, tk_idx.load(c)) 78 tk_val.store(c, tv); tk_idx.store(c, ti) 79 j = c 80 # Sort descending 81 for i in range(heap_size - 1): 82 var max_idx = i 83 for j in range(i + 1, heap_size): 84 if tk_val.load(j) > tk_val.load(max_idx): max_idx = j 85 if max_idx != i: 86 var tv = tk_val.load(i); var ti = tk_idx.load(i) 87 tk_val.store(i, tk_val.load(max_idx)); tk_idx.store(i, tk_idx.load(max_idx)) 88 tk_val.store(max_idx, tv); tk_idx.store(max_idx, ti) 89 90 def sample_argmax(tk_val: UnsafePointer[Float32, MutExternalOrigin], 91 tk_idx: UnsafePointer[Int32, MutExternalOrigin], 92 k: Int) -> Int: 93 """Return index of highest logit (greedy).""" 94 return Int(tk_idx.load(0)) 95 96 def softmax_with_temp(logits: UnsafePointer[Float32, MutExternalOrigin], 97 probs: UnsafePointer[Float32, MutExternalOrigin], 98 n: Int, temperature: Float32): 99 """Compute softmax with temperature.""" 100 var max_val: Float32 = -1e30 101 for i in range(n): 102 if logits.load(i) > max_val: max_val = logits.load(i) 103 var inv_temp = 1.0 / temperature if temperature > 0 else 1e10 104 var sum_exp: Float32 = 0.0 105 for i in range(n): 106 var e = math.exp((logits.load(i) - max_val) * inv_temp) 107 if e > 1e30: e = 1e30 108 probs.store(i, e); sum_exp += e 109 var inv_sum = 1.0 / (sum_exp + 1e-10) 110 for i in range(n): probs.store(i, probs.load(i) * inv_sum) 111 112 def sample_topk(probs: UnsafePointer[Float32, MutExternalOrigin], 113 tk_idx: UnsafePointer[Int32, MutExternalOrigin], 114 k: Int, rng_val: Float32) -> Int: 115 """Sample from top-k distribution.""" 116 var cumsum: Float32 = 0.0 117 for i in range(k): 118 cumsum += probs.load(tk_idx.load(i)) 119 if cumsum > rng_val: return Int(tk_idx.load(i)) 120 return Int(tk_idx.load(k - 1))