interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / kernels / norms.mojo

169 lines · 5415 bytes Raw Blame History
1"""MojoLlama Normalization Kernels v2 — stride-8 SIMD loops.
2
3RMSNorm: x / sqrt(mean(x^2) + eps) * weight
4RoPE: rotary position embeddings via complex rotation
5SiLU: x * sigmoid(x) = x / (1 + exp(-x))
6
7All use stride-8 F32x8 loops for full-dimension vectorization.
8Memory layout: pointer-based for interoperability with C kernels.
9"""
10from std.memory.unsafe_pointer import alloc
11from std.math import exp, sqrt, cos, sin, pow
12
13alias F32x8 = SIMD[DType.float32, 8]
14
15# ─── RMSNorm (full-dimension stride-8 SIMD) ────────────────────────────
16
17def rms_norm(
18 x: UnsafePointer[Float32, MutAnyOrigin],
19 weight: UnsafePointer[Float32, MutAnyOrigin],
20 out: UnsafePointer[Float32, MutAnyOrigin],
21 n: Int,
22):
23 """Vectorized RMS norm over full dimension n.
24 Uses F32x8 SIMD for sum-of-squares and output.
25 Matches C kernel's hadd-based reduction pattern.
26 """
27 var ss: Float32 = 0.0
28 var i = 0
29 # SIMD sum of squares
30 while i + 8 <= n:
31 var v = x.load[width=8](i)
32 ss += (v * v).reduce_add()
33 i += 8
34 # Scalar tail
35 while i < n:
36 ss += x.load(i) * x.load(i)
37 i += 1
38 var inv_rms = 1.0 / sqrt(ss / Float32(n) + 1e-6)
39 var inv_v = F32x8(inv_rms)
40 # SIMD output: out[i] = x[i] * inv_rms * weight[i]
41 i = 0
42 while i + 8 <= n:
43 var v = x.load[width=8](i)
44 var w = weight.load[width=8](i)
45 out.store[width=8](i, v * inv_v * w)
46 i += 8
47 while i < n:
48 out.store(i, x.load(i) * inv_rms * weight.load(i))
49 i += 1
50
51# ─── SiLU (full-dimension stride-8, scalar exp) ───────────────────────
52
53def silu(
54 x: UnsafePointer[Float32, MutAnyOrigin],
55 out: UnsafePointer[Float32, MutAnyOrigin],
56 n: Int,
57):
58 """SiLU activation: out[i] = x[i] / (1 + exp(-x[i]))
59 Uses F32x8 load/store, scalar exp per lane (AVX2 has no vector exp).
60 Matches C kernel's approach.
61 """
62 var one = F32x8(1.0)
63 var i = 0
64 while i + 8 <= n:
65 var v = x.load[width=8](i)
66 var result = F32x8()
67 for j in range(8):
68 result[j] = v[j] / (1.0 + exp(-v[j]))
69 out.store[width=8](i, result)
70 i += 8
71 while i < n:
72 var val = x.load(i)
73 out.store(i, val / (1.0 + exp(-val)))
74 i += 1
75
76# ─── RoPE (rotary position embeddings) ────────────────────────────────
77
78def rope(
79 x: UnsafePointer[Float32, MutAnyOrigin],
80 out: UnsafePointer[Float32, MutAnyOrigin],
81 pos: Int, head_dim: Int,
82):
83 """Apply rotary position embeddings.
84 For each pair (x[i], x[i+half]):
85 out[i] = x[i] * cos(pos * freq_i) - x[i+half] * sin(pos * freq_i)
86 out[i+half] = x[i] * sin(pos * freq_i) + x[i+half] * cos(pos * freq_i)
87 where freq_i = 1 / 10000^(2i/d)
88 """
89 var half = head_dim // 2
90 var i = 0
91 while i + 8 <= half:
92 for j in range(8):
93 var idx = Float32(i + j)
94 var freq = 1.0 / pow(10000.0, 2.0 * idx / Float32(head_dim))
95 var angle = Float32(pos) * freq
96 var cos_a = cos(angle)
97 var sin_a = sin(angle)
98 var x0 = x.load(i + j)
99 var x1 = x.load(i + j + half)
100 out.store(i + j, x0 * cos_a - x1 * sin_a)
101 out.store(i + j + half, x0 * sin_a + x1 * cos_a)
102 i += 8
103 while i < half:
104 var idx = Float32(i)
105 var freq = 1.0 / pow(10000.0, 2.0 * idx / Float32(head_dim))
106 var angle = Float32(pos) * freq
107 var cos_a = cos(angle)
108 var sin_a = sin(angle)
109 var x0 = x.load(i)
110 var x1 = x.load(i + half)
111 out.store(i, x0 * cos_a - x1 * sin_a)
112 out.store(i + half, x0 * sin_a + x1 * cos_a)
113 i += 1
114 # Copy remaining dimensions unchanged
115 while i < head_dim:
116 out.store(i, x.load(i))
117 i += 1
118
119# ─── Softmax (stride-8 max/sum, scalar exp) ─────────────────────────────
120
121def softmax(
122 x: UnsafePointer[Float32, MutAnyOrigin],
123 out: UnsafePointer[Float32, MutAnyOrigin],
124 n: Int,
125):
126 """Vectorized softmax: find max (SIMD), exp(x-max) (scalar), normalize (SIMD).
127 Matches C kernel's AVX2 hadd-based max reduction pattern.
128 """
129 # Find max for numerical stability
130 var max_val: Float32 = -1e30
131 var i = 0
132 while i + 8 <= n:
133 var v = x.load[width=8](i)
134 # SIMD max reduction
135 var m = v.reduce_max()
136 if m > max_val: max_val = m
137 i += 8
138 while i < n:
139 if x.load(i) > max_val: max_val = x.load(i)
140 i += 1
141
142 # exp(x - max) and sum
143 var sum: Float32 = 0.0
144 i = 0
145 while i + 8 <= n:
146 var v = x.load[width=8](i)
147 var result = F32x8()
148 for j in range(8):
149 result[j] = exp(v[j] - max_val)
150 out.store[width=8](i, result)
151 sum += result.reduce_add()
152 i += 8
153 while i < n:
154 var val = exp(x.load(i) - max_val)
155 out.store(i, val)
156 sum += val
157 i += 1
158
159 # Normalize
160 var inv_sum = 1.0 / sum
161 var inv_v = F32x8(inv_sum)
162 i = 0
163 while i + 8 <= n:
164 var v = out.load[width=8](i)
165 out.store[width=8](i, v * inv_v)
166 i += 8
167 while i < n:
168 out.store(i, out.load(i) * inv_sum)
169 i += 1