Skip to main content

logicaffeine_system/
ntt.rs

1//! ML-KEM (Kyber) negacyclic NTT runtime kernel — the verified scalar reference + AVX2 i16×16
2//! path that compiled LOGOS reaches through the `mlkemNtt` stdlib function. Ported from the
3//! validated `scripts/dev/ntt_simd_proto.rs` (round-trip + AVX2==scalar bit-identical). q = 3329,
4//! R = 2¹⁶, the incomplete 7-level transform over ℤ_q\[X\]/(X²⁵⁶+1). The Montgomery reduction it
5//! uses is kernel-certified (`logicaffeine_kernel::field_algebra::montgomery_reduction_*`).
6//!
7//! Input/output are LOGOS `Int` (i64); coefficients are reduced into [0, q) at the boundary, the
8//! transform runs in i16, and the result is returned reduced into [0, q). On x86-64 with AVX2 the
9//! 16-wide kernel runs (≈49 ns/NTT on a modern core); otherwise the scalar path (≈147 ns).
10
11use crate::kernel_args as args;
12
13const Q: i32 = 3329;
14const QINV: i32 = -3327; // q⁻¹ mod 2¹⁶ (signed i16)
15
16/// Kyber zetas[128] — ζ^bitrev(i) · R mod q, signed, Montgomery form.
17const ZETAS: [i16; 128] = [
18    -1044, -758, -359, -1517, 1493, 1422, 287, 202, -171, 622, 1577, 182, 962, -1202, -1474, 1468,
19    573, -1325, 264, 383, -829, 1458, -1602, -130, -681, 1017, 732, 608, -1542, 411, -205, -1571,
20    1223, 652, -552, 1015, -1293, 1491, -282, -1544, 516, -8, -320, -666, -1618, -1162, 126, 1469,
21    -853, -90, -271, 830, 107, -1421, -247, -951, -398, 961, -1508, -725, 448, -1065, 677, -1275,
22    -1103, 430, 555, 843, -1251, 871, 1550, 105, 422, 587, 177, -235, -291, -460, 1574, 1653, -246,
23    778, 1159, -147, -777, 1483, -602, 1119, -1590, 644, -872, 349, 418, 329, -156, -75, 817, 1097,
24    603, 610, 1322, -1285, -1465, 384, -1215, -136, 1218, -1335, -874, 220, -1187, -1659, -1185,
25    -1530, -1278, 794, -1510, -854, -870, 478, -108, -308, 996, 991, 958, -1460, 1522, 1628,
26];
27
28#[inline]
29fn montgomery_reduce(a: i32) -> i16 {
30    let t = (a as i16).wrapping_mul(QINV as i16);
31    ((a - (t as i32) * Q) >> 16) as i16
32}
33
34/// Reduce a value already in the Montgomery range `(−q, q)` into `[0, q)` with a single conditional
35/// add — branchless (`x + (q & (x >> 15))`), auto-vectorizes 16-wide, and replaces the division-based
36/// `rem_euclid(Q)` in the coefficient hot path. Sound ONLY when `|x| < q` (the reduction invariant).
37#[inline]
38pub(crate) fn cadd_q(x: i16) -> u16 {
39    (x + (Q as i16 & (x >> 15))) as u16
40}
41
42/// `x mod q` for `x ∈ [0, 2q)`: subtract q, then add it back if that went negative.
43#[inline]
44pub(crate) fn csub_q(x: u16) -> u16 {
45    cadd_q(x.wrapping_sub(Q as u16) as i16)
46}
47
48/// `x mod q` in `[0, q)` for every i64, by multiplication alone: fold the high 32 bits in as
49/// `hi·(2³² mod q)`, lift by a multiple of q into `[0, 2⁴³)`, then a Barrett quotient exact there
50/// (`M = ⌈2⁵⁵/q⌉`, error `M·q − 2⁵⁵ = 2777`, so exact below `2⁵⁵/2777 > 2⁴³`).
51#[inline]
52pub(crate) fn reduce_wide(x: i64) -> u16 {
53    const TWO32_MOD_Q: i64 = 1353;
54    const LIFT: i64 = Q as i64 * (1 << 30);
55    const M: u128 = 10_822_708_626_905;
56    let z = ((x >> 32) * TWO32_MOD_Q + (x & 0xFFFF_FFFF) + LIFT) as u128;
57    let quotient = (z * M) >> 55;
58    (z - quotient * Q as u128) as u16
59}
60
61/// Compress_d (FIPS 203 §4.2.1) of one coefficient in `[0, q)`: `⌊(2ᵈ·x + ⌊q/2⌋) / q⌉ mod 2ᵈ`, the
62/// quotient by a Barrett multiply (`M = ⌈2³⁵/q⌉`, exact for every numerator below 2²³).
63#[inline]
64pub(crate) fn compress_coefficient(x: u16, d: usize) -> u16 {
65    const M: u64 = 10_321_340;
66    let numerator = ((x as u64) << d) + (Q as u64) / 2;
67    (((numerator * M) >> 35) & ((1u64 << d) - 1)) as u16
68}
69#[inline]
70fn fqmul(a: i16, b: i16) -> i16 {
71    montgomery_reduce(a as i32 * b as i32)
72}
73
74/// Scalar forward negacyclic NTT (Kyber reference), in place.
75fn ntt_scalar(r: &mut [i16; 256]) {
76    let mut k = 1usize;
77    let mut len = 128usize;
78    while len >= 2 {
79        let mut start = 0usize;
80        while start < 256 {
81            let zeta = ZETAS[k];
82            k += 1;
83            for j in start..start + len {
84                let t = fqmul(zeta, r[j + len]);
85                r[j + len] = r[j].wrapping_sub(t);
86                r[j] = r[j].wrapping_add(t);
87            }
88            start += 2 * len;
89        }
90        len >>= 1;
91    }
92}
93
94/// AVX2 forward NTT — all 7 levels vectorized 16-wide. Bit-identical to `ntt_scalar`.
95#[cfg(target_arch = "x86_64")]
96#[target_feature(enable = "avx2")]
97unsafe fn ntt_avx2(r: &mut [i16; 256]) {
98    use std::arch::x86_64::*;
99    let qv = _mm256_set1_epi16(Q as i16);
100    let qinvv = _mm256_set1_epi16(QINV as i16);
101    let mut k = 1usize;
102    let mut len = 128usize;
103    // len >= 16: contiguous 16-wide butterflies, broadcast zeta.
104    while len >= 16 {
105        let mut start = 0usize;
106        while start < 256 {
107            let zeta = _mm256_set1_epi16(ZETAS[k]);
108            k += 1;
109            let mut j = start;
110            while j < start + len {
111                let aj = _mm256_loadu_si256(r.as_ptr().add(j) as *const __m256i);
112                let ajl = _mm256_loadu_si256(r.as_ptr().add(j + len) as *const __m256i);
113                let rlo = _mm256_mullo_epi16(zeta, ajl);
114                let rhi = _mm256_mulhi_epi16(zeta, ajl);
115                let tt = _mm256_mullo_epi16(rlo, qinvv);
116                let tt = _mm256_mulhi_epi16(tt, qv);
117                let t = _mm256_sub_epi16(rhi, tt);
118                _mm256_storeu_si256(
119                    r.as_mut_ptr().add(j) as *mut __m256i,
120                    _mm256_add_epi16(aj, t),
121                );
122                _mm256_storeu_si256(
123                    r.as_mut_ptr().add(j + len) as *mut __m256i,
124                    _mm256_sub_epi16(aj, t),
125                );
126                j += 16;
127            }
128            start += 2 * len;
129        }
130        len >>= 1;
131    }
132    // len = 8: one block per vector, 128-bit half-swap + blend.
133    {
134        let lo_mask = _mm256_set_epi64x(0, 0, -1, -1);
135        let mut start = 0usize;
136        while start < 256 {
137            let zeta = _mm256_set1_epi16(ZETAS[k]);
138            k += 1;
139            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
140            let hi = _mm256_permute2x128_si256(v, v, 0x01);
141            let rlo = _mm256_mullo_epi16(zeta, hi);
142            let rhi = _mm256_mulhi_epi16(zeta, hi);
143            let tt = _mm256_mullo_epi16(rlo, qinvv);
144            let tt = _mm256_mulhi_epi16(tt, qv);
145            let t = _mm256_sub_epi16(rhi, tt);
146            let add = _mm256_add_epi16(v, t);
147            let sub = _mm256_sub_epi16(v, t);
148            let sub_hi = _mm256_permute2x128_si256(sub, sub, 0x01);
149            let out = _mm256_blendv_epi8(sub_hi, add, lo_mask);
150            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
151            start += 16;
152        }
153        len >>= 1;
154    }
155    // len = 4: two blocks per vector, per-block zeta + 64-bit swap.
156    {
157        let mask4 = _mm256_set_epi64x(0, -1, 0, -1);
158        let mut start = 0usize;
159        while start < 256 {
160            let z0 = ZETAS[k];
161            let z1 = ZETAS[k + 1];
162            k += 2;
163            let zv = _mm256_set_epi16(
164                z1, z1, z1, z1, z1, z1, z1, z1, z0, z0, z0, z0, z0, z0, z0, z0,
165            );
166            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
167            let vhi = _mm256_shuffle_epi32(v, 0x4E);
168            let rlo = _mm256_mullo_epi16(zv, vhi);
169            let rhi = _mm256_mulhi_epi16(zv, vhi);
170            let tt = _mm256_mullo_epi16(rlo, qinvv);
171            let tt = _mm256_mulhi_epi16(tt, qv);
172            let t = _mm256_sub_epi16(rhi, tt);
173            let add = _mm256_add_epi16(v, t);
174            let sub = _mm256_sub_epi16(v, t);
175            let sub_s = _mm256_shuffle_epi32(sub, 0x4E);
176            let out = _mm256_blendv_epi8(sub_s, add, mask4);
177            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
178            start += 16;
179        }
180        len >>= 1;
181    }
182    // len = 2: four blocks per vector, per-block zeta + 32-bit swap.
183    {
184        let mask2 = _mm256_set_epi32(0, -1, 0, -1, 0, -1, 0, -1);
185        let mut start = 0usize;
186        while start < 256 {
187            let z0 = ZETAS[k];
188            let z1 = ZETAS[k + 1];
189            let z2 = ZETAS[k + 2];
190            let z3 = ZETAS[k + 3];
191            k += 4;
192            let zv = _mm256_set_epi16(
193                z3, z3, z3, z3, z2, z2, z2, z2, z1, z1, z1, z1, z0, z0, z0, z0,
194            );
195            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
196            let vhi = _mm256_shuffle_epi32(v, 0xB1);
197            let rlo = _mm256_mullo_epi16(zv, vhi);
198            let rhi = _mm256_mulhi_epi16(zv, vhi);
199            let tt = _mm256_mullo_epi16(rlo, qinvv);
200            let tt = _mm256_mulhi_epi16(tt, qv);
201            let t = _mm256_sub_epi16(rhi, tt);
202            let add = _mm256_add_epi16(v, t);
203            let sub = _mm256_sub_epi16(v, t);
204            let sub_s = _mm256_shuffle_epi32(sub, 0xB1);
205            let out = _mm256_blendv_epi8(sub_s, add, mask2);
206            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
207            start += 16;
208        }
209    }
210}
211
212/// Montgomery multiply 16 i16 lanes: `montgomery_reduce(a·b)` — bit-identical to the scalar `fqmul`
213/// (low·qinv→t, then high − (t·q)high). The verified Kyber AVX2 reduction.
214#[cfg(target_arch = "x86_64")]
215#[target_feature(enable = "avx2")]
216#[inline]
217unsafe fn mont_mul_x16(
218    a: std::arch::x86_64::__m256i,
219    b: std::arch::x86_64::__m256i,
220) -> std::arch::x86_64::__m256i {
221    use std::arch::x86_64::*;
222    let q = _mm256_set1_epi16(Q as i16);
223    let qinv = _mm256_set1_epi16(QINV as i16);
224    let rlo = _mm256_mullo_epi16(b, a);
225    let rhi = _mm256_mulhi_epi16(b, a);
226    let tt = _mm256_mullo_epi16(rlo, qinv);
227    let tt = _mm256_mulhi_epi16(tt, q);
228    _mm256_sub_epi16(rhi, tt)
229}
230
231/// Barrett-reduce 16 i16 lanes, bit-identical to the scalar `barrett_reduce`. The scalar form
232/// `t = (V·a + 2²⁵) >> 26` (V = ⌊2²⁶/q⌉ = 20159, rounded) equals `t = (mulhi(a,V) + 512) >> 10`
233/// exactly: writing `V·a = hi·2¹⁶ + L` with `L ∈ [0,2¹⁶)`, the term `L/2²⁶ < 1/1024` can never
234/// move the floor, so the low half drops out and the rounding collapses to a +512 before the >>10.
235#[cfg(target_arch = "x86_64")]
236#[target_feature(enable = "avx2")]
237#[inline]
238unsafe fn barrett_x16(a: std::arch::x86_64::__m256i) -> std::arch::x86_64::__m256i {
239    use std::arch::x86_64::*;
240    const V: i16 = (((1 << 26) + Q / 2) / Q) as i16;
241    let q = _mm256_set1_epi16(Q as i16);
242    let hi = _mm256_mulhi_epi16(a, _mm256_set1_epi16(V));
243    let t = _mm256_srai_epi16(_mm256_add_epi16(hi, _mm256_set1_epi16(512)), 10);
244    _mm256_sub_epi16(a, _mm256_mullo_epi16(t, q))
245}
246
247/// AVX2 inverse NTT (`invntt_tomont`) — all 7 Gentleman-Sande levels vectorized 16-wide, then the
248/// final `f`-scaling. Bit-identical to `invntt_scalar`. Mirrors `ntt_avx2`'s lane routing in reverse
249/// level order: the GS butterfly writes `barrett(lo+hi)` to the low slot and `fqmul(ζ, hi−lo)` to the
250/// high slot (both already in position — no post-swap, unlike the forward Cooley–Tukey blend).
251#[cfg(target_arch = "x86_64")]
252#[target_feature(enable = "avx2")]
253unsafe fn invntt_avx2(r: &mut [i16; 256]) {
254    use std::arch::x86_64::*;
255    const F: i16 = 1441;
256    let mut k = 127usize;
257    // len = 2: four blocks per vector, per-block zeta, 32-bit swap.
258    {
259        let mask2 = _mm256_set_epi32(0, -1, 0, -1, 0, -1, 0, -1);
260        let mut start = 0usize;
261        while start < 256 {
262            let z0 = ZETAS[k];
263            let z1 = ZETAS[k - 1];
264            let z2 = ZETAS[k - 2];
265            let z3 = ZETAS[k - 3];
266            k -= 4;
267            let zv = _mm256_set_epi16(
268                z3, z3, z3, z3, z2, z2, z2, z2, z1, z1, z1, z1, z0, z0, z0, z0,
269            );
270            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
271            let vsh = _mm256_shuffle_epi32(v, 0xB1);
272            let lopart = barrett_x16(_mm256_add_epi16(v, vsh));
273            let hipart = mont_mul_x16(zv, _mm256_sub_epi16(v, vsh));
274            let out = _mm256_blendv_epi8(hipart, lopart, mask2);
275            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
276            start += 16;
277        }
278    }
279    // len = 4: two blocks per vector, per-block zeta, 64-bit swap.
280    {
281        let mask4 = _mm256_set_epi64x(0, -1, 0, -1);
282        let mut start = 0usize;
283        while start < 256 {
284            let z0 = ZETAS[k];
285            let z1 = ZETAS[k - 1];
286            k -= 2;
287            let zv = _mm256_set_epi16(
288                z1, z1, z1, z1, z1, z1, z1, z1, z0, z0, z0, z0, z0, z0, z0, z0,
289            );
290            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
291            let vsh = _mm256_shuffle_epi32(v, 0x4E);
292            let lopart = barrett_x16(_mm256_add_epi16(v, vsh));
293            let hipart = mont_mul_x16(zv, _mm256_sub_epi16(v, vsh));
294            let out = _mm256_blendv_epi8(hipart, lopart, mask4);
295            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
296            start += 16;
297        }
298    }
299    // len = 8: one block per vector, 128-bit half-swap.
300    {
301        let lo_mask = _mm256_set_epi64x(0, 0, -1, -1);
302        let mut start = 0usize;
303        while start < 256 {
304            let zeta = _mm256_set1_epi16(ZETAS[k]);
305            k -= 1;
306            let v = _mm256_loadu_si256(r.as_ptr().add(start) as *const __m256i);
307            let vsh = _mm256_permute2x128_si256(v, v, 0x01);
308            let lopart = barrett_x16(_mm256_add_epi16(v, vsh));
309            let hipart = mont_mul_x16(zeta, _mm256_sub_epi16(v, vsh));
310            let out = _mm256_blendv_epi8(hipart, lopart, lo_mask);
311            _mm256_storeu_si256(r.as_mut_ptr().add(start) as *mut __m256i, out);
312            start += 16;
313        }
314    }
315    // len >= 16: contiguous 16-wide butterflies, broadcast zeta.
316    let mut len = 16usize;
317    while len <= 128 {
318        let mut start = 0usize;
319        while start < 256 {
320            let zeta = _mm256_set1_epi16(ZETAS[k]);
321            k = k.wrapping_sub(1);
322            let mut j = start;
323            while j < start + len {
324                let lo = _mm256_loadu_si256(r.as_ptr().add(j) as *const __m256i);
325                let hi = _mm256_loadu_si256(r.as_ptr().add(j + len) as *const __m256i);
326                _mm256_storeu_si256(
327                    r.as_mut_ptr().add(j) as *mut __m256i,
328                    barrett_x16(_mm256_add_epi16(lo, hi)),
329                );
330                _mm256_storeu_si256(
331                    r.as_mut_ptr().add(j + len) as *mut __m256i,
332                    mont_mul_x16(zeta, _mm256_sub_epi16(hi, lo)),
333                );
334                j += 16;
335            }
336            start += 2 * len;
337        }
338        len <<= 1;
339    }
340    // Final f = mont²/128 scaling.
341    let fv = _mm256_set1_epi16(F);
342    let mut i = 0usize;
343    while i < 256 {
344        let v = _mm256_loadu_si256(r.as_ptr().add(i) as *const __m256i);
345        _mm256_storeu_si256(r.as_mut_ptr().add(i) as *mut __m256i, mont_mul_x16(fv, v));
346        i += 16;
347    }
348}
349
350/// Core forward ML-KEM NTT of 256 coefficients (mod q = 3329): AVX2 when the CPU has it, else
351/// scalar — same result. Coefficients are reduced into [0, q) at the boundary; output in [0, q).
352fn mlkem_ntt_raw(input: &[i64]) -> Vec<i64> {
353    assert_eq!(
354        input.len(),
355        256,
356        "mlkemNtt expects exactly 256 coefficients"
357    );
358    // mlkem_ntt's contract is to reduce ANY i64 input (see mlkem_ntt_reduces_and_matches_scalar),
359    // so every coefficient takes the full-width reduction — unlike base_mul/inv_ntt/to_mont, which
360    // only ever see already-reduced NTT-domain coefficients.
361    let mut r = [0i16; 256];
362    for (slot, &x) in r.iter_mut().zip(input) {
363        *slot = reduce_wide(x) as i16;
364    }
365    #[cfg(target_arch = "x86_64")]
366    {
367        if std::is_x86_feature_detected!("avx2") {
368            unsafe { ntt_avx2(&mut r) };
369        } else {
370            ntt_scalar(&mut r);
371        }
372    }
373    #[cfg(not(target_arch = "x86_64"))]
374    ntt_scalar(&mut r);
375    r.iter()
376        .map(|&x| cadd_q(barrett_reduce(x)) as i64)
377        .collect()
378}
379
380/// The compiled form of LOGOS `mlkemNtt(a)` — the runtime entry the generated Rust calls (and the
381/// interpreter dispatches to). Takes/returns the LOGOS `Seq of Int` carrier.
382pub fn mlkem_ntt(input: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
383    args::count("polynomial", input.len(), 256)?;
384    let out = mlkem_ntt_raw(input);
385    Ok(logicaffeine_data::LogosSeq::from_vec(out))
386}
387
388/// `Word16`-native forward NTT — coefficients are carried as `Word16` (u16) in [0, q), so the
389/// boundary is a plain reinterpret (`w.0 as i16`, exact since q < 2¹⁵), no rem_euclid and no
390/// i64 round-trip. The experimental fast carrier for the Word16-representation crypto.
391pub fn mlkem_ntt_w16(input: &[logicaffeine_base::Word16]) -> Vec<logicaffeine_base::Word16> {
392    use logicaffeine_base::Word16;
393    assert_eq!(input.len(), 256);
394    let mut r = [0i16; 256];
395    for (slot, w) in r.iter_mut().zip(input) {
396        *slot = w.0 as i16;
397    }
398    #[cfg(target_arch = "x86_64")]
399    {
400        if std::is_x86_feature_detected!("avx2") {
401            unsafe { ntt_avx2(&mut r) };
402        } else {
403            ntt_scalar(&mut r);
404        }
405    }
406    #[cfg(not(target_arch = "x86_64"))]
407    ntt_scalar(&mut r);
408    r.iter()
409        .map(|&x| Word16(cadd_q(barrett_reduce(x))))
410        .collect()
411}
412
413/// `Word16`-native inverse NTT, base multiply, and tomont — same zero-conversion carrier.
414pub fn mlkem_inv_ntt_w16(input: &[logicaffeine_base::Word16]) -> Vec<logicaffeine_base::Word16> {
415    use logicaffeine_base::Word16;
416    assert_eq!(
417        input.len(),
418        256,
419        "the inverse NTT takes one 256-coefficient polynomial"
420    );
421    let mut r = [0i16; 256];
422    for (slot, w) in r.iter_mut().zip(input) {
423        *slot = w.0 as i16;
424    }
425    inv_ntt_inplace(&mut r);
426    r.iter()
427        .map(|&x| Word16(cadd_q(barrett_reduce(x))))
428        .collect()
429}
430
431/// Inverse NTT in place: AVX2 when the CPU has it (bit-identical to the scalar reference), else scalar.
432#[inline]
433fn inv_ntt_inplace(r: &mut [i16; 256]) {
434    #[cfg(target_arch = "x86_64")]
435    {
436        if std::is_x86_feature_detected!("avx2") {
437            unsafe { invntt_avx2(r) };
438            return;
439        }
440    }
441    invntt_scalar(r);
442}
443pub fn mlkem_base_mul_w16(
444    a: &[logicaffeine_base::Word16],
445    b: &[logicaffeine_base::Word16],
446) -> Vec<logicaffeine_base::Word16> {
447    use logicaffeine_base::Word16;
448    assert!(
449        a.len() == 256 && b.len() == 256,
450        "the base multiply takes two 256-coefficient polynomials"
451    );
452    let to16 = |v: &[Word16]| -> [i16; 256] {
453        let mut r = [0i16; 256];
454        for (slot, w) in r.iter_mut().zip(v) {
455            *slot = w.0 as i16;
456        }
457        r
458    };
459    let r = basemul_scalar(&to16(a), &to16(b));
460    // basemul_scalar sums two Montgomery products (each ∈ (−q, q)) ⇒ result ∈ (−2q, 2q): Barrett into
461    // (−q/2, q/2] then a conditional add into [0, q) — both branchless, no division.
462    r.iter()
463        .map(|&x| Word16(cadd_q(barrett_reduce(x))))
464        .collect()
465}
466pub fn mlkem_to_mont_w16(coeffs: &[logicaffeine_base::Word16]) -> Vec<logicaffeine_base::Word16> {
467    use logicaffeine_base::Word16;
468    const F: i32 = 1353;
469    // montgomery_reduce returns (−q, q) ⇒ conditional add, no division.
470    coeffs
471        .iter()
472        .map(|w| Word16(cadd_q(montgomery_reduce(w.0 as i16 as i32 * F))))
473        .collect()
474}
475
476/// Native entry for the LOGOS `Seq of Word16` carrier — wraps the raw Word16 NTT in a `LogosSeq`.
477pub fn mlkem_ntt_w16_seq(
478    input: &[logicaffeine_base::Word16],
479) -> Result<logicaffeine_data::LogosSeq<logicaffeine_base::Word16>, String> {
480    reduced_words("polynomial", input)?;
481    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_ntt_w16(input)))
482}
483
484// ── Word16/Word8 carrier: the rest of the ML-KEM pipeline (zero i64 round-trip) ───────────────
485use logicaffeine_base::{Word16, Word8};
486
487/// CBD noise sampled to [0, q) Word16 (the reduced form the Word16 NTT consumes directly).
488pub fn mlkem_cbd2_w16(buf: &[u8]) -> Vec<Word16> {
489    cbd_eta2(buf).iter().map(|&c| Word16(cadd_q(c))).collect()
490}
491pub fn mlkem_cbd3_w16(buf: &[u8]) -> Vec<Word16> {
492    cbd_eta3(buf).iter().map(|&c| Word16(cadd_q(c))).collect()
493}
494pub fn mlkem_compress_w16(coeffs: &[Word16], d: usize) -> Vec<Word16> {
495    assert!(
496        (1..=11).contains(&d),
497        "Compress_d takes a width d from 1 to 11"
498    );
499    coeffs
500        .iter()
501        .map(|w| Word16(compress_coefficient(w.0, d)))
502        .collect()
503}
504pub fn mlkem_decompress_w16(coeffs: &[Word16], d: usize) -> Vec<Word16> {
505    assert!(
506        (1..=11).contains(&d),
507        "Decompress_d takes a width d from 1 to 11"
508    );
509    let denom = 1u64 << d;
510    coeffs
511        .iter()
512        .map(|w| Word16((((w.0 as u64) * (Q as u64) + denom / 2) >> d) as u16))
513        .collect()
514}
515pub fn mlkem_byte_encode_w16(coeffs: &[Word16], d: usize) -> Vec<u8> {
516    assert!(
517        (1..=12).contains(&d),
518        "ByteEncode_d takes a width d from 1 to 12"
519    );
520    assert_eq!(
521        coeffs.len(),
522        256,
523        "ByteEncode_{d} takes one 256-coefficient polynomial"
524    );
525    let mask = (1u64 << d) - 1;
526    let mut out = Vec::with_capacity((coeffs.len() * d).div_ceil(8));
527    let (mut acc, mut nbits) = (0u64, 0u32);
528    for w in coeffs {
529        acc |= (w.0 as u64 & mask) << nbits;
530        nbits += d as u32;
531        while nbits >= 8 {
532            out.push((acc & 0xff) as u8);
533            acc >>= 8;
534            nbits -= 8;
535        }
536    }
537    if nbits > 0 {
538        out.push((acc & 0xff) as u8);
539    }
540    out
541}
542/// ByteDecode_d of one polynomial: exactly `32·d` bytes to 256 coefficients, reduced mod q for d = 12.
543pub fn mlkem_byte_decode_w16(bytes: &[u8], d: usize) -> Vec<Word16> {
544    assert!(
545        (1..=12).contains(&d),
546        "ByteDecode_d takes a width d from 1 to 12"
547    );
548    assert_eq!(
549        bytes.len(),
550        32 * d,
551        "ByteDecode_{d} takes one polynomial's 32·d bytes"
552    );
553    let mask = (1u64 << d) - 1;
554    let mut out = Vec::with_capacity(256);
555    let (mut acc, mut nbits, mut bi) = (0u64, 0u32, 0usize);
556    for _ in 0..256 {
557        while nbits < d as u32 {
558            acc |= (bytes[bi] as u64) << nbits;
559            nbits += 8;
560            bi += 1;
561        }
562        let val = (acc & mask) as u16;
563        acc >>= d;
564        nbits -= d as u32;
565        out.push(Word16(if d == 12 { csub_q(val) } else { val }));
566    }
567    out
568}
569/// FIPS-203 SampleNTT rejection over one 168-byte SHAKE128 block: parse 12-bit pairs, keep those
570/// `< q`, append to `out` (capped at 256). 168 = 56·3 so triples never straddle a block boundary.
571#[inline]
572fn reject_sample_block(buf: &[u8; 168], out: &mut Vec<Word16>) {
573    let q = Q as u32;
574    let mut k = 0;
575    while k + 3 <= 168 && out.len() < 256 {
576        let (b0, b1, b2) = (buf[k] as u32, buf[k + 1] as u32, buf[k + 2] as u32);
577        let d1 = b0 + 256 * (b1 % 16);
578        let d2 = (b1 / 16) + 16 * b2;
579        if d1 < q {
580            out.push(Word16(d1 as u16));
581        }
582        if d2 < q && out.len() < 256 {
583            out.push(Word16(d2 as u16));
584        }
585        k += 3;
586    }
587}
588
589/// The 256-entry byte-compaction shuffle table for the vectorized rejection sampler: `table[m]` is the
590/// `vpshufb` index that packs the accepted 16-bit lanes (accept bitmask `m` over 8 lanes) to the front
591/// of a 128-bit register. Built once (idempotent).
592#[cfg(target_arch = "x86_64")]
593fn rej_compact_table() -> &'static [[u8; 16]; 256] {
594    use std::sync::OnceLock;
595    static TABLE: OnceLock<[[u8; 16]; 256]> = OnceLock::new();
596    TABLE.get_or_init(|| {
597        let mut t = [[0xFFu8; 16]; 256];
598        for (m, entry) in t.iter_mut().enumerate() {
599            let mut pos = 0usize;
600            for lane in 0..8u8 {
601                if (m >> lane) & 1 == 1 {
602                    entry[pos * 2] = lane * 2;
603                    entry[pos * 2 + 1] = lane * 2 + 1;
604                    pos += 1;
605                }
606            }
607        }
608        t
609    })
610}
611
612/// AVX2 vectorized ML-KEM matrix rejection sampler — **bit-identical** to [`reject_sample_block`],
613/// several × faster: spread 24 bytes → 16 twelve-bit candidates per step (`vpshufb` + `vpsrlw` + blend),
614/// compare all sixteen to q at once (`vpcmpgtw`), then compact the accepted lanes with a 256-entry
615/// shuffle table (`vpshufb` + popcount advance). Appends accepted coefficients to `out` in the SAME
616/// order as the scalar sampler and stops at 256. This is the ExpandA hot loop (~85% of sampleA cost).
617#[cfg(target_arch = "x86_64")]
618#[target_feature(enable = "avx2")]
619unsafe fn reject_sample_block_avx2(buf: &[u8; 168], out: &mut Vec<Word16>) {
620    use std::arch::x86_64::*;
621    let table = rej_compact_table();
622    let qv = _mm256_set1_epi16(Q as i16);
623    let maskv = _mm256_set1_epi16(0x0fff);
624    // idx8: within each 128-bit half, 16-bit lane 2i ← bytes [3i, 3i+1], lane 2i+1 ← bytes [3i+1, 3i+2]
625    // (low half over its bytes 0..11, high half over its bytes 4..15 = the group's bytes 12..23).
626    let idx8 = _mm256_set_epi8(
627        15, 14, 14, 13, 12, 11, 11, 10, 9, 8, 8, 7, 6, 5, 5, 4, //
628        11, 10, 10, 9, 8, 7, 7, 6, 5, 4, 4, 3, 2, 1, 1, 0,
629    );
630    // Pad so every 32-byte load stays in bounds (168 = 7·24; the 7th load reads to byte 175).
631    let mut padded = [0u8; 192];
632    padded[..168].copy_from_slice(buf);
633
634    let mut off = 0usize;
635    while off + 24 <= 168 && out.len() < 256 {
636        let raw = _mm256_loadu_si256(padded.as_ptr().add(off) as *const __m256i);
637        let perm = _mm256_permute4x64_epi64(raw, 0x94); // lo=bytes0..15, hi=bytes8..23
638        let mut f = _mm256_shuffle_epi8(perm, idx8);
639        let g = _mm256_srli_epi16(f, 4);
640        f = _mm256_blend_epi16(f, g, 0xAA); // odd 16-bit lanes take the >>4 form (d2)
641        f = _mm256_and_si256(f, maskv);
642        let good = _mm256_cmpgt_epi16(qv, f); // 0xFFFF where f < q (accepted)
643
644        for half in 0..2 {
645            if out.len() >= 256 {
646                break;
647            }
648            let cand = if half == 0 {
649                _mm256_castsi256_si128(f)
650            } else {
651                _mm256_extracti128_si256(f, 1)
652            };
653            let gd = if half == 0 {
654                _mm256_castsi256_si128(good)
655            } else {
656                _mm256_extracti128_si256(good, 1)
657            };
658            let m = (_mm_movemask_epi8(_mm_packs_epi16(gd, gd)) & 0xff) as usize;
659            let sh = _mm_loadu_si128(table[m].as_ptr() as *const __m128i);
660            let packed = _mm_shuffle_epi8(cand, sh);
661            let mut tmp = [0i16; 8];
662            _mm_storeu_si128(tmp.as_mut_ptr() as *mut __m128i, packed);
663            let n = (m.count_ones() as usize).min(256 - out.len());
664            for &c in tmp.iter().take(n) {
665                out.push(Word16(c as u16));
666            }
667        }
668        off += 24;
669    }
670}
671
672/// The 32-byte ρ a matrix sampler takes; any other length is a caller's error, never truncated.
673fn sample_seed(seed: &[u8]) -> &[u8] {
674    assert_eq!(seed.len(), 32, "the matrix seed ρ is 32 bytes");
675    seed
676}
677
678/// A row or column index of  as the XOF's index byte; one past a byte is a caller's error.
679fn sample_index(idx: i64) -> u8 {
680    u8::try_from(idx).expect("a matrix index is a byte")
681}
682
683/// The padded 168-byte SHAKE128 absorb block for matrix entry `Â[r][c]`: `seed‖r‖c`, the `0x1f`
684/// delimiter, and the `0x80` final bit — the single-block XOF input the rejection sampler streams.
685#[inline]
686fn sample_a_xof_block(seed: &[u8], r: u8, c: u8) -> [u8; 168] {
687    let mut blk = [0u8; 168];
688    blk[..32].copy_from_slice(&seed[..32]);
689    blk[32] = r;
690    blk[33] = c;
691    blk[34] = 0x1f;
692    blk[167] |= 0x80;
693    blk
694}
695
696/// Matrix entry Â\[i\]\[j\] sampled to [0, q) Word16 — streaming SHAKE128 rejection (scalar reference).
697pub fn mlkem_sample_a_w16(seed: &[u8], idx_i: i64, idx_j: i64) -> Vec<Word16> {
698    let mut xof_in = [0u8; 34];
699    xof_in[..32].copy_from_slice(sample_seed(seed));
700    xof_in[32] = sample_index(idx_i);
701    xof_in[33] = sample_index(idx_j);
702    let mut st = crate::keccak::shake128_absorb(&xof_in);
703    let mut out: Vec<Word16> = Vec::with_capacity(256);
704    let mut buf = [0u8; 168];
705    loop {
706        for i in 0..21 {
707            buf[i * 8..i * 8 + 8].copy_from_slice(&st[i].to_le_bytes());
708        }
709        #[cfg(target_arch = "x86_64")]
710        {
711            if std::is_x86_feature_detected!("avx2") {
712                unsafe { reject_sample_block_avx2(&buf, &mut out) };
713            } else {
714                reject_sample_block(&buf, &mut out);
715            }
716        }
717        #[cfg(not(target_arch = "x86_64"))]
718        reject_sample_block(&buf, &mut out);
719        if out.len() >= 256 {
720            out.truncate(256);
721            return out;
722        }
723        crate::keccak::keccak_f1600(&mut st);
724    }
725}
726
727/// Sample the full ML-KEM-768 3×3 matrix  at once (9 × 256 Word16, entry Â\[r\]\[c\] at slot
728/// `(r·3+c)·256`), batching four rejection-sampling streams per 4-way AVX2 SHAKE128 permutation.
729/// Bit-identical to nine `mlkem_sample_a_w16` calls; falls back to scalar without AVX2. This is the
730/// matrix-expansion keystone — sampleA is ~60% of keygen and is `×9` again in encaps.
731pub fn mlkem_sample_matrix_w16(seed: &[u8]) -> Vec<Word16> {
732    let seed = sample_seed(seed);
733    const ENTRIES: [(u8, u8); 9] = [
734        (0, 0),
735        (0, 1),
736        (0, 2),
737        (1, 0),
738        (1, 1),
739        (1, 2),
740        (2, 0),
741        (2, 1),
742        (2, 2),
743    ];
744    let mut out = vec![Word16(0); 9 * 256];
745    let mut place = |e: usize, poly: &[Word16]| {
746        out[e * 256..e * 256 + 256].copy_from_slice(&poly[..256]);
747    };
748
749    #[cfg(target_arch = "x86_64")]
750    {
751        if std::is_x86_feature_detected!("avx2") {
752            let mut e = 0;
753            while e + 4 <= ENTRIES.len() {
754                let blocks: [[u8; 168]; 4] = std::array::from_fn(|l| {
755                    sample_a_xof_block(seed, ENTRIES[e + l].0, ENTRIES[e + l].1)
756                });
757                let mut accs: [Vec<Word16>; 4] = std::array::from_fn(|_| Vec::with_capacity(256));
758                let mut st = unsafe { crate::keccak::shake128_x4_absorb_once(&blocks) };
759                loop {
760                    let outb = unsafe { crate::keccak::shake128_x4_squeeze_block(&st) };
761                    let mut done = true;
762                    for (l, acc) in accs.iter_mut().enumerate() {
763                        if acc.len() < 256 {
764                            unsafe { reject_sample_block_avx2(&outb[l], acc) };
765                        }
766                        if acc.len() < 256 {
767                            done = false;
768                        }
769                    }
770                    if done {
771                        break;
772                    }
773                    unsafe { crate::keccak::keccak_f1600_x4(&mut st) };
774                }
775                for (l, acc) in accs.iter().enumerate() {
776                    place(e + l, acc);
777                }
778                e += 4;
779            }
780            while e < ENTRIES.len() {
781                let v = mlkem_sample_a_w16(seed, ENTRIES[e].0 as i64, ENTRIES[e].1 as i64);
782                place(e, &v);
783                e += 1;
784            }
785            return out;
786        }
787    }
788
789    for (e, &(r, c)) in ENTRIES.iter().enumerate() {
790        let v = mlkem_sample_a_w16(seed, r as i64, c as i64);
791        place(e, &v);
792    }
793    out
794}
795
796#[inline]
797fn barrett_reduce(a: i16) -> i16 {
798    const V: i32 = ((1 << 26) + Q / 2) / Q;
799    let t = (((V * a as i32) + (1 << 25)) >> 26) as i16;
800    a.wrapping_sub(t.wrapping_mul(Q as i16))
801}
802
803/// Scalar inverse NTT (Kyber reference, `invntt_tomont`), in place — Gentleman-Sande butterflies
804/// with Barrett reduction, then the `f = mont²/128` final scaling. invntt(ntt(p)) = p·MONT mod q.
805fn invntt_scalar(r: &mut [i16; 256]) {
806    const F: i16 = 1441;
807    let mut k = 127usize;
808    let mut len = 2usize;
809    while len <= 128 {
810        let mut start = 0usize;
811        while start < 256 {
812            let zeta = ZETAS[k];
813            k = k.wrapping_sub(1);
814            for j in start..start + len {
815                let t = r[j];
816                r[j] = barrett_reduce(t.wrapping_add(r[j + len]));
817                r[j + len] = r[j + len].wrapping_sub(t);
818                r[j + len] = fqmul(zeta, r[j + len]);
819            }
820            start += 2 * len;
821        }
822        len <<= 1;
823    }
824    for x in r.iter_mut() {
825        *x = fqmul(*x, F);
826    }
827}
828
829fn mlkem_inv_ntt_raw(input: &[i64]) -> Vec<i64> {
830    assert_eq!(
831        input.len(),
832        256,
833        "mlkemInvNtt expects exactly 256 coefficients"
834    );
835    // Inputs are NTT-domain coefficients in [0, q) — the truncating `as i16` cast is exact.
836    let mut r = [0i16; 256];
837    for (slot, &x) in r.iter_mut().zip(input) {
838        debug_assert!((0..Q as i64).contains(&x), "inv_ntt input out of [0,q)");
839        *slot = x as i16;
840    }
841    inv_ntt_inplace(&mut r);
842    r.iter()
843        .map(|&x| cadd_q(barrett_reduce(x)) as i64)
844        .collect()
845}
846
847/// The compiled form of LOGOS `mlkemInvNtt(a)` — the inverse ML-KEM NTT (`tomont`), so
848/// `mlkemInvNtt(mlkemNtt(p)) = p·2285 mod q`. Together with `mlkemNtt` and a base-multiply this is
849/// the polynomial-multiplication primitive ML-KEM is built on.
850pub fn mlkem_inv_ntt(input: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
851    reduced_polynomial("polynomial", input)?;
852    let out = mlkem_inv_ntt_raw(input);
853    Ok(logicaffeine_data::LogosSeq::from_vec(out))
854}
855
856/// One degree-1 base multiply mod (X² − ζ): `r0 = a0·b0 + ζ·a1·b1`, `r1 = a0·b1 + a1·b0`. This is
857/// the gauss/Karatsuba bilinear form the kernel certifies (`field_algebra::gauss_three_multiply`).
858#[inline]
859fn bmul(a: &[i16], b: &[i16], zeta: i16) -> (i16, i16) {
860    let r0 = fqmul(fqmul(a[1], b[1]), zeta).wrapping_add(fqmul(a[0], b[0]));
861    let r1 = fqmul(a[0], b[1]).wrapping_add(fqmul(a[1], b[0]));
862    (r0, r1)
863}
864
865/// Scalar pointwise base-multiply of two NTT-domain polynomials (Kyber `poly_basemul`). The 128
866/// degree-1 pairs use ζ = ±zetas[64+i].
867fn basemul_scalar(a: &[i16; 256], b: &[i16; 256]) -> [i16; 256] {
868    let mut r = [0i16; 256];
869    for i in 0..64 {
870        let zeta = ZETAS[64 + i];
871        let (c0, c1) = bmul(&a[4 * i..4 * i + 2], &b[4 * i..4 * i + 2], zeta);
872        r[4 * i] = c0;
873        r[4 * i + 1] = c1;
874        let (d0, d1) = bmul(
875            &a[4 * i + 2..4 * i + 4],
876            &b[4 * i + 2..4 * i + 4],
877            zeta.wrapping_neg(),
878        );
879        r[4 * i + 2] = d0;
880        r[4 * i + 3] = d1;
881    }
882    r
883}
884
885fn mlkem_base_mul_raw(a: &[i64], b: &[i64]) -> Vec<i64> {
886    assert_eq!(a.len(), 256);
887    assert_eq!(b.len(), 256);
888    // Inputs are NTT-domain coefficients already reduced to [0, q) (q = 3329 < 2¹⁵), so the
889    // truncating `as i16` cast is exact — no per-element rem_euclid needed on the way in.
890    let to16 = |v: &[i64]| -> [i16; 256] {
891        let mut r = [0i16; 256];
892        for (slot, &x) in r.iter_mut().zip(v) {
893            debug_assert!((0..Q as i64).contains(&x), "base_mul input out of [0,q)");
894            *slot = x as i16;
895        }
896        r
897    };
898    let r = basemul_scalar(&to16(a), &to16(b));
899    r.iter()
900        .map(|&x| cadd_q(barrett_reduce(x)) as i64)
901        .collect()
902}
903
904/// The compiled form of LOGOS `mlkemBaseMul(a, b)` — pointwise multiply of two NTT-domain
905/// polynomials. `mlkemInvNtt(mlkemBaseMul(mlkemNtt(a), mlkemNtt(b)))` is the ML-KEM polynomial
906/// product a·b in ℤ_q\[X\]/(X²⁵⁶+1).
907pub fn mlkem_base_mul(a: &[i64], b: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
908    reduced_polynomial("first polynomial", a)?;
909    reduced_polynomial("second polynomial", b)?;
910    let out = mlkem_base_mul_raw(a, b);
911    Ok(logicaffeine_data::LogosSeq::from_vec(out))
912}
913
914/// poly_tomont (Kyber): bring coefficients into the Montgomery domain by multiplying by R = 2¹⁶
915/// (F = 2³² mod q = 1353, one montgomery_reduce). After accumulating `Σ_j basemul(Â[i][j], ŝ[j])`
916/// — which lands in the R⁻¹ domain — a single tomont returns t̂ to normal form for ByteEncode12.
917fn mlkem_to_mont_raw(coeffs: &[i64]) -> Vec<i64> {
918    const F: i32 = 1353; // 2³² mod q
919    coeffs
920        .iter()
921        .map(|&x| {
922            debug_assert!((0..Q as i64).contains(&x), "to_mont input out of [0,q)");
923            cadd_q(montgomery_reduce(x as i32 * F)) as i64
924        })
925        .collect()
926}
927
928/// The compiled form of LOGOS `toMont(coeffs)` — multiply a polynomial into the Montgomery domain.
929pub fn mlkem_to_mont(coeffs: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
930    args::ints_below("polynomial", coeffs, Q as i64)?;
931    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_to_mont_raw(
932        coeffs,
933    )))
934}
935
936// ── CBD sampling: centered binomial noise, the Kyber bit-trick (η = 2, 3) ─────────────────────
937
938/// CBD_2 (ML-KEM η=2): 128 bytes → 256 coefficients in [−2, 2]. Each coefficient is
939/// popcount(2 bits) − popcount(2 bits); the `& 0x55..` trick sums the bit-pairs in parallel.
940fn cbd_eta2(buf: &[u8]) -> [i16; 256] {
941    assert_eq!(buf.len(), 128, "CBD_2 needs 64·η = 128 bytes");
942    let mut r = [0i16; 256];
943    for i in 0..32 {
944        let t = u32::from_le_bytes(buf[4 * i..4 * i + 4].try_into().unwrap());
945        let mut d = t & 0x5555_5555;
946        d += (t >> 1) & 0x5555_5555;
947        for j in 0..8 {
948            let a = ((d >> (4 * j)) & 0x3) as i16;
949            let b = ((d >> (4 * j + 2)) & 0x3) as i16;
950            r[8 * i + j] = a - b;
951        }
952    }
953    r
954}
955
956/// CBD_3 (ML-KEM η=3 / ML-KEM-512's `s`,`e`): 192 bytes → 256 coefficients in [−3, 3].
957fn cbd_eta3(buf: &[u8]) -> [i16; 256] {
958    assert_eq!(buf.len(), 192, "CBD_3 needs 64·η = 192 bytes");
959    let mut r = [0i16; 256];
960    for i in 0..64 {
961        let t = buf[3 * i] as u32 | (buf[3 * i + 1] as u32) << 8 | (buf[3 * i + 2] as u32) << 16;
962        let mut d = t & 0x0024_9249;
963        d += (t >> 1) & 0x0024_9249;
964        d += (t >> 2) & 0x0024_9249;
965        for j in 0..4 {
966            let a = ((d >> (6 * j)) & 0x7) as i16;
967            let b = ((d >> (6 * j + 3)) & 0x7) as i16;
968            r[4 * i + j] = a - b;
969        }
970    }
971    r
972}
973
974fn mlkem_cbd_raw(bytes: &[u8], eta: usize) -> Vec<i64> {
975    let r = match eta {
976        2 => cbd_eta2(bytes),
977        3 => cbd_eta3(bytes),
978        _ => panic!("ML-KEM CBD supports η ∈ {{2, 3}}"),
979    };
980    r.iter().map(|&x| x as i64).collect()
981}
982
983/// The compiled form of LOGOS `cbd2(buf)` — sample a noise polynomial (η=2) from 128 bytes of
984/// (SHAKE) randomness; 256 coefficients in [−2, 2].
985pub fn mlkem_cbd2(buf: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
986    let bytes = args::exact_bytes("randomness", buf, 128)?;
987    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_cbd_raw(
988        &bytes, 2,
989    )))
990}
991/// The compiled form of LOGOS `cbd3(buf)` — η=3 noise from 192 bytes; coefficients in [−3, 3].
992pub fn mlkem_cbd3(buf: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
993    let bytes = args::exact_bytes("randomness", buf, 192)?;
994    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_cbd_raw(
995        &bytes, 3,
996    )))
997}
998
999// ── Serialization: Compress/Decompress + ByteEncode/ByteDecode (FIPS 203 §4.2.1) ──────────────
1000
1001/// Compress_d (FIPS 203): map a coefficient in [0, q) into d bits, `round(2^d·x / q) mod 2^d`,
1002/// rounding half up exactly as the Kyber reference (`(x·2^d + ⌊q/2⌋) / q`).
1003fn mlkem_compress_raw(coeffs: &[i64], d: usize) -> Vec<i64> {
1004    coeffs
1005        .iter()
1006        .map(|&x| compress_coefficient(reduce_wide(x), d) as i64)
1007        .collect()
1008}
1009
1010/// Decompress_d (FIPS 203): map d bits back toward [0, q), `round(q·y / 2^d)` (round half up).
1011fn mlkem_decompress_raw(coeffs: &[i64], d: usize) -> Vec<i64> {
1012    let denom = 1u64 << d;
1013    coeffs
1014        .iter()
1015        .map(|&y| (((y as u64) * (Q as u64) + denom / 2) >> d) as i64)
1016        .collect()
1017}
1018
1019/// ByteEncode_d (FIPS 203 Alg. 5): pack the low d bits of each coefficient, least-significant bit
1020/// first, into a byte string of length ⌈(len·d)/8⌉ (= 32·d for a 256-coefficient polynomial). A
1021/// 64-bit bit-accumulator emits whole bytes (d ≤ 12, so at most 19 staged bits) — no per-bit loop.
1022fn mlkem_byte_encode_raw(coeffs: &[i64], d: usize) -> Vec<i64> {
1023    let mask = (1u64 << d) - 1;
1024    let mut out = Vec::with_capacity((coeffs.len() * d).div_ceil(8));
1025    let mut acc: u64 = 0;
1026    let mut nbits = 0u32;
1027    for &c in coeffs {
1028        acc |= ((c as u64) & mask) << nbits;
1029        nbits += d as u32;
1030        while nbits >= 8 {
1031            out.push((acc & 0xff) as i64);
1032            acc >>= 8;
1033            nbits -= 8;
1034        }
1035    }
1036    if nbits > 0 {
1037        out.push((acc & 0xff) as i64);
1038    }
1039    out
1040}
1041
1042/// ByteDecode_d (FIPS 203 Alg. 6): the inverse of ByteEncode; for d = 12 the value is reduced
1043/// mod q (12-bit fields can exceed q), otherwise it is a plain d-bit integer. Byte-batched: bytes
1044/// feed a 64-bit accumulator from which d-bit values are sliced — no per-bit loop.
1045fn mlkem_byte_decode_raw(bytes: &[i64], d: usize) -> Vec<i64> {
1046    assert_eq!(
1047        bytes.len(),
1048        32 * d,
1049        "ByteDecode_{d} takes one polynomial's 32·d bytes"
1050    );
1051    let mask = (1u64 << d) - 1;
1052    let mut out = Vec::with_capacity(256);
1053    let mut acc: u64 = 0;
1054    let mut nbits = 0u32;
1055    let mut bi = 0usize;
1056    for _ in 0..256 {
1057        while nbits < d as u32 {
1058            acc |= (bytes[bi] as u64) << nbits;
1059            nbits += 8;
1060            bi += 1;
1061        }
1062        let val = (acc & mask) as i64;
1063        acc >>= d;
1064        nbits -= d as u32;
1065        out.push(if d == 12 {
1066            csub_q(val as u16) as i64
1067        } else {
1068            val
1069        });
1070    }
1071    out
1072}
1073
1074/// The compiled form of LOGOS `compress(coeffs, d)` — element-wise Compress_d.
1075pub fn mlkem_compress(coeffs: &[i64], d: i64) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1076    let d = args::int_in("width d", d, 1, 11)?;
1077    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_compress_raw(
1078        coeffs, d as usize,
1079    )))
1080}
1081/// The compiled form of LOGOS `decompress(coeffs, d)` — element-wise Decompress_d.
1082pub fn mlkem_decompress(
1083    coeffs: &[i64],
1084    d: i64,
1085) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1086    let d = args::int_in("width d", d, 1, 11)?;
1087    args::ints_below("compressed values", coeffs, 1 << d)?;
1088    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_decompress_raw(
1089        coeffs, d as usize,
1090    )))
1091}
1092/// The compiled form of LOGOS `byteEncode(coeffs, d)` — pack coefficients to bytes.
1093pub fn mlkem_byte_encode(
1094    coeffs: &[i64],
1095    d: i64,
1096) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1097    let d = args::int_in("width d", d, 1, 12)?;
1098    args::count("polynomial", coeffs.len(), 256)?;
1099    args::ints_below("polynomial", coeffs, encoded_bound(d))?;
1100    Ok(logicaffeine_data::LogosSeq::from_vec(
1101        mlkem_byte_encode_raw(coeffs, d as usize),
1102    ))
1103}
1104/// The compiled form of LOGOS `byteDecode(bytes, d)` — unpack bytes to coefficients.
1105pub fn mlkem_byte_decode(
1106    bytes: &[i64],
1107    d: i64,
1108) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1109    let d = args::int_in("width d", d, 1, 12)?;
1110    args::exact_bytes("encoding", bytes, 32 * d as usize)?;
1111    Ok(logicaffeine_data::LogosSeq::from_vec(
1112        mlkem_byte_decode_raw(bytes, d as usize),
1113    ))
1114}
1115
1116/// One polynomial of 256 coefficients, each already reduced into [0, q).
1117fn reduced_polynomial(what: &str, coeffs: &[i64]) -> Result<(), String> {
1118    args::count(what, coeffs.len(), 256)?;
1119    args::ints_below(what, coeffs, Q as i64)
1120}
1121
1122/// One polynomial of 256 Word16 coefficients, each already reduced into [0, q).
1123fn reduced_words(what: &str, coeffs: &[Word16]) -> Result<(), String> {
1124    args::count(what, coeffs.len(), 256)?;
1125    args::words_below(what, coeffs, Q as u16)
1126}
1127
1128/// The values ByteEncode_d packs: d-bit integers, or for d = 12 coefficients reduced mod q.
1129fn encoded_bound(d: i64) -> i64 {
1130    if d == 12 {
1131        Q as i64
1132    } else {
1133        1 << d
1134    }
1135}
1136
1137// ── Uniform sampling in the NTT domain: SampleNTT + matrix-entry expansion (FIPS 203 §4.2.2) ──
1138
1139/// Try to rejection-sample 256 coefficients (< q) from a byte stream of XOF output, three bytes
1140/// yielding two 12-bit candidates. `Err(k)` if the stream is exhausted after `k` coefficients (the
1141/// caller then squeezes more — SHAKE output is a stream, so a longer squeeze extends this one's prefix).
1142fn try_sample_ntt(stream: &[u8], want: usize) -> Result<Vec<i64>, usize> {
1143    let q = Q as u32;
1144    let mut a = Vec::with_capacity(want);
1145    let mut i = 0usize;
1146    while a.len() < want {
1147        if i + 3 > stream.len() {
1148            return Err(a.len());
1149        }
1150        let (b0, b1, b2) = (stream[i] as u32, stream[i + 1] as u32, stream[i + 2] as u32);
1151        let d1 = b0 + 256 * (b1 % 16);
1152        let d2 = (b1 / 16) + 16 * b2;
1153        if d1 < q {
1154            a.push(d1 as i64);
1155        }
1156        if d2 < q && a.len() < want {
1157            a.push(d2 as i64);
1158        }
1159        i += 3;
1160    }
1161    Ok(a)
1162}
1163
1164/// Expand one NTT-domain matrix entry Â[i][j] (FIPS 203 §5.1): XOF = SHAKE128(ρ ‖ i ‖ j), then
1165/// SampleNTT. Squeezes 168-byte SHAKE128 blocks until 256 coefficients are sampled — never
1166/// truncates (the rejection rate makes one extra block astronomically rare, but the loop is exact).
1167fn mlkem_sample_a_raw(seed: &[u8], idx_i: i64, idx_j: i64) -> Vec<i64> {
1168    // Streaming SHAKE128 rejection sampling: absorb ρ‖i‖j once, then squeeze 168-byte blocks and
1169    // reject directly from each block (168 = 56·3, so the 3-byte candidate triples never straddle a
1170    // block boundary — bit-identical to sampling the concatenated stream). No heap stream, no
1171    // re-squeeze-from-scratch.
1172    let mut xof_in = [0u8; 34];
1173    xof_in[..32].copy_from_slice(sample_seed(seed));
1174    xof_in[32] = sample_index(idx_i);
1175    xof_in[33] = sample_index(idx_j);
1176    let mut st = crate::keccak::shake128_absorb(&xof_in);
1177
1178    let q = Q as u32;
1179    let mut out = Vec::with_capacity(256);
1180    let mut buf = [0u8; 168];
1181    loop {
1182        for i in 0..21 {
1183            buf[i * 8..i * 8 + 8].copy_from_slice(&st[i].to_le_bytes());
1184        }
1185        let mut k = 0;
1186        while k + 3 <= 168 && out.len() < 256 {
1187            let (b0, b1, b2) = (buf[k] as u32, buf[k + 1] as u32, buf[k + 2] as u32);
1188            let d1 = b0 + 256 * (b1 % 16);
1189            let d2 = (b1 / 16) + 16 * b2;
1190            if d1 < q {
1191                out.push(d1 as i64);
1192            }
1193            if d2 < q && out.len() < 256 {
1194                out.push(d2 as i64);
1195            }
1196            k += 3;
1197        }
1198        if out.len() >= 256 {
1199            return out;
1200        }
1201        crate::keccak::keccak_f1600(&mut st);
1202    }
1203}
1204
1205/// The compiled form of LOGOS `sampleNtt(stream)` — rejection-sample a uniform NTT-domain
1206/// polynomial directly from a caller-provided byte stream.
1207pub fn mlkem_sample_ntt(stream: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1208    let bytes = args::bytes("stream", stream)?;
1209    try_sample_ntt(&bytes, 256)
1210        .map(logicaffeine_data::LogosSeq::from_vec)
1211        .map_err(|k| format!("the stream ran out after {k} of 256 coefficients"))
1212}
1213
1214/// The compiled form of LOGOS `sampleA(seed, i, j)` — expand matrix entry Â\[i\]\[j\] from the
1215/// 32-byte seed ρ via SHAKE128, with the XOF and rejection handled in one verified step.
1216pub fn mlkem_sample_a(
1217    seed: &[i64],
1218    idx_i: i64,
1219    idx_j: i64,
1220) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1221    let (seed, i, j) = matrix_entry_args(seed, idx_i, idx_j)?;
1222    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_sample_a_raw(
1223        &seed, i, j,
1224    )))
1225}
1226
1227/// The ρ and the row and column a matrix-entry kernel takes: 32 bytes and two byte indices.
1228fn matrix_entry_args(seed: &[i64], i: i64, j: i64) -> Result<([u8; 32], i64, i64), String> {
1229    Ok((
1230        args::byte_array::<32>("seed", seed)?,
1231        args::int_in("row index", i, 0, 255)?,
1232        args::int_in("column index", j, 0, 255)?,
1233    ))
1234}
1235
1236// ── Word16/Word8 LOGOS native entries (LogosSeq carrier) + native modular arithmetic ──────────
1237// The full Word16-representation ML-KEM rides on these: the SHIPPED `crypto.lg` calls them, the
1238// coefficient hot loop never touches i64, and the byte edges convert cheaply (≤1184 B).
1239
1240type Seq16 = logicaffeine_data::LogosSeq<Word16>;
1241type Seq8 = logicaffeine_data::LogosSeq<Word8>;
1242#[inline]
1243fn w8_to_u8(s: &[Word8]) -> Vec<u8> {
1244    s.iter().map(|w| w.0).collect()
1245}
1246#[inline]
1247fn u8_to_seq8(v: Vec<u8>) -> Seq8 {
1248    logicaffeine_data::LogosSeq::from_vec(v.into_iter().map(Word8).collect())
1249}
1250
1251pub fn mlkem_inv_ntt_w16_seq(input: &[Word16]) -> Result<Seq16, String> {
1252    reduced_words("polynomial", input)?;
1253    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_inv_ntt_w16(
1254        input,
1255    )))
1256}
1257pub fn mlkem_base_mul_w16_seq(a: &[Word16], b: &[Word16]) -> Result<Seq16, String> {
1258    reduced_words("first polynomial", a)?;
1259    reduced_words("second polynomial", b)?;
1260    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_base_mul_w16(
1261        a, b,
1262    )))
1263}
1264pub fn mlkem_to_mont_w16_seq(c: &[Word16]) -> Result<Seq16, String> {
1265    args::words_below("polynomial", c, Q as u16)?;
1266    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_to_mont_w16(c)))
1267}
1268pub fn mlkem_compress_w16_seq(c: &[Word16], d: i64) -> Result<Seq16, String> {
1269    let d = args::int_in("width d", d, 1, 11)?;
1270    args::words_below("polynomial", c, Q as u16)?;
1271    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_compress_w16(
1272        c, d as usize,
1273    )))
1274}
1275pub fn mlkem_decompress_w16_seq(c: &[Word16], d: i64) -> Result<Seq16, String> {
1276    let d = args::int_in("width d", d, 1, 11)?;
1277    args::words_below("compressed values", c, 1 << d)?;
1278    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_decompress_w16(
1279        c, d as usize,
1280    )))
1281}
1282pub fn mlkem_byte_encode_w16_seq(c: &[Word16], d: i64) -> Result<Seq8, String> {
1283    let d = encodable_words(c, d)?;
1284    Ok(u8_to_seq8(mlkem_byte_encode_w16(c, d)))
1285}
1286pub fn mlkem_byte_decode_w16_seq(b: &[Word8], d: i64) -> Result<Seq16, String> {
1287    let d = args::int_in("width d", d, 1, 12)? as usize;
1288    if b.len() != 32 * d {
1289        return Err(format!(
1290            "the encoding is {} bytes; it must be {}",
1291            b.len(),
1292            32 * d
1293        ));
1294    }
1295    Ok(logicaffeine_data::LogosSeq::from_vec(
1296        mlkem_byte_decode_w16(&w8_to_u8(b), d),
1297    ))
1298}
1299pub fn mlkem_cbd2_w16_seq(buf: &[Word8]) -> Result<Seq16, String> {
1300    word8_count("randomness", buf, 128)?;
1301    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_cbd2_w16(
1302        &w8_to_u8(buf),
1303    )))
1304}
1305pub fn mlkem_cbd3_w16_seq(buf: &[Word8]) -> Result<Seq16, String> {
1306    word8_count("randomness", buf, 192)?;
1307    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_cbd3_w16(
1308        &w8_to_u8(buf),
1309    )))
1310}
1311pub fn mlkem_sample_a_w16_seq(seed: &[Word8], i: i64, j: i64) -> Result<Seq16, String> {
1312    word8_count("seed", seed, 32)?;
1313    let i = args::int_in("row index", i, 0, 255)?;
1314    let j = args::int_in("column index", j, 0, 255)?;
1315    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_sample_a_w16(
1316        &w8_to_u8(seed),
1317        i,
1318        j,
1319    )))
1320}
1321
1322/// A `Seq of Word8` byte string of exactly `n` bytes.
1323fn word8_count(what: &str, s: &[Word8], n: usize) -> Result<(), String> {
1324    if s.len() == n {
1325        Ok(())
1326    } else {
1327        Err(format!("the {what} is {} bytes; it must be {n}", s.len()))
1328    }
1329}
1330
1331/// The width and polynomial a Word16 ByteEncode takes: d from 1 to 12, 256 coefficients, each a
1332/// d-bit integer (or below q for d = 12).
1333fn encodable_words(c: &[Word16], d: i64) -> Result<usize, String> {
1334    let d = args::int_in("width d", d, 1, 12)?;
1335    args::count("polynomial", c.len(), 256)?;
1336    args::words_below("polynomial", c, encoded_bound(d) as u16)?;
1337    Ok(d as usize)
1338}
1339pub fn sha3_256_w8_seq(input: &[Word8]) -> Seq8 {
1340    u8_to_seq8(crate::keccak::sha3_256_bytes(&w8_to_u8(input)).to_vec())
1341}
1342pub fn sha3_512_w8_seq(input: &[Word8]) -> Seq8 {
1343    u8_to_seq8(crate::keccak::sha3_512_bytes(&w8_to_u8(input)).to_vec())
1344}
1345pub fn shake128_w8_seq(input: &[Word8], outlen: i64) -> Result<Seq8, String> {
1346    let outlen = args::non_negative("output length", outlen)?;
1347    Ok(u8_to_seq8(crate::keccak::shake128_bytes(
1348        &w8_to_u8(input),
1349        outlen,
1350    )))
1351}
1352pub fn shake256_w8_seq(input: &[Word8], outlen: i64) -> Result<Seq8, String> {
1353    let outlen = args::non_negative("output length", outlen)?;
1354    Ok(u8_to_seq8(crate::keccak::shake256_bytes(
1355        &w8_to_u8(input),
1356        outlen,
1357    )))
1358}
1359
1360/// `(a + b) mod q`, element-wise on Word16 [0, q) — the native modular-add the Logos matrix-vector
1361/// loop calls (so the orchestration never does Word16 arithmetic, only structure).
1362pub fn mlkem_add_mod_q_w16(a: &[Word16], b: &[Word16]) -> Result<Seq16, String> {
1363    modular_operands(a, b)?;
1364    // Operands ∈ [0, q) ⇒ a + b ∈ [0, 2q): one conditional subtract (auto-vectorizes 16-wide), no
1365    // division — this is the Logos ML-KEM matrix-vector loop's inner reduction (called ~9×/keygen).
1366    Ok(logicaffeine_data::LogosSeq::from_vec(
1367        a.iter()
1368            .zip(b)
1369            .map(|(x, y)| Word16(csub_q(x.0 + y.0)))
1370            .collect(),
1371    ))
1372}
1373/// `(a − b) mod q`, element-wise on Word16 [0, q).
1374pub fn mlkem_sub_mod_q_w16(a: &[Word16], b: &[Word16]) -> Result<Seq16, String> {
1375    modular_operands(a, b)?;
1376    // Operands ∈ [0, q) ⇒ a − b ∈ (−q, q): one conditional add, no division.
1377    Ok(logicaffeine_data::LogosSeq::from_vec(
1378        a.iter()
1379            .zip(b)
1380            .map(|(x, y)| Word16(cadd_q(x.0 as i16 - y.0 as i16)))
1381            .collect(),
1382    ))
1383}
1384/// The two operands of a coefficient-wise modular add or subtract: as many coefficients each, all
1385/// reduced into [0, q).
1386fn modular_operands(a: &[Word16], b: &[Word16]) -> Result<(), String> {
1387    args::same_count("operands", a.len(), b.len())?;
1388    args::words_below("first operand", a, Q as u16)?;
1389    args::words_below("second operand", b, Q as u16)
1390}
1391
1392/// A run of `n` zero coefficients (Word16).
1393pub fn mlkem_zeros_w16(n: i64) -> Result<Seq16, String> {
1394    let n = args::non_negative("count", n)?;
1395    Ok(logicaffeine_data::LogosSeq::from_vec(vec![Word16(0); n]))
1396}
1397
1398// Int↔Word16 bridges at the byte edges: ML-KEM byte buffers stay LOGOS `Seq of Int` (so the AOT
1399// gates / hashing are unchanged), only the COEFFICIENT hot loop is Word16. Cheap (≤1184 bytes).
1400pub fn mlkem_cbd2_w16_from_int(buf: &[i64]) -> Result<Seq16, String> {
1401    let bytes = args::exact_bytes("randomness", buf, 128)?;
1402    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_cbd2_w16(
1403        &bytes,
1404    )))
1405}
1406pub fn mlkem_byte_encode_w16_to_int(
1407    c: &[Word16],
1408    d: i64,
1409) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
1410    let d = encodable_words(c, d)?;
1411    Ok(args::seq_of_bytes(&mlkem_byte_encode_w16(c, d)))
1412}
1413pub fn mlkem_byte_decode_w16_from_int(b: &[i64], d: i64) -> Result<Seq16, String> {
1414    let d = args::int_in("width d", d, 1, 12)? as usize;
1415    let bytes = args::exact_bytes("encoding", b, 32 * d)?;
1416    Ok(logicaffeine_data::LogosSeq::from_vec(
1417        mlkem_byte_decode_w16(&bytes, d),
1418    ))
1419}
1420pub fn mlkem_sample_a_w16_from_int(seed: &[i64], i: i64, j: i64) -> Result<Seq16, String> {
1421    let (seed, i, j) = matrix_entry_args(seed, i, j)?;
1422    Ok(logicaffeine_data::LogosSeq::from_vec(mlkem_sample_a_w16(
1423        &seed, i, j,
1424    )))
1425}
1426/// Native entry for the full 3×3 matrix  (9 × 256 Word16, entry Â\[r\]\[c\] at slot `(r·3+c)·256`),
1427/// 4-way AVX2 SHAKE128 batched — the shipped-Logos `mlkemSampleMatrixW16(rho)`.
1428pub fn mlkem_sample_matrix_w16_from_int(seed: &[i64]) -> Result<Seq16, String> {
1429    let seed = args::byte_array::<32>("seed", seed)?;
1430    Ok(logicaffeine_data::LogosSeq::from_vec(
1431        mlkem_sample_matrix_w16(&seed),
1432    ))
1433}
1434
1435#[cfg(test)]
1436#[path = "../../logicaffeine_tests/unit/logicaffeine_system/ntt/tests.rs"]
1437mod tests;