interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / infer / rope.rs

191 lines · 6476 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Allocation-free Llama-style rotary position embeddings.
17
18use super::gemm::{self, KernelError};
19
20fn ln_approx(x: f32) -> f32 {
21 let bits = x.to_bits();
22 let exponent = ((bits >> 23) & 0xff) as i32 - 127;
23 let mantissa = f32::from_bits((bits & 0x7f_ffff) | (127 << 23));
24 let y = (mantissa - 1.0) / (mantissa + 1.0);
25 let y2 = y * y;
26 let series = y * (1.0 + y2 * (1.0 / 3.0 + y2 * (1.0 / 5.0 + y2 * (1.0 / 7.0 + y2 / 9.0))));
27 2.0 * series + exponent as f32 * core::f32::consts::LN_2
28}
29
30/// sin and cos without libm. Reduce to [-pi, pi] (Euclidean, so negative
31/// angles are handled), then fold to [-pi/2, pi/2] using sin(pi - x) = sin(x),
32/// cos(pi - x) = -cos(x), where the Taylor series below is accurate to about
33/// 1e-6. Evaluating them directly out to +/-pi was off by up to ~0.03.
34fn sin_cos_approx(angle: f32) -> (f32, f32) {
35 use core::f32::consts::{FRAC_PI_2, PI, TAU};
36 // Euclidean remainder by hand (f32::rem_euclid needs std).
37 let mut r = (angle + PI) % TAU;
38 if r < 0.0 {
39 r += TAU;
40 }
41 let mut x = r - PI;
42 let mut cos_sign = 1.0;
43 if x > FRAC_PI_2 {
44 x = PI - x;
45 cos_sign = -1.0;
46 } else if x < -FRAC_PI_2 {
47 x = -PI - x;
48 cos_sign = -1.0;
49 }
50 let x2 = x * x;
51 let sin = x
52 * (1.0
53 + x2 * (-1.0 / 6.0
54 + x2 * (1.0 / 120.0 + x2 * (-1.0 / 5040.0 + x2 * (1.0 / 362_880.0)))));
55 let cos = 1.0
56 + x2 * (-1.0 / 2.0
57 + x2 * (1.0 / 24.0 + x2 * (-1.0 / 720.0 + x2 * (1.0 / 40_320.0 - x2 / 3_628_800.0))));
58 (sin, cos_sign * cos)
59}
60
61/// Precomputes rotary cosine and sine values into caller-owned tables.
62///
63/// Tables are row-major with `head_dim / 2` values per position. Each pair
64/// `(x[2*i], x[2*i + 1])` is rotated by the corresponding angle.
65pub fn precompute(
66 theta: f32,
67 head_dim: usize,
68 max_seq_len: usize,
69 cos: &mut [f32],
70 sin: &mut [f32],
71) -> Result<(), KernelError> {
72 if theta <= 0.0 || !theta.is_finite() || head_dim == 0 || !head_dim.is_multiple_of(2) {
73 return Err(KernelError::InvalidParameter);
74 }
75 let pairs = head_dim / 2;
76 let needed = max_seq_len.checked_mul(pairs).ok_or(KernelError::Shape)?;
77 if cos.len() < needed || sin.len() < needed {
78 return Err(KernelError::Shape);
79 }
80 for pos in 0..max_seq_len {
81 for pair in 0..pairs {
82 let exponent = (2 * pair) as f32 / head_dim as f32;
83 let frequency = gemm::exp_approx(exponent * ln_approx(theta));
84 let angle = pos as f32 / frequency;
85 let index = pos * pairs + pair;
86 let (sin_value, cos_value) = sin_cos_approx(angle);
87 cos[index] = cos_value;
88 sin[index] = sin_value;
89 }
90 }
91 Ok(())
92}
93
94/// Rotates all query and key heads in place for one sequence position.
95pub fn apply(
96 q: &mut [f32],
97 k: &mut [f32],
98 position: usize,
99 head_dim: usize,
100 cos: &[f32],
101 sin: &[f32],
102) -> Result<(), KernelError> {
103 if head_dim == 0 || !head_dim.is_multiple_of(2) {
104 return Err(KernelError::InvalidParameter);
105 }
106 let pairs = head_dim / 2;
107 let offset = position.checked_mul(pairs).ok_or(KernelError::Shape)?;
108 if !q.len().is_multiple_of(head_dim)
109 || !k.len().is_multiple_of(head_dim)
110 || offset
111 .checked_add(pairs)
112 .is_none_or(|end| end > cos.len() || end > sin.len())
113 {
114 return Err(KernelError::Shape);
115 }
116 rotate(
117 q,
118 head_dim,
119 &cos[offset..offset + pairs],
120 &sin[offset..offset + pairs],
121 );
122 rotate(
123 k,
124 head_dim,
125 &cos[offset..offset + pairs],
126 &sin[offset..offset + pairs],
127 );
128 Ok(())
129}
130
131fn rotate(values: &mut [f32], head_dim: usize, cos: &[f32], sin: &[f32]) {
132 for head in values.chunks_exact_mut(head_dim) {
133 for pair in 0..cos.len() {
134 let even = head[2 * pair];
135 let odd = head[2 * pair + 1];
136 head[2 * pair] = even * cos[pair] - odd * sin[pair];
137 head[2 * pair + 1] = even * sin[pair] + odd * cos[pair];
138 }
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 fn table(dim: usize, len: usize) -> (std::vec::Vec<f32>, std::vec::Vec<f32>) {
147 let mut cos = std::vec![0.0; dim / 2 * len];
148 let mut sin = std::vec![0.0; dim / 2 * len];
149 precompute(500_000.0, dim, len, &mut cos, &mut sin).unwrap();
150 (cos, sin)
151 }
152
153 #[test]
154 fn position_zero_is_identity() {
155 let (cos, sin) = table(4, 3);
156 let mut q = [1.0, 2.0, 3.0, 4.0];
157 let mut k = q;
158 apply(&mut q, &mut k, 0, 4, &cos, &sin).unwrap();
159 assert_eq!(q, [1.0, 2.0, 3.0, 4.0]);
160 assert_eq!(k, q);
161 }
162
163 #[test]
164 fn rotation_preserves_each_pair_norm() {
165 let (cos, sin) = table(4, 3);
166 let mut q = [3.0, 4.0, 5.0, 12.0];
167 let mut k = q;
168 apply(&mut q, &mut k, 2, 4, &cos, &sin).unwrap();
169 for (before, after) in [
170 (25.0, q[0] * q[0] + q[1] * q[1]),
171 (169.0, q[2] * q[2] + q[3] * q[3]),
172 ] {
173 assert!((before - after).abs() < 1e-4);
174 }
175 }
176 #[test]
177 fn sin_cos_matches_std_across_the_circle() {
178 // Review follow-up: accuracy over the whole reduced range, including
179 // negative and large angles (large positions at small frequencies).
180 let mut worst = 0.0f32;
181 let mut a = -50.0f32;
182 while a < 50.0 {
183 let (s, c) = sin_cos_approx(a);
184 worst = worst.max((s - a.sin()).abs()).max((c - a.cos()).abs());
185 a += 0.01;
186 }
187 assert!(worst < 2e-5, "worst error {worst}");
188 let (s, c) = sin_cos_approx(3.0);
189 assert!((s - 3.0f32.sin()).abs() < 2e-5 && (c - 3.0f32.cos()).abs() < 2e-5);
190 }
191}