Skip to main content

kodamaembed_cpu/
encoder.rs

1//! CPU transformer encoder for packed sequences.
2
3#[cfg(target_arch = "x86_64")]
4use crate::int8::{DeferredNorm, Operand};
5use crate::{
6    CpuPrecision,
7    attention::attention_current_pool,
8    gemm::{Epilogue, Kernel, NR, PackedWeight, gemm_current_pool},
9    math,
10    projection::Projection,
11    workers::{POOL, SHORT_POOL, Workers},
12};
13#[cfg(target_arch = "x86_64")]
14use kodamaembed_model::repro::Kind;
15use kodamaembed_model::{
16    Activation, Head, Output, Pooling, Positions, Profile, Rotary, STAGES, Shape, Stage, Tensors,
17    fused_qkv, relative::RelativeBias, repro::restored_class, tensor, tensor_len,
18};
19use rayon::prelude::*;
20use std::{fmt, num::NonZeroUsize, time::Instant};
21
22/// Token rows per task in the row-wise kernels.
23const ROWS: usize = 64;
24
25/// Short inputs take fewer rows a task, so every worker gets some.
26fn rows_per_task(tokens: usize) -> usize {
27    tokens.div_ceil(rayon::current_num_threads()).clamp(1, ROWS)
28}
29
30/// Token limit for the smaller pool, which reduces short-batch scheduling overhead.
31const SHORT_TOKENS: usize = 256;
32
33/// One sequence's token ids and segment types.
34pub type TokenSequence = (Vec<i32>, Vec<i32>);
35
36/// The mean of the sequences' key means: the center nearest them in squared distance.
37#[cfg(target_arch = "x86_64")]
38fn key_means(qkv: &[f32], hidden: usize, firsts: &[usize], lengths: &[usize]) -> Vec<f64> {
39    let mut total = vec![0.0f64; hidden];
40    let mut sequence = vec![0.0f64; hidden];
41    for (&first, &len) in firsts.iter().zip(lengths) {
42        sequence.fill(0.0);
43        for row in first..first + len {
44            for (sum, &x) in sequence
45                .iter_mut()
46                .zip(&qkv[row * 3 * hidden + hidden..][..hidden])
47            {
48                *sum += f64::from(x);
49            }
50        }
51        for (all, &sum) in total.iter_mut().zip(&sequence) {
52            *all += sum / len as f64;
53        }
54    }
55    total.iter().map(|&sum| sum / firsts.len() as f64).collect()
56}
57
58#[cfg(target_arch = "x86_64")]
59fn class_means(rows: &[f32], width: usize, firsts: &[usize], lasts: &[usize]) -> Vec<f64> {
60    let mut means = vec![0.0; 2 * width];
61    for (mean, picks) in means.chunks_exact_mut(width).zip([firsts, lasts]) {
62        for &row in picks {
63            for (sum, &x) in mean.iter_mut().zip(&rows[row * width..(row + 1) * width]) {
64                *sum += f64::from(x);
65            }
66        }
67        for sum in mean {
68            *sum /= picks.len() as f64;
69        }
70    }
71    means
72}
73
74#[cfg(target_arch = "x86_64")]
75fn middle_mean(
76    rows: &[f32],
77    width: usize,
78    firsts: &[usize],
79    lengths: &[usize],
80) -> Option<Vec<f64>> {
81    let mut mean = vec![0.0; width];
82    let mut sequences = 0;
83    for (&first, &len) in firsts.iter().zip(lengths).filter(|(_, len)| **len > 2) {
84        let mut own = vec![0.0; width];
85        for row in rows[(first + 1) * width..(first + len - 1) * width].chunks_exact(width) {
86            for (sum, &x) in own.iter_mut().zip(row) {
87                *sum += f64::from(x);
88            }
89        }
90        for (total, sum) in mean.iter_mut().zip(own) {
91            *total += sum / (len - 2) as f64;
92        }
93        sequences += 1;
94    }
95    (sequences > 0).then(|| {
96        mean.into_iter()
97            .map(|total| total / f64::from(sequences))
98            .collect()
99    })
100}
101
102/// Worker counts change only partitioning, never reduction order or bits.
103fn pool_for(own: Option<&Workers>, tokens: usize) -> &Workers {
104    match own {
105        Some(pool) => pool,
106        None if tokens <= SHORT_TOKENS => SHORT_POOL.as_ref().unwrap_or(&POOL),
107        None => &POOL,
108    }
109}
110
111struct Timer {
112    last: Instant,
113    milliseconds: [f64; STAGES.len()],
114}
115
116fn mark(timer: &mut Option<Timer>, stage: Stage) {
117    if let Some(timer) = timer {
118        let now = Instant::now();
119        timer.milliseconds[stage as usize] += (now - timer.last).as_secs_f64() * 1e3;
120        timer.last = now;
121    }
122}
123
124#[derive(Debug)]
125pub enum EncoderError {
126    Unsupported(String),
127    Weights(String),
128    Input(String),
129}
130
131impl fmt::Display for EncoderError {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        match self {
134            Self::Unsupported(reason) => write!(f, "unsupported model: {reason}"),
135            Self::Weights(reason) => write!(f, "weights: {reason}"),
136            Self::Input(reason) => write!(f, "input: {reason}"),
137        }
138    }
139}
140
141impl std::error::Error for EncoderError {}
142
143struct Norm {
144    gamma: Vec<f32>,
145    beta: Vec<f32>,
146    eps: f32,
147}
148
149impl Norm {
150    /// None when the mean or variance + eps is not finite.
151    fn moments(&self, row: &[f32]) -> Option<(f32, f32)> {
152        let n = row.len() as f32;
153        let mean = lane_sum(row, |x| x) / n;
154        let variance = lane_sum(row, |x| (x - mean) * (x - mean)) / n;
155        let denominator = variance + self.eps;
156        (mean.is_finite() && denominator.is_finite()).then(|| (mean, 1.0 / denominator.sqrt()))
157    }
158
159    fn apply(&self, row: &mut [f32]) {
160        self.normalize(row, self.moments(row));
161    }
162
163    /// A row whose variance overflows becomes NaN, not zeros: the output check rejects it.
164    fn normalize(&self, row: &mut [f32], moments: Option<(f32, f32)>) {
165        let Some((mean, rstd)) = moments else {
166            row.fill(f32::NAN);
167            return;
168        };
169        for ((x, &gamma), &beta) in row.iter_mut().zip(&self.gamma).zip(&self.beta) {
170            *x = (*x - mean) * rstd * gamma + beta;
171        }
172    }
173
174    fn apply_rows(&self, rows: &mut [f32], half: bool) {
175        let width = self.gamma.len();
176        let per = rows_per_task(rows.len() / width);
177        rows.par_chunks_mut(per * width).for_each(|chunk| {
178            round_half(chunk, half);
179            for row in chunk.chunks_exact_mut(width) {
180                self.apply(row);
181            }
182            round_half(chunk, half);
183        });
184    }
185
186    /// Also keeps the rows and statistics the deferred projection reads.
187    fn apply_rows_keeping(&self, rows: &mut [f32], half: bool, input: &mut NormInput) {
188        let width = self.gamma.len();
189        let tokens = rows.len() / width;
190        input.resize(tokens, width);
191        let per = rows_per_task(tokens);
192        rows.par_chunks_mut(per * width)
193            .zip(input.rows.par_chunks_mut(per * width))
194            .zip(
195                input
196                    .mean
197                    .par_chunks_mut(per)
198                    .zip(input.rstd.par_chunks_mut(per)),
199            )
200            .for_each(|((chunk, kept), (means, rstds))| {
201                round_half(chunk, half);
202                kept.copy_from_slice(chunk);
203                for ((row, mean), rstd) in chunk.chunks_exact_mut(width).zip(means).zip(rstds) {
204                    let moments = self.moments(row);
205                    (*mean, *rstd) = moments.unwrap_or((f32::NAN, f32::NAN));
206                    self.normalize(row, moments);
207                }
208                round_half(chunk, half);
209            });
210    }
211}
212
213/// A deferred projection's input: the norm's rows as read and their statistics.
214#[derive(Default)]
215struct NormInput {
216    rows: Vec<f32>,
217    mean: Vec<f32>,
218    rstd: Vec<f32>,
219}
220
221impl NormInput {
222    fn resize(&mut self, tokens: usize, width: usize) {
223        self.rows.resize(tokens * width, 0.0);
224        self.mean.resize(tokens, 0.0);
225        self.rstd.resize(tokens, 0.0);
226    }
227}
228
229/// Integer attention rounds residuals and norms to FP16, as projection inputs are.
230fn round_half(rows: &mut [f32], half: bool) {
231    if !half {
232        return;
233    }
234    #[cfg(target_arch = "x86_64")]
235    // SAFETY: only integer-attention encoders round, and they require F16C.
236    unsafe {
237        crate::math::avx2::round_to_fp16(rows)
238    };
239    #[cfg(not(target_arch = "x86_64"))]
240    {
241        let _ = rows;
242        panic!("FP16 residual rows belong to integer attention, which requires x86-64");
243    }
244}
245
246/// 32 lane sums halved by partners, in a GPU warp's xor-shuffle order: the same bits on both.
247fn lane_sum<T: Copy + Default + std::ops::AddAssign>(values: &[T], f: impl Fn(T) -> T) -> T {
248    let (chunks, tail) = values.as_chunks::<32>();
249    let mut lanes = [T::default(); 32];
250    for chunk in chunks {
251        for (lane, &x) in lanes.iter_mut().zip(chunk) {
252            *lane += f(x);
253        }
254    }
255    for (lane, &x) in lanes.iter_mut().zip(tail) {
256        *lane += f(x);
257    }
258    let mut width = 16;
259    while width > 0 {
260        for j in 0..width {
261            lanes[j] += lanes[j + width];
262        }
263        width /= 2;
264    }
265    lanes[0]
266}
267
268struct Embeddings {
269    word: Vec<f32>,
270    position: Vec<f32>,
271    token_type: Vec<f32>,
272    norm: Norm,
273}
274
275impl Embeddings {
276    fn apply(&self, ids: &[i32], types: &[i32], positions: &[i32], out: &mut [f32], half: bool) {
277        let h = self.norm.gamma.len();
278        let per = rows_per_task(positions.len());
279        out.par_chunks_mut(per * h)
280            .enumerate()
281            .for_each(|(chunk, out)| {
282                for (r, row) in out.chunks_exact_mut(h).enumerate() {
283                    let token = chunk * per + r;
284                    let word = &self.word[ids[token] as usize * h..][..h];
285                    let segment = &self.token_type[types[token] as usize * h..][..h];
286                    let position = &self.position[positions[token] as usize * h..][..h];
287                    for (((x, &w), &s), &p) in row.iter_mut().zip(word).zip(segment).zip(position) {
288                        *x = (w + s) + p;
289                    }
290                    self.norm.apply(row);
291                }
292                round_half(out, half);
293            });
294    }
295}
296
297/// A BERT layer: a norm after attention and after the feed-forward.
298struct Layer {
299    qkv: Projection,
300    qkv_bias: Vec<f32>,
301    key_centers: Option<Vec<f32>>,
302    out: Projection,
303    out_bias: Vec<f32>,
304    norm1: Norm,
305    up: Projection,
306    up_bias: Vec<f32>,
307    down: Projection,
308    down_bias: Vec<f32>,
309    norm2: Norm,
310}
311
312/// A ModernBERT layer: a norm before attention and before the gated feed-forward, no biases.
313struct ModernLayer {
314    /// None in the first layer, which attends over the embedding norm's rows as they are.
315    attention_norm: Option<Norm>,
316    qkv: PackedWeight,
317    out: PackedWeight,
318    feed_forward_norm: Norm,
319    /// The up projection's rows by half: the activated inputs, then their gates.
320    inputs: PackedWeight,
321    gates: PackedWeight,
322    down: PackedWeight,
323}
324
325/// Rotary positions: [`Rotary::turns`] for one rotation base.
326struct Turns(Vec<f32>);
327
328impl Turns {
329    /// Turns each head's query and key in every qkv row by its token's position.
330    fn apply(&self, qkv: &mut [f32], hidden: usize, head: usize, positions: &[i32]) {
331        let pairs = head / 2;
332        let per = rows_per_task(positions.len());
333        qkv.par_chunks_mut(per * 3 * hidden)
334            .zip(positions.par_chunks(per))
335            .for_each(|(rows, positions)| {
336                for (row, &position) in rows.chunks_exact_mut(3 * hidden).zip(positions) {
337                    let turns = &self.0[position as usize * head..][..head];
338                    let (cos, sin) = turns.split_at(pairs);
339                    for vector in row[..2 * hidden].chunks_exact_mut(head) {
340                        let (first, second) = vector.split_at_mut(pairs);
341                        for (((x, y), &c), &s) in first.iter_mut().zip(second).zip(cos).zip(sin) {
342                            (*x, *y) = (*x * c - *y * s, *y * c + *x * s);
343                        }
344                    }
345                }
346            });
347    }
348}
349
350/// BERT, RoBERTa and MPNet: tables for positions and segments, and layers that norm afterwards.
351struct Bert {
352    embeddings: Embeddings,
353    layers: Vec<Layer>,
354    relative: Option<RelativeBias>,
355}
356
357/// ModernBERT: positions turn the queries and keys, and layers norm beforehand.
358struct Modern {
359    rotary: Rotary,
360    word: Vec<f32>,
361    embedding_norm: Norm,
362    layers: Vec<ModernLayer>,
363    /// The turns of the layers over whole sequences, and of the windowed ones.
364    global_turns: Turns,
365    local_turns: Turns,
366    final_norm: Norm,
367    /// What every projection adds as its bias: the family has none.
368    no_bias: Vec<f32>,
369    /// A sublayer's normed input, and the feed-forward's gates.
370    normed: Vec<f32>,
371    gates: Vec<f32>,
372}
373
374/// A model family's weights.
375enum Family {
376    Bert(Box<Bert>),
377    Modern(Box<Modern>),
378}
379
380#[cfg(target_arch = "x86_64")]
381struct Calibrated {
382    projections: [Projection; 4],
383    keys: Option<Vec<f32>>,
384}
385
386struct Workspace {
387    hidden: Vec<f32>,
388    qkv: Vec<f32>,
389    context: Vec<f32>,
390    attended: Vec<f32>,
391    intermediate: Vec<f32>,
392    norm1_input: NormInput,
393    norm2_input: NormInput,
394}
395
396impl Workspace {
397    fn new(shape: &Shape, tokens: usize) -> Result<Self, EncoderError> {
398        let (h, i) = (shape.hidden, shape.intermediate);
399        let hidden = tensor_len(&[tokens, h]).map_err(EncoderError::Unsupported)?;
400        let qkv = tensor_len(&[tokens, 3, h]).map_err(EncoderError::Unsupported)?;
401        let intermediate = tensor_len(&[tokens, i]).map_err(EncoderError::Unsupported)?;
402        Ok(Self {
403            hidden: zeros(hidden)?,
404            qkv: zeros(qkv)?,
405            context: zeros(hidden)?,
406            attended: zeros(hidden)?,
407            intermediate: zeros(intermediate)?,
408            norm1_input: NormInput::default(),
409            norm2_input: NormInput::default(),
410        })
411    }
412}
413
414/// Allocation failure is an error, not an abort.
415fn zeros(len: usize) -> Result<Vec<f32>, EncoderError> {
416    let layout = std::alloc::Layout::array::<f32>(len)
417        .map_err(|_| EncoderError::Unsupported(format!("{len} activations overflow a layout")))?;
418    if layout.size() == 0 {
419        return Ok(Vec::new());
420    }
421    // SAFETY: the layout has a nonzero size.
422    let at = unsafe { std::alloc::alloc_zeroed(layout) }.cast::<f32>();
423    if at.is_null() {
424        return Err(EncoderError::Unsupported(format!(
425            "{len} activations exceed the memory available"
426        )));
427    }
428    // SAFETY: `at` holds `len` zeroed f32 values from this layout.
429    Ok(unsafe { Vec::from_raw_parts(at, len, len) })
430}
431
432/// A batch's token count, once it fits `max_tokens` and the model.
433fn checked_tokens(
434    shape: &Shape,
435    max_tokens: usize,
436    ids: &[i32],
437    types: &[i32],
438    lengths: &[usize],
439) -> Result<usize, EncoderError> {
440    let tokens = checked_input(shape, ids, types, lengths)?;
441    if tokens > max_tokens {
442        return Err(EncoderError::Input(format!(
443            "{tokens} tokens (limit {max_tokens})"
444        )));
445    }
446    Ok(tokens)
447}
448
449fn checked_input(
450    shape: &Shape,
451    ids: &[i32],
452    types: &[i32],
453    lengths: &[usize],
454) -> Result<usize, EncoderError> {
455    let tokens = lengths
456        .iter()
457        .try_fold(0usize, |total, &len| total.checked_add(len))
458        .ok_or_else(|| EncoderError::Input("sequence lengths overflow usize".into()))?;
459    let max_len = lengths.iter().copied().max().unwrap_or(0);
460    if lengths.is_empty() || lengths.contains(&0) || tokens != ids.len() {
461        return Err(EncoderError::Input(format!(
462            "{} ids for lengths summing to {tokens}, with no empty sequence allowed",
463            ids.len()
464        )));
465    }
466    if types.len() != ids.len() {
467        return Err(EncoderError::Input(format!(
468            "{} segment types for {} ids",
469            types.len(),
470            ids.len()
471        )));
472    }
473    if max_len > shape.max_sequence_len() {
474        return Err(EncoderError::Input(format!(
475            "a sequence of {max_len} tokens (limit {})",
476            shape.max_sequence_len()
477        )));
478    }
479    let vocab = shape.vocab as i32;
480    if let Some(bad) = ids.iter().find(|&&id| !(0..vocab).contains(&id)) {
481        return Err(EncoderError::Input(format!(
482            "token id {bad} outside the vocabulary"
483        )));
484    }
485    let segments = shape.type_vocab as i32;
486    if let Some(bad) = types.iter().find(|&&kind| !(0..segments).contains(&kind)) {
487        return Err(EncoderError::Input(format!(
488            "segment type {bad} outside the {segments} the model has"
489        )));
490    }
491    Ok(tokens)
492}
493
494#[derive(Clone, Copy)]
495struct ExecutionOptions {
496    kernel: Kernel,
497    integer_attention: bool,
498    half_residual: bool,
499    /// For calibration's means; centered layers keep them anyway: deferred projections read them.
500    keep_norm_inputs: bool,
501    /// Calibration's own pass centers keys on their sequences' means instead.
502    static_keys: bool,
503}
504
505impl Layer {
506    /// Both norms defer: QKV reads the previous layer's kept input, the up projection this layer's.
507    #[allow(clippy::too_many_arguments)]
508    fn apply(
509        &self,
510        execution: ExecutionOptions,
511        heads: usize,
512        relative: Option<&RelativeBias>,
513        lengths: &[usize],
514        restored: Option<&[u32]>,
515        tokens: usize,
516        w: &mut Workspace,
517        timer: &mut Option<Timer>,
518    ) -> Result<(), EncoderError> {
519        let ExecutionOptions {
520            kernel,
521            integer_attention,
522            half_residual,
523            keep_norm_inputs,
524            static_keys,
525        } = execution;
526        let keep = keep_norm_inputs || restored.is_some();
527        // Restart restored chains at hidden-width boundaries for batch-invariant rounding.
528        let h = self.out.n();
529        let project =
530            |projection: &Projection, input: &[f32], epilogue: Epilogue<'_>, output: &mut [f32]| {
531                match restored {
532                    Some(classes) => projection
533                        .apply_restored(kernel, input, tokens, classes, h, epilogue, output),
534                    None => projection.apply(kernel, input, tokens, epilogue, output),
535                }
536            };
537        let Workspace {
538            hidden,
539            qkv,
540            context,
541            attended,
542            intermediate,
543            norm1_input,
544            norm2_input,
545        } = w;
546        let hidden = &mut hidden[..tokens * h];
547        let qkv = &mut qkv[..tokens * 3 * h];
548        let context = &mut context[..tokens * h];
549        let attended = &mut attended[..tokens * h];
550        let intermediate = &mut intermediate[..tokens * self.up.n()];
551        match restored.filter(|_| self.qkv.defers()) {
552            Some(classes) => self.qkv.apply_deferred(
553                kernel,
554                &norm2_input.rows,
555                tokens,
556                classes,
557                &norm2_input.mean,
558                &norm2_input.rstd,
559                false,
560                h,
561                qkv,
562            )?,
563            None => project(&self.qkv, hidden, Epilogue::Bias(&self.qkv_bias), qkv)?,
564        }
565        mark(timer, Stage::Qkv);
566        attention_current_pool(
567            kernel,
568            qkv,
569            lengths,
570            h,
571            heads,
572            integer_attention,
573            self.key_centers.as_deref().filter(|_| static_keys),
574            relative,
575            None,
576            context,
577        );
578        mark(timer, Stage::Attention);
579        project(
580            &self.out,
581            context,
582            Epilogue::BiasResidual(&self.out_bias, hidden),
583            attended,
584        )?;
585        mark(timer, Stage::Out);
586        if keep {
587            self.norm1
588                .apply_rows_keeping(attended, half_residual, norm1_input);
589        } else {
590            self.norm1.apply_rows(attended, half_residual);
591        }
592        mark(timer, Stage::Norm1);
593        match restored.filter(|_| self.up.defers()) {
594            Some(classes) => self.up.apply_deferred(
595                kernel,
596                &norm1_input.rows,
597                tokens,
598                classes,
599                &norm1_input.mean,
600                &norm1_input.rstd,
601                true,
602                h,
603                intermediate,
604            )?,
605            None => project(
606                &self.up,
607                attended,
608                Epilogue::BiasGelu(&self.up_bias),
609                intermediate,
610            )?,
611        }
612        mark(timer, Stage::Ffn1);
613        project(
614            &self.down,
615            intermediate,
616            Epilogue::BiasResidual(&self.down_bias, attended),
617            hidden,
618        )?;
619        mark(timer, Stage::Ffn2);
620        if keep {
621            self.norm2
622                .apply_rows_keeping(hidden, half_residual, norm2_input);
623        } else {
624            self.norm2.apply_rows(hidden, half_residual);
625        }
626        mark(timer, Stage::Norm2);
627        Ok(())
628    }
629}
630
631impl Bert {
632    fn load(shape: &Shape, tensors: &dyn Tensors) -> Result<Self, EncoderError> {
633        let (h, i) = (shape.hidden, shape.intermediate);
634        let get =
635            |name: &str, len: usize| tensor(tensors, name, len).map_err(EncoderError::Weights);
636        let norm = |name: &str| -> Result<Norm, EncoderError> {
637            Ok(Norm {
638                gamma: get(&format!("{name}.weight"), h)?,
639                beta: get(&format!("{name}.bias"), h)?,
640                eps: shape.eps,
641            })
642        };
643        let embeddings = Embeddings {
644            word: get("embeddings.word_embeddings.weight", shape.vocab * h)?,
645            position: get(
646                "embeddings.position_embeddings.weight",
647                shape.max_positions * h,
648            )?,
649            token_type: get(
650                "embeddings.token_type_embeddings.weight",
651                shape.type_vocab * h,
652            )?,
653            norm: norm("embeddings.LayerNorm")?,
654        };
655        let mut layers: Vec<Layer> = Vec::with_capacity(shape.layers);
656        for layer in 0..shape.layers {
657            let at = |suffix: &str| format!("encoder.layer.{layer}.{suffix}");
658            let (qkv_weights, qkv_bias) =
659                fused_qkv(tensors, shape, layer).map_err(EncoderError::Weights)?;
660            layers.push(Layer {
661                qkv: Projection::new(&qkv_weights, 3 * h, h),
662                qkv_bias,
663                key_centers: None,
664                out: Projection::new(&get(&at("attention.output.dense.weight"), h * h)?, h, h),
665                out_bias: get(&at("attention.output.dense.bias"), h)?,
666                norm1: norm(&at("attention.output.LayerNorm"))?,
667                up: Projection::new(&get(&at("intermediate.dense.weight"), i * h)?, i, h),
668                up_bias: get(&at("intermediate.dense.bias"), i)?,
669                down: Projection::new(&get(&at("output.dense.weight"), h * i)?, h, i),
670                down_bias: get(&at("output.dense.bias"), h)?,
671                norm2: norm(&at("output.LayerNorm"))?,
672            });
673        }
674        Ok(Self {
675            embeddings,
676            layers,
677            relative: RelativeBias::load(shape, tensors).map_err(EncoderError::Weights)?,
678        })
679    }
680
681    /// The calibrated projections and key centers in place of the FP32 ones.
682    #[cfg(target_arch = "x86_64")]
683    fn install(&mut self, built: Vec<Calibrated>) {
684        for (layer, built) in self.layers.iter_mut().zip(built) {
685            let [qkv, out, up, down] = built.projections;
686            (layer.qkv, layer.out, layer.up, layer.down) = (qkv, out, up, down);
687            layer.key_centers = built.keys;
688        }
689    }
690}
691
692impl Modern {
693    fn load(
694        shape: &Shape,
695        rotary: Rotary,
696        max_tokens: usize,
697        tensors: &dyn Tensors,
698    ) -> Result<Self, EncoderError> {
699        let (h, inner) = (shape.hidden, shape.intermediate);
700        let rows = |width: usize| -> Result<Vec<f32>, EncoderError> {
701            zeros(tensor_len(&[max_tokens, width]).map_err(EncoderError::Unsupported)?)
702        };
703        let (normed, gates) = (rows(h)?, rows(inner)?);
704        let get =
705            |name: &str, len: usize| tensor(tensors, name, len).map_err(EncoderError::Weights);
706        let norm = |name: &str| -> Result<Norm, EncoderError> {
707            Ok(Norm {
708                gamma: get(&format!("{name}.weight"), h)?,
709                beta: vec![0.0; h],
710                eps: shape.eps,
711            })
712        };
713        let word = get("embeddings.tok_embeddings.weight", shape.vocab * h)?;
714        let embedding_norm = norm("embeddings.norm")?;
715        let mut layers: Vec<ModernLayer> = Vec::with_capacity(shape.layers);
716        for layer in 0..shape.layers {
717            let at = |suffix: &str| format!("layers.{layer}.{suffix}");
718            let attention_norm = match layer {
719                0 => None,
720                _ => Some(norm(&at("attn_norm"))?),
721            };
722            let qkv = PackedWeight::new(&get(&at("attn.Wqkv.weight"), 3 * h * h)?, 3 * h, h);
723            let out = PackedWeight::new(&get(&at("attn.Wo.weight"), h * h)?, h, h);
724            let feed_forward_norm = norm(&at("mlp_norm"))?;
725            let up = get(&at("mlp.Wi.weight"), 2 * inner * h)?;
726            let (inputs, gates) = up.split_at(inner * h);
727            layers.push(ModernLayer {
728                attention_norm,
729                qkv,
730                out,
731                feed_forward_norm,
732                inputs: PackedWeight::new(inputs, inner, h),
733                gates: PackedWeight::new(gates, inner, h),
734                down: PackedWeight::new(&get(&at("mlp.Wo.weight"), h * inner)?, h, inner),
735            });
736        }
737        let final_norm = norm("final_norm")?;
738        let (head, positions) = (h / shape.heads, max_tokens.min(shape.max_sequence_len()));
739        let turns = |theta: f32| Turns(Rotary::turns(theta, head, positions));
740        Ok(Self {
741            rotary,
742            word,
743            embedding_norm,
744            layers,
745            global_turns: turns(rotary.global_theta),
746            local_turns: turns(rotary.local_theta),
747            final_norm,
748            no_bias: vec![0.0; (3 * h).max(inner)],
749            normed,
750            gates,
751        })
752    }
753
754    /// Embeds the batch and runs every layer and the final norm, which leaves the encoded rows
755    /// in `w.hidden`.
756    #[allow(clippy::too_many_arguments)]
757    fn forward(
758        &mut self,
759        kernel: Kernel,
760        shape: &Shape,
761        ids: &[i32],
762        positions: &[i32],
763        lengths: &[usize],
764        w: &mut Workspace,
765        timer: &mut Option<Timer>,
766    ) {
767        let (h, inner, heads) = (shape.hidden, shape.intermediate, shape.heads);
768        let tokens = ids.len();
769        let Self {
770            rotary,
771            word,
772            embedding_norm,
773            layers,
774            global_turns,
775            local_turns,
776            final_norm,
777            no_bias,
778            normed,
779            gates,
780        } = self;
781        let (qkv_bias, row_bias, inner_bias) =
782            (&no_bias[..3 * h], &no_bias[..h], &no_bias[..inner]);
783        let hidden = &mut w.hidden[..tokens * h];
784        let qkv = &mut w.qkv[..tokens * 3 * h];
785        let context = &mut w.context[..tokens * h];
786        let attended = &mut w.attended[..tokens * h];
787        let inputs = &mut w.intermediate[..tokens * inner];
788        let normed = &mut normed[..tokens * h];
789        let gates = &mut gates[..tokens * inner];
790        let per = rows_per_task(tokens);
791        hidden
792            .par_chunks_mut(per * h)
793            .zip(ids.par_chunks(per))
794            .for_each(|(rows, ids)| {
795                for (row, &id) in rows.chunks_exact_mut(h).zip(ids) {
796                    row.copy_from_slice(&word[id as usize * h..][..h]);
797                    embedding_norm.apply(row);
798                }
799            });
800        mark(timer, Stage::Embed);
801        for (index, layer) in layers.iter().enumerate() {
802            let input: &[f32] = match &layer.attention_norm {
803                Some(norm) => {
804                    normed.copy_from_slice(hidden);
805                    norm.apply_rows(normed, false);
806                    normed
807                }
808                None => hidden,
809            };
810            mark(timer, Stage::Norm1);
811            gemm_current_pool(
812                kernel,
813                input,
814                tokens,
815                &layer.qkv,
816                Epilogue::Bias(qkv_bias),
817                qkv,
818            );
819            let reach = rotary.reach(index);
820            let turns: &Turns = match reach {
821                Some(_) => local_turns,
822                None => global_turns,
823            };
824            turns.apply(qkv, h, h / heads, positions);
825            mark(timer, Stage::Qkv);
826            attention_current_pool(
827                kernel, qkv, lengths, h, heads, false, None, None, reach, context,
828            );
829            mark(timer, Stage::Attention);
830            gemm_current_pool(
831                kernel,
832                context,
833                tokens,
834                &layer.out,
835                Epilogue::BiasResidual(row_bias, hidden),
836                attended,
837            );
838            mark(timer, Stage::Out);
839            normed.copy_from_slice(attended);
840            layer.feed_forward_norm.apply_rows(normed, false);
841            mark(timer, Stage::Norm2);
842            gemm_current_pool(
843                kernel,
844                normed,
845                tokens,
846                &layer.inputs,
847                Epilogue::BiasGelu(inner_bias),
848                inputs,
849            );
850            gemm_current_pool(
851                kernel,
852                normed,
853                tokens,
854                &layer.gates,
855                Epilogue::Bias(inner_bias),
856                gates,
857            );
858            inputs
859                .par_chunks_mut(per * inner)
860                .zip(gates.par_chunks(per * inner))
861                .for_each(|(inputs, gates)| {
862                    for (input, &gate) in inputs.iter_mut().zip(gates) {
863                        *input *= gate;
864                    }
865                });
866            mark(timer, Stage::Ffn1);
867            gemm_current_pool(
868                kernel,
869                inputs,
870                tokens,
871                &layer.down,
872                Epilogue::BiasResidual(row_bias, attended),
873                hidden,
874            );
875            mark(timer, Stage::Ffn2);
876        }
877        final_norm.apply_rows(hidden, false);
878    }
879}
880
881/// Mean pooling and L2 normalization, one output row per sequence.
882#[doc(hidden)]
883pub fn pool_rows(hidden: &[f32], h: usize, lengths: &[usize], out: &mut [f32]) {
884    Finish::Pool(Pooling::Mean).apply(Kernel::Portable, hidden, h, lengths, out);
885}
886
887/// How a cross-encoder's head turns its dense layer's outputs into the classifier's features.
888enum Features {
889    /// BERT's pooler: tanh.
890    Tanh,
891    /// ModernBERT's prediction head: an activation, then a norm.
892    Normed(Activation, Norm),
893}
894
895enum Finish {
896    /// L2-normalized pooled rows, `hidden` values per sequence.
897    Pool(Pooling),
898    /// A cross-encoder's head and classifier, one score per sequence.
899    Score {
900        /// The rows the head's dense layer reads: the first, or their mean.
901        pooling: Pooling,
902        dense: PackedWeight,
903        /// Zeros in a prediction head, whose dense layer has none.
904        dense_bias: Vec<f32>,
905        features: Features,
906        classifier: Vec<f32>,
907        classifier_bias: f32,
908    },
909}
910
911/// The mean of `rows`, each `h` wide, summed in their order.
912fn mean_row(rows: &[f32], h: usize) -> Vec<f64> {
913    let mut mean = vec![0.0f64; h];
914    for row in rows.chunks_exact(h) {
915        for (sum, &x) in mean.iter_mut().zip(row) {
916            *sum += f64::from(x);
917        }
918    }
919    let count = (rows.len() / h) as f64;
920    for m in &mut mean {
921        *m /= count;
922    }
923    mean
924}
925
926impl Finish {
927    fn apply(&self, kernel: Kernel, hidden: &[f32], h: usize, lengths: &[usize], out: &mut [f32]) {
928        let starts: Vec<usize> = lengths
929            .iter()
930            .scan(0, |at, &len| {
931                let start = *at;
932                *at += len;
933                Some(start)
934            })
935            .collect();
936        match self {
937            Self::Pool(pooling) => {
938                out.par_chunks_mut(h)
939                    .zip(starts.par_iter().zip(lengths))
940                    .for_each(|(out, (&start, &len))| {
941                        let mean = mean_row(&hidden[start * h..(start + pooling.rows(len)) * h], h);
942                        let norm = lane_sum(&mean, |m| m * m).sqrt().max(1e-12);
943                        for (o, m) in out.iter_mut().zip(&mean) {
944                            *o = (m / norm) as f32;
945                        }
946                    });
947            }
948            Self::Score {
949                pooling,
950                dense,
951                dense_bias,
952                features,
953                classifier,
954                classifier_bias,
955            } => {
956                let rows: Vec<f32> = match pooling {
957                    Pooling::Cls => starts
958                        .iter()
959                        .flat_map(|&start| &hidden[start * h..(start + 1) * h])
960                        .copied()
961                        .collect(),
962                    Pooling::Mean => starts
963                        .iter()
964                        .zip(lengths)
965                        .flat_map(|(&start, &len)| {
966                            mean_row(&hidden[start * h..(start + len) * h], h)
967                        })
968                        .map(|mean| mean as f32)
969                        .collect(),
970                };
971                let mut projected = vec![0.0; lengths.len() * h];
972                gemm_current_pool(
973                    kernel,
974                    &rows,
975                    lengths.len(),
976                    dense,
977                    Epilogue::Bias(dense_bias),
978                    &mut projected,
979                );
980                for (score, row) in out.iter_mut().zip(projected.chunks_exact_mut(h)) {
981                    // tanh maps infinity to a finite value, hiding overflow in the dense layer's
982                    // matrix product or bias addition.
983                    if row.iter().any(|value| !value.is_finite()) {
984                        *score = f32::NAN;
985                        continue;
986                    }
987                    match features {
988                        Features::Tanh => row.iter_mut().for_each(|x| *x = x.tanh()),
989                        Features::Normed(activation, norm) => {
990                            let activate: fn(f32) -> f32 = match activation {
991                                Activation::Gelu => math::gelu_unbounded,
992                                Activation::Silu => math::silu,
993                            };
994                            row.iter_mut().for_each(|x| *x = activate(*x));
995                            norm.apply(row);
996                        }
997                    }
998                    let dot: f64 = row
999                        .iter()
1000                        .zip(classifier)
1001                        .map(|(&feature, &w)| f64::from(feature) * f64::from(w))
1002                        .sum();
1003                    *score = (dot + f64::from(*classifier_bias)) as f32;
1004                }
1005            }
1006        }
1007    }
1008}
1009
1010pub struct Encoder {
1011    // Dedicated pools isolate explicit worker budgets from the shared pools.
1012    pool: Option<Workers>,
1013    precision: CpuPrecision,
1014    statics: bool,
1015    half_residual: bool,
1016    kernel: Kernel,
1017    shape: Shape,
1018    max_tokens: usize,
1019    family: Family,
1020    finish: Finish,
1021    work: Workspace,
1022    profile: Option<Profile>,
1023}
1024
1025impl Encoder {
1026    pub fn new(
1027        kernel: Kernel,
1028        shape: Shape,
1029        output: Output,
1030        max_tokens: usize,
1031        tensors: &dyn Tensors,
1032    ) -> Result<Self, EncoderError> {
1033        Self::new_with_precision(
1034            kernel,
1035            shape,
1036            output,
1037            max_tokens,
1038            tensors,
1039            CpuPrecision::Fp32,
1040        )
1041    }
1042
1043    /// Loads with an explicit projection policy; [`CpuPrecision`] gives each
1044    /// preset's requirements.
1045    pub fn new_with_precision(
1046        kernel: Kernel,
1047        shape: Shape,
1048        output: Output,
1049        max_tokens: usize,
1050        tensors: &dyn Tensors,
1051        precision: CpuPrecision,
1052    ) -> Result<Self, EncoderError> {
1053        shape.validate().map_err(EncoderError::Unsupported)?;
1054        precision.validate(kernel, shape, output)?;
1055        Self::load(kernel, shape, output, max_tokens, tensors, precision)
1056    }
1057
1058    /// [`Self::new_with_precision`] without the shape check, so centered tests run fewer layers.
1059    #[cfg(all(test, target_arch = "x86_64"))]
1060    pub(crate) fn new_without_shape_check(
1061        kernel: Kernel,
1062        shape: Shape,
1063        output: Output,
1064        max_tokens: usize,
1065        tensors: &dyn Tensors,
1066        precision: CpuPrecision,
1067    ) -> Result<Self, EncoderError> {
1068        shape.validate().map_err(EncoderError::Unsupported)?;
1069        Self::load(kernel, shape, output, max_tokens, tensors, precision)
1070    }
1071
1072    fn load(
1073        kernel: Kernel,
1074        shape: Shape,
1075        output: Output,
1076        max_tokens: usize,
1077        tensors: &dyn Tensors,
1078        precision: CpuPrecision,
1079    ) -> Result<Self, EncoderError> {
1080        if !kernel.is_supported() {
1081            return Err(EncoderError::Unsupported(format!(
1082                "{kernel} is unavailable on this processor"
1083            )));
1084        }
1085        if max_tokens == 0 {
1086            return Err(EncoderError::Unsupported(
1087                "max_tokens must be positive".into(),
1088            ));
1089        }
1090        let (h, i) = (shape.hidden, shape.intermediate);
1091        let rotary = match shape.positions {
1092            Positions::ModernBert(rotary) => Some(rotary),
1093            _ => None,
1094        };
1095        let layer_bytes = match rotary {
1096            Some(_) => size_of::<ModernLayer>(),
1097            None => size_of::<Layer>(),
1098        };
1099        if shape
1100            .layers
1101            .checked_mul(layer_bytes)
1102            .is_none_or(|bytes| bytes > isize::MAX as usize)
1103        {
1104            return Err(EncoderError::Unsupported(
1105                "layer storage exceeds addressable memory".into(),
1106            ));
1107        }
1108        // ModernBERT packs its up projection by half, each as wide as BERT's.
1109        for (columns, depth) in [(3 * h, h), (h, h), (i, h), (h, i)] {
1110            tensor_len(&[columns.div_ceil(NR), NR, depth]).map_err(EncoderError::Unsupported)?;
1111        }
1112        let work = Workspace::new(&shape, max_tokens)?;
1113        let family = match rotary {
1114            Some(rotary) => {
1115                Family::Modern(Box::new(Modern::load(&shape, rotary, max_tokens, tensors)?))
1116            }
1117            None => Family::Bert(Box::new(Bert::load(&shape, tensors)?)),
1118        };
1119        let get =
1120            |name: &str, len: usize| tensor(tensors, name, len).map_err(EncoderError::Weights);
1121        let finish = match output {
1122            Output::Embedding(pooling) => Finish::Pool(pooling),
1123            Output::Relevance(head) => {
1124                let (pooling, dense, dense_bias, features) = match head {
1125                    Head::Pooler => {
1126                        let dense = PackedWeight::new(&get("pooler.dense.weight", h * h)?, h, h);
1127                        let bias = get("pooler.dense.bias", h)?;
1128                        (Pooling::Cls, dense, bias, Features::Tanh)
1129                    }
1130                    Head::Prediction(pooling, activation) => {
1131                        let dense = PackedWeight::new(&get("head.dense.weight", h * h)?, h, h);
1132                        let norm = Norm {
1133                            gamma: get("head.norm.weight", h)?,
1134                            beta: vec![0.0; h],
1135                            eps: shape.eps,
1136                        };
1137                        let features = Features::Normed(activation, norm);
1138                        (pooling, dense, vec![0.0; h], features)
1139                    }
1140                };
1141                Finish::Score {
1142                    pooling,
1143                    dense,
1144                    dense_bias,
1145                    features,
1146                    classifier: get("classifier.weight", h)?,
1147                    classifier_bias: get("classifier.bias", 1)?[0],
1148                }
1149            }
1150        };
1151        Ok(Self {
1152            pool: None,
1153            precision,
1154            statics: false,
1155            half_residual: false,
1156            kernel,
1157            shape,
1158            max_tokens,
1159            family,
1160            finish,
1161            work,
1162            profile: None,
1163        })
1164    }
1165
1166    /// Loads with a dedicated inference pool, independent of RAYON_NUM_THREADS.
1167    pub fn new_with_precision_and_workers(
1168        kernel: Kernel,
1169        shape: Shape,
1170        output: Output,
1171        max_tokens: usize,
1172        tensors: &dyn Tensors,
1173        precision: CpuPrecision,
1174        workers: NonZeroUsize,
1175    ) -> Result<Self, EncoderError> {
1176        if workers.get() > rayon::max_num_threads() {
1177            return Err(EncoderError::Unsupported(format!(
1178                "CPU worker count exceeds Rayon's limit {}",
1179                rayon::max_num_threads()
1180            )));
1181        }
1182        let mut encoder =
1183            Self::new_with_precision(kernel, shape, output, max_tokens, tensors, precision)?;
1184        encoder.pool = Some(
1185            crate::worker_pool("kodamaembed-cpu-bounded", workers.get())
1186                .map_err(|e| EncoderError::Unsupported(format!("CPU worker pool: {e}")))?,
1187        );
1188        if encoder.threads() != workers.get() {
1189            return Err(EncoderError::Unsupported(
1190                "CPU worker pool did not honor the requested count".into(),
1191            ));
1192        }
1193        Ok(encoder)
1194    }
1195
1196    pub fn max_tokens(&self) -> usize {
1197        self.max_tokens
1198    }
1199
1200    /// The explicitly selected CPU projection policy.
1201    pub fn precision(&self) -> CpuPrecision {
1202        self.precision
1203    }
1204
1205    /// The label a fingerprint hashes with [`crate::NUMERICAL_SOURCES`], the
1206    /// [`Kernel`] and the model bytes.
1207    pub fn numerical_identity(&self) -> &'static str {
1208        self.precision.identity()
1209    }
1210
1211    /// Without a dedicated pool, batches of up to 256 tokens may run on a
1212    /// smaller pool of performance cores.
1213    pub fn threads(&self) -> usize {
1214        self.pool
1215            .as_ref()
1216            .unwrap_or_else(|| &POOL)
1217            .current_num_threads()
1218    }
1219
1220    /// Times every stage of every later batch; see [`Encoder::profile`].
1221    pub fn enable_profiling(&mut self) {
1222        self.profile = Some(Profile::default());
1223    }
1224
1225    /// Wall time per stage of the batches since profiling was enabled.
1226    pub fn profile(&self) -> Option<&Profile> {
1227        self.profile.as_ref()
1228    }
1229
1230    /// Values returned per sequence: `hidden` for sentence vectors, 1 for scores.
1231    pub fn output_width(&self) -> usize {
1232        match self.finish {
1233            Finish::Pool(_) => self.shape.hidden,
1234            Finish::Score { .. } => 1,
1235        }
1236    }
1237
1238    /// Quantizes a centered preset by GPTQ over the FP32 forward of `inputs`, two or more
1239    /// tokens each and one with interior tokens; once only, a failure leaves it uncalibrated.
1240    #[cfg(target_arch = "x86_64")]
1241    pub fn calibrate(&mut self, inputs: &[TokenSequence]) -> Result<(), EncoderError> {
1242        if !self.precision.centered() {
1243            return Err(EncoderError::Unsupported(
1244                "calibration quantizes a centered INT8 preset".into(),
1245            ));
1246        }
1247        if self.statics {
1248            return Err(EncoderError::Unsupported(
1249                "the encoder is calibrated already".into(),
1250            ));
1251        }
1252        if inputs.is_empty()
1253            || inputs
1254                .iter()
1255                .any(|(ids, types)| ids.len() < 2 || types.len() != ids.len())
1256        {
1257            return Err(EncoderError::Input(
1258                "static centers need sequences of at least two tokens, a segment type each".into(),
1259            ));
1260        }
1261        let ids: Vec<i32> = inputs
1262            .iter()
1263            .flat_map(|(ids, _)| ids.iter().copied())
1264            .collect();
1265        let types: Vec<i32> = inputs
1266            .iter()
1267            .flat_map(|(_, types)| types.iter().copied())
1268            .collect();
1269        let lengths: Vec<usize> = inputs.iter().map(|(ids, _)| ids.len()).collect();
1270        let tokens = checked_input(&self.shape, &ids, &types, &lengths)?;
1271        let mut own = if tokens > self.max_tokens {
1272            Some(Workspace::new(&self.shape, tokens)?)
1273        } else {
1274            None
1275        };
1276        let firsts: Vec<usize> = lengths
1277            .iter()
1278            .scan(0, |at, &len| {
1279                *at += len;
1280                Some(*at - len)
1281            })
1282            .collect();
1283        let lasts: Vec<usize> = firsts
1284            .iter()
1285            .zip(&lengths)
1286            .map(|(&first, &len)| first + len - 1)
1287            .collect();
1288        let row_classes: Vec<u32> = lengths
1289            .iter()
1290            .flat_map(|&len| (0..len).map(move |t| restored_class(t, len) as u32))
1291            .collect();
1292        let execution = ExecutionOptions {
1293            kernel: self.kernel,
1294            integer_attention: false,
1295            half_residual: false,
1296            keep_norm_inputs: true,
1297            static_keys: false,
1298        };
1299        let (h, i, heads) = (self.shape.hidden, self.shape.intermediate, self.shape.heads);
1300        let (precision, integer) = (self.precision, self.precision.integer_attention());
1301        let means = |input: &[f32], width: usize| -> Result<Vec<f64>, EncoderError> {
1302            let mut means = class_means(input, width, &firsts, &lasts);
1303            let Some(between) = middle_mean(input, width, &firsts, &lengths) else {
1304                return Err(EncoderError::Input(
1305                    "static centers need inputs with tokens between their first and last".into(),
1306                ));
1307            };
1308            means.extend(between);
1309            Ok(means)
1310        };
1311        let gained = |input: &NormInput, norm: &Norm| -> (Vec<f32>, Vec<f32>) {
1312            (
1313                input.rows[..tokens * h]
1314                    .chunks_exact(h)
1315                    .flat_map(|row| row.iter().zip(&norm.gamma).map(|(&z, &gamma)| z * gamma))
1316                    .collect(),
1317                input.rstd[..tokens]
1318                    .iter()
1319                    .map(|&rstd| rstd * rstd)
1320                    .collect(),
1321            )
1322        };
1323        let positions = self.shape.position_ids(&ids, &lengths);
1324        let Family::Bert(bert) = &mut self.family else {
1325            return Err(EncoderError::Unsupported(
1326                "calibration quantizes a centered INT8 preset".into(),
1327            ));
1328        };
1329        let (embeddings, layers, relative) =
1330            (&bert.embeddings, &bert.layers, bert.relative.as_ref());
1331        let w = match &mut own {
1332            Some(work) => work,
1333            None => &mut self.work,
1334        };
1335        let pool = pool_for(self.pool.as_ref(), tokens);
1336        // Every layer builds before any installs, so a failure installs none.
1337        let built = pool.install(|| -> Result<Vec<Calibrated>, EncoderError> {
1338            embeddings.apply(&ids, &types, &positions, &mut w.hidden[..tokens * h], false);
1339            let mut built = Vec::with_capacity(layers.len());
1340            for (index, layer) in layers.iter().enumerate() {
1341                let quantize = |projection: &Projection,
1342                                kind: Kind,
1343                                rows: &[f32],
1344                                weights: Option<&[f32]>,
1345                                norm: Option<DeferredNorm<'_>>| {
1346                    let means = means(rows, projection.k())?;
1347                    let operand = Operand {
1348                        rows,
1349                        classes: &row_classes,
1350                        means: &means,
1351                        weights,
1352                    };
1353                    projection.calibrated(index, kind, precision, operand, norm)
1354                };
1355                // Past layer 0, QKV defers the previous second LayerNorm.
1356                let qkv = match index.checked_sub(1).map(|last| &layers[last].norm2) {
1357                    None => quantize(&layer.qkv, Kind::Qkv, &w.hidden[..tokens * h], None, None)?,
1358                    Some(norm) => {
1359                        let (rows, weights) = gained(&w.norm2_input, norm);
1360                        let deferred = DeferredNorm {
1361                            gains: &norm.gamma,
1362                            beta: &norm.beta,
1363                            bias: &layer.qkv_bias,
1364                        };
1365                        quantize(&layer.qkv, Kind::Qkv, &rows, Some(&weights), Some(deferred))?
1366                    }
1367                };
1368                layer.apply(
1369                    execution, heads, relative, &lengths, None, tokens, w, &mut None,
1370                )?;
1371                let out = quantize(&layer.out, Kind::Out, &w.context[..tokens * h], None, None)?;
1372                let (rows, weights) = gained(&w.norm1_input, &layer.norm1);
1373                let deferred = DeferredNorm {
1374                    gains: &layer.norm1.gamma,
1375                    beta: &layer.norm1.beta,
1376                    bias: &layer.up_bias,
1377                };
1378                let up = quantize(&layer.up, Kind::Ffn1, &rows, Some(&weights), Some(deferred))?;
1379                let down = quantize(
1380                    &layer.down,
1381                    Kind::Ffn2,
1382                    &w.intermediate[..tokens * i],
1383                    None,
1384                    None,
1385                )?;
1386                let keys = integer.then(|| {
1387                    key_means(&w.qkv[..tokens * 3 * h], h, &firsts, &lengths)
1388                        .iter()
1389                        .map(|&mean| mean as f32)
1390                        .collect()
1391                });
1392                built.push(Calibrated {
1393                    projections: [qkv, out, up, down],
1394                    keys,
1395                });
1396            }
1397            Ok(built)
1398        })?;
1399        bert.install(built);
1400        self.set_calibrated();
1401        Ok(())
1402    }
1403
1404    /// Calibration quantizes a centered INT8 preset, which needs x86-64.
1405    #[cfg(not(target_arch = "x86_64"))]
1406    pub fn calibrate(&mut self, _inputs: &[TokenSequence]) -> Result<(), EncoderError> {
1407        Err(EncoderError::Unsupported(
1408            "calibration quantizes a centered INT8 preset, which requires x86-64".into(),
1409        ))
1410    }
1411
1412    /// The calibration as the bytes [`Self::install_calibration`] takes back.
1413    #[cfg(target_arch = "x86_64")]
1414    pub fn calibration(&self) -> Result<Vec<u8>, EncoderError> {
1415        let Some(bert) = self.calibrated() else {
1416            return Err(EncoderError::Unsupported(
1417                "calibration tables need a calibrated centered preset".into(),
1418            ));
1419        };
1420        let mut out = Vec::new();
1421        for layer in &bert.layers {
1422            for projection in [&layer.qkv, &layer.out, &layer.up, &layer.down] {
1423                projection.write_calibration(&mut out)?;
1424            }
1425            for key in layer.key_centers.iter().flatten() {
1426                out.extend(key.to_le_bytes());
1427            }
1428        }
1429        Ok(out)
1430    }
1431
1432    /// Installs [`Self::calibration`]'s bytes without the forward pass. Malformed
1433    /// tables are refused and leave the encoder uncalibrated; once only.
1434    #[cfg(target_arch = "x86_64")]
1435    pub fn install_calibration(&mut self, tables: &[u8]) -> Result<(), EncoderError> {
1436        if !self.precision.centered() {
1437            return Err(EncoderError::Unsupported(
1438                "calibration quantizes a centered INT8 preset".into(),
1439            ));
1440        }
1441        if self.statics {
1442            return Err(EncoderError::Unsupported(
1443                "the encoder is calibrated already".into(),
1444            ));
1445        }
1446        let (precision, h) = (self.precision, self.shape.hidden);
1447        let Family::Bert(bert) = &mut self.family else {
1448            return Err(EncoderError::Unsupported(
1449                "calibration quantizes a centered INT8 preset".into(),
1450            ));
1451        };
1452        let layers = &bert.layers;
1453        let mut rest = tables;
1454        let mut built = Vec::with_capacity(layers.len());
1455        for (index, layer) in layers.iter().enumerate() {
1456            // Deferred as calibrate defers them.
1457            let qkv_gains = index
1458                .checked_sub(1)
1459                .map(|last| &layers[last].norm2.gamma[..]);
1460            let up_gains = Some(&layer.norm1.gamma[..]);
1461            let projections = [
1462                layer
1463                    .qkv
1464                    .installed(index, Kind::Qkv, precision, qkv_gains, &mut rest)?,
1465                layer
1466                    .out
1467                    .installed(index, Kind::Out, precision, None, &mut rest)?,
1468                layer
1469                    .up
1470                    .installed(index, Kind::Ffn1, precision, up_gains, &mut rest)?,
1471                layer
1472                    .down
1473                    .installed(index, Kind::Ffn2, precision, None, &mut rest)?,
1474            ];
1475            let keys = precision
1476                .integer_attention()
1477                .then(|| crate::int8::take_floats(&mut rest, h))
1478                .transpose()
1479                .map_err(|e| EncoderError::Input(format!("layer {index} key centers: {e}")))?;
1480            built.push(Calibrated { projections, keys });
1481        }
1482        if !rest.is_empty() {
1483            return Err(EncoderError::Input(
1484                "calibration tables run past this model's".into(),
1485            ));
1486        }
1487        bert.install(built);
1488        self.set_calibrated();
1489        Ok(())
1490    }
1491
1492    /// From here on, encodes run the installed calibration.
1493    #[cfg(target_arch = "x86_64")]
1494    fn set_calibrated(&mut self) {
1495        self.statics = true;
1496        self.half_residual = self.precision.integer_attention();
1497    }
1498
1499    /// The weights a calibrated centered preset runs: BERT's, the family it quantizes.
1500    #[cfg(target_arch = "x86_64")]
1501    fn calibrated(&self) -> Option<&Bert> {
1502        match &self.family {
1503            Family::Bert(bert) if self.precision.centered() && self.statics => Some(bert),
1504            _ => None,
1505        }
1506    }
1507
1508    /// Calibrated parameters for bit-identical execution on another backend.
1509    #[cfg(target_arch = "x86_64")]
1510    pub fn export_reproducible(
1511        &self,
1512    ) -> Result<kodamaembed_model::repro::EncoderExport, EncoderError> {
1513        use kodamaembed_model::repro::{EncoderExport, LayerExport, NormExport};
1514        let mean_pooled = matches!(self.finish, Finish::Pool(Pooling::Mean));
1515        let Some(bert) = self.calibrated().filter(|_| mean_pooled) else {
1516            return Err(EncoderError::Unsupported(
1517                "exports need a calibrated centered mean-pooling encoder".into(),
1518            ));
1519        };
1520        let norm = |n: &Norm| NormExport {
1521            gamma: n.gamma.clone(),
1522            beta: n.beta.clone(),
1523            eps: n.eps,
1524        };
1525        let layers = bert
1526            .layers
1527            .iter()
1528            .map(|layer| {
1529                Ok(LayerExport {
1530                    qkv: layer.qkv.export(&layer.qkv_bias)?,
1531                    key_centers: layer.key_centers.clone().ok_or_else(|| {
1532                        EncoderError::Unsupported("exports need static key centers".into())
1533                    })?,
1534                    out: layer.out.export(&layer.out_bias)?,
1535                    norm1: norm(&layer.norm1),
1536                    up: layer.up.export(&layer.up_bias)?,
1537                    down: layer.down.export(&layer.down_bias)?,
1538                    norm2: norm(&layer.norm2),
1539                })
1540            })
1541            .collect::<Result<Vec<_>, EncoderError>>()?;
1542        Ok(EncoderExport {
1543            shape: self.shape,
1544            word: bert.embeddings.word.clone(),
1545            position: bert.embeddings.position.clone(),
1546            token_type: bert.embeddings.token_type.clone(),
1547            embedding_norm: norm(&bert.embeddings.norm),
1548            layers,
1549            constants_f32: crate::int8::repro_constants(),
1550            attention_weights: crate::attention::weight_table().to_vec(),
1551        })
1552    }
1553
1554    /// Encodes sequences packed back to back by `lengths`, [`Encoder::output_width`]
1555    /// values each; no sequence depends on another in the batch.
1556    pub fn encode(
1557        &mut self,
1558        ids: &[i32],
1559        types: &[i32],
1560        lengths: &[usize],
1561    ) -> Result<Vec<f32>, EncoderError> {
1562        let tokens = checked_tokens(&self.shape, self.max_tokens, ids, types, lengths)?;
1563        let (h, mut out) = (
1564            self.shape.hidden,
1565            vec![0.0; lengths.len() * self.output_width()],
1566        );
1567        let mut timer = self.profile.is_some().then(|| Timer {
1568            last: Instant::now(),
1569            milliseconds: [0.0; STAGES.len()],
1570        });
1571        let (kernel, heads) = (self.kernel, self.shape.heads);
1572        let execution = ExecutionOptions {
1573            kernel,
1574            integer_attention: self.precision.integer_attention(),
1575            half_residual: self.half_residual,
1576            keep_norm_inputs: false,
1577            static_keys: true,
1578        };
1579        let centered = self.precision.centered();
1580        if centered && !self.statics {
1581            return Err(EncoderError::Unsupported(
1582                "centered INT8 requires calibrated static centers".into(),
1583            ));
1584        }
1585        let row_classes: Option<Vec<u32>> = centered.then(|| {
1586            lengths
1587                .iter()
1588                .flat_map(|&len| (0..len).map(move |t| restored_class(t, len) as u32))
1589                .collect()
1590        });
1591        let positions = self.shape.position_ids(ids, lengths);
1592        let (shape, family, finish, w) =
1593            (&self.shape, &mut self.family, &self.finish, &mut self.work);
1594        pool_for(self.pool.as_ref(), tokens).install(|| -> Result<(), EncoderError> {
1595            match family {
1596                Family::Bert(bert) => {
1597                    bert.embeddings.apply(
1598                        ids,
1599                        types,
1600                        &positions,
1601                        &mut w.hidden[..tokens * h],
1602                        execution.half_residual,
1603                    );
1604                    mark(&mut timer, Stage::Embed);
1605                    let (relative, restored) = (bert.relative.as_ref(), row_classes.as_deref());
1606                    for layer in &bert.layers {
1607                        layer.apply(
1608                            execution, heads, relative, lengths, restored, tokens, w, &mut timer,
1609                        )?;
1610                    }
1611                }
1612                Family::Modern(modern) => {
1613                    modern.forward(kernel, shape, ids, &positions, lengths, w, &mut timer);
1614                }
1615            }
1616            finish.apply(kernel, &w.hidden[..tokens * h], h, lengths, &mut out);
1617            mark(&mut timer, Stage::Pool);
1618            Ok(())
1619        })?;
1620        if out.iter().any(|value| !value.is_finite()) {
1621            return Err(EncoderError::Weights(
1622                "encoder produced non-finite outputs; checkpoint values exceed backend numerical range".into(),
1623            ));
1624        }
1625        if let (Some(profile), Some(timer)) = (&mut self.profile, timer) {
1626            for (total, ms) in profile.milliseconds.iter_mut().zip(timer.milliseconds) {
1627                *total += ms;
1628            }
1629            profile.batches += 1;
1630            profile.tokens += tokens;
1631        }
1632        Ok(out)
1633    }
1634}
1635
1636#[cfg(all(test, target_arch = "x86_64"))]
1637mod centered_tests;
1638
1639#[cfg(test)]
1640mod worker_budget_tests {
1641    use super::*;
1642    use kodamaembed_model::Positions;
1643
1644    struct Weights;
1645    impl Tensors for Weights {
1646        fn get(&self, name: &str, len: usize) -> Result<Vec<f32>, String> {
1647            Ok(if name.contains("LayerNorm.weight") {
1648                vec![1.0; len]
1649            } else {
1650                (0..len).map(|i| ((i % 23) as f32 - 11.0) * 0.005).collect()
1651            })
1652        }
1653    }
1654
1655    fn encoder(output: Output, workers: Option<NonZeroUsize>) -> Encoder {
1656        let shape = Shape {
1657            layers: 1,
1658            hidden: 32,
1659            heads: 4,
1660            intermediate: 64,
1661            vocab: 8,
1662            max_positions: 16,
1663            type_vocab: 2,
1664            eps: 1e-5,
1665            positions: Positions::Sequential,
1666        };
1667        let capacity = 2 * SHORT_TOKENS;
1668        match workers {
1669            Some(workers) => Encoder::new_with_precision_and_workers(
1670                Kernel::Portable,
1671                shape,
1672                output,
1673                capacity,
1674                &Weights,
1675                CpuPrecision::Fp32,
1676                workers,
1677            ),
1678            None => Encoder::new(Kernel::Portable, shape, output, capacity, &Weights),
1679        }
1680        .unwrap()
1681    }
1682
1683    const OUTPUTS: [Output; 3] = [
1684        Output::Embedding(Pooling::Mean),
1685        Output::Embedding(Pooling::Cls),
1686        Output::Relevance(Head::Pooler),
1687    ];
1688
1689    #[test]
1690    fn dedicated_pools_preserve_short_panel_and_multihead_arithmetic_and_reuse() {
1691        for output in OUTPUTS {
1692            let mut reference = encoder(output, None);
1693            for count in [1, 2] {
1694                let workers = NonZeroUsize::new(count).unwrap();
1695                let mut actual = encoder(output, Some(workers));
1696                assert_eq!(actual.threads(), count);
1697                for lengths in [&[1][..], &[1, 3, 2][..], &[16, 16, 1][..], &[1][..]] {
1698                    let tokens = lengths.iter().sum::<usize>();
1699                    let ids: Vec<i32> = (0..tokens).map(|i| (i % 8) as i32).collect();
1700                    let types = vec![0; tokens];
1701                    let expected = reference.encode(&ids, &types, lengths).unwrap();
1702                    let observed = actual.encode(&ids, &types, lengths).unwrap();
1703                    assert_eq!(
1704                        observed.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1705                        expected.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1706                    );
1707                }
1708                assert!(actual.encode(&[8], &[0], &[1]).is_err());
1709                assert_eq!(
1710                    actual
1711                        .encode(&[1], &[0], &[1])
1712                        .unwrap()
1713                        .iter()
1714                        .map(|v| v.to_bits())
1715                        .collect::<Vec<_>>(),
1716                    reference
1717                        .encode(&[1], &[0], &[1])
1718                        .unwrap()
1719                        .iter()
1720                        .map(|v| v.to_bits())
1721                        .collect::<Vec<_>>(),
1722                );
1723            }
1724        }
1725    }
1726
1727    #[cfg(target_arch = "x86_64")]
1728    #[test]
1729    fn class_means_average_first_and_last_rows_in_f64() {
1730        let rows = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
1731        assert_eq!(
1732            class_means(&rows, 2, &[0, 2], &[1, 3]),
1733            [3.0, 4.0, 5.0, 6.0]
1734        );
1735    }
1736
1737    #[test]
1738    fn short_batches_run_on_one_thread_per_performance_core() {
1739        let all = POOL.current_num_threads();
1740        let short = SHORT_POOL.as_ref().unwrap_or(&POOL).current_num_threads();
1741        let cores = crate::workers::allowed_cores();
1742        eprintln!("allowed cores {cores:?}, short-batch threads {short} of {all}");
1743        let rule = cores.and_then(|cores| crate::workers::short_pool_threads(cores, all));
1744        assert_eq!(short, rule.unwrap_or(all));
1745        assert_eq!(pool_for(None, 1).current_num_threads(), short);
1746        assert_eq!(pool_for(None, SHORT_TOKENS).current_num_threads(), short);
1747        assert_eq!(pool_for(None, SHORT_TOKENS + 1).current_num_threads(), all);
1748        let own = crate::worker_pool("own", 3).unwrap();
1749        assert_eq!(pool_for(Some(&own), 1).current_num_threads(), 3);
1750        assert_eq!(
1751            pool_for(Some(&own), SHORT_TOKENS + 1).current_num_threads(),
1752            3
1753        );
1754    }
1755
1756    #[test]
1757    fn inputs_alone_match_their_rows_in_a_batch_past_the_short_threshold() {
1758        let lengths = [16; SHORT_TOKENS / 16 + 1];
1759        let tokens = lengths.iter().sum::<usize>();
1760        assert!(tokens > SHORT_TOKENS);
1761        let ids: Vec<i32> = (0..tokens).map(|i| (i * 5 % 8) as i32).collect();
1762        let types = vec![0; tokens];
1763        for output in OUTPUTS {
1764            let mut encoder = encoder(output, None);
1765            let batch = encoder.encode(&ids, &types, &lengths).unwrap();
1766            let width = batch.len() / lengths.len();
1767            for (s, row) in batch.chunks(width).enumerate() {
1768                let range = 16 * s..16 * (s + 1);
1769                let alone = encoder
1770                    .encode(&ids[range.clone()], &types[range], &[16])
1771                    .unwrap();
1772                assert_eq!(
1773                    alone.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1774                    row.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1775                    "{output:?} sequence {s}"
1776                );
1777            }
1778        }
1779    }
1780
1781    #[test]
1782    fn dedicated_embedding_and_scoring_complete_with_all_legacy_workers_parked() {
1783        use std::sync::{Arc, Condvar, Mutex, mpsc};
1784        use std::thread::{self, JoinHandle};
1785        use std::time::Duration;
1786
1787        struct Parked {
1788            state: Arc<(Mutex<(usize, bool)>, Condvar)>,
1789            job: Option<JoinHandle<()>>,
1790        }
1791        impl Parked {
1792            fn release_and_join(&mut self) -> thread::Result<()> {
1793                let (lock, wake) = &*self.state;
1794                lock.lock().unwrap_or_else(|e| e.into_inner()).1 = true;
1795                wake.notify_all();
1796                self.job.take().map_or(Ok(()), |job| job.join())
1797            }
1798        }
1799        impl Drop for Parked {
1800            fn drop(&mut self) {
1801                // Runs before any assertion, even on a timeout or panic.
1802                let _ = self.release_and_join();
1803            }
1804        }
1805
1806        let workers = NonZeroUsize::new(1).unwrap();
1807        let mut embedding = encoder(Output::Embedding(Pooling::Mean), Some(workers));
1808        let mut scoring = encoder(Output::Relevance(Head::Pooler), Some(workers));
1809        let expected_embedding = encoder(Output::Embedding(Pooling::Mean), None)
1810            .encode(&[1, 2, 3], &[0, 0, 0], &[1, 2])
1811            .unwrap();
1812        let expected_scoring = encoder(Output::Relevance(Head::Pooler), None)
1813            .encode(&[1, 2, 3], &[0, 0, 0], &[1, 2])
1814            .unwrap();
1815        let count = POOL.current_num_threads();
1816        let state = Arc::new((Mutex::new((0_usize, false)), Condvar::new()));
1817        let worker_state = Arc::clone(&state);
1818        let job = thread::spawn(move || {
1819            POOL.broadcast(|_| {
1820                let (lock, wake) = &*worker_state;
1821                let mut state = lock.lock().unwrap_or_else(|e| e.into_inner());
1822                state.0 += 1;
1823                wake.notify_all();
1824                while !state.1 {
1825                    state = wake.wait(state).unwrap_or_else(|e| e.into_inner());
1826                }
1827            });
1828        });
1829        let mut parked = Parked {
1830            state,
1831            job: Some(job),
1832        };
1833        let all_parked = {
1834            let (lock, wake) = &*parked.state;
1835            let state = lock.lock().unwrap_or_else(|e| e.into_inner());
1836            let (state, _) = wake
1837                .wait_timeout_while(state, Duration::from_secs(10), |state| state.0 < count)
1838                .unwrap_or_else(|e| e.into_inner());
1839            state.0 == count
1840        };
1841        if !all_parked {
1842            let cleanup = parked.release_and_join();
1843            assert!(cleanup.is_ok(), "park job failed");
1844            panic!("workers never parked");
1845        }
1846        let (send, receive) = mpsc::sync_channel(1);
1847        let actual = thread::spawn(move || {
1848            let embeddings = embedding.encode(&[1, 2, 3], &[0, 0, 0], &[1, 2]);
1849            let scores = scoring.encode(&[1, 2, 3], &[0, 0, 0], &[1, 2]);
1850            let _ = send.send((embeddings, scores));
1851        });
1852        // A deadlock watchdog.
1853        let completed_while_parked = receive.recv_timeout(Duration::from_secs(10));
1854        let cleanup = parked.release_and_join();
1855        let worker_result = actual.join();
1856        assert!(cleanup.is_ok(), "park job failed");
1857        assert!(worker_result.is_ok(), "explicit-pool worker panicked");
1858        let (embeddings, scores) = completed_while_parked.expect("used parked pool");
1859        for (observed, expected) in [
1860            (embeddings.unwrap(), expected_embedding),
1861            (scores.unwrap(), expected_scoring),
1862        ] {
1863            assert_eq!(
1864                observed.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1865                expected.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
1866            );
1867        }
1868    }
1869}
1870
1871#[cfg(all(test, target_arch = "x86_64"))]
1872mod norm_tests {
1873    use super::{Norm, NormInput, round_half};
1874
1875    fn bits(values: &[f32]) -> Vec<u32> {
1876        values.iter().map(|v| v.to_bits()).collect()
1877    }
1878
1879    /// Keeping a LayerNorm's input changes nothing it writes.
1880    #[test]
1881    fn kept_inputs_are_the_rows_and_statistics_the_norm_used() {
1882        let (width, tokens) = (128, 70);
1883        let norm = Norm {
1884            gamma: (0..width).map(|t| 0.5 + t as f32 / 97.0).collect(),
1885            beta: (0..width).map(|t| (t % 7) as f32 / 9.0 - 0.3).collect(),
1886            eps: 1e-12,
1887        };
1888        let mut rows: Vec<f32> = (0..tokens * width)
1889            .map(|at| ((at * 37 % 211) as f32 - 100.0) / 13.0 + 0.001)
1890            .collect();
1891        for (t, x) in rows[3 * width..4 * width].iter_mut().enumerate() {
1892            *x = if t % 2 == 0 { 3e19 } else { -3e19 };
1893        }
1894        let halves: &[bool] = if std::is_x86_feature_detected!("f16c") {
1895            &[false, true]
1896        } else {
1897            &[false]
1898        };
1899        for &half in halves {
1900            let mut plain = rows.clone();
1901            norm.apply_rows(&mut plain, half);
1902            let mut kept = rows.clone();
1903            let mut input = NormInput::default();
1904            norm.apply_rows_keeping(&mut kept, half, &mut input);
1905            assert_eq!(bits(&kept), bits(&plain), "half {half}");
1906            let mut read = rows.clone();
1907            round_half(&mut read, half);
1908            assert_eq!(bits(&input.rows), bits(&read), "half {half}");
1909            assert_eq!((input.mean.len(), input.rstd.len()), (tokens, tokens));
1910            for (r, row) in read.chunks_exact(width).enumerate() {
1911                let (mean, rstd) = norm.moments(row).unwrap_or((f32::NAN, f32::NAN));
1912                assert_eq!(
1913                    input.mean[r].to_bits(),
1914                    mean.to_bits(),
1915                    "half {half} row {r}"
1916                );
1917                assert_eq!(
1918                    input.rstd[r].to_bits(),
1919                    rstd.to_bits(),
1920                    "half {half} row {r}"
1921                );
1922            }
1923            assert!(
1924                input.rstd[3].is_nan() && kept[3 * width..4 * width].iter().all(|x| x.is_nan())
1925            );
1926        }
1927    }
1928}
1929
1930#[cfg(test)]
1931mod lane_sum_tests {
1932    use super::lane_sum;
1933
1934    /// lane_sum as a warp computes it (repro.cu repro_layernorm_lanes).
1935    fn warp_sum<T: Copy + Default + std::ops::Add<Output = T>>(values: &[T]) -> [T; 32] {
1936        let mut lanes = [T::default(); 32];
1937        for (c, &x) in values.iter().enumerate() {
1938            lanes[c % 32] = lanes[c % 32] + x;
1939        }
1940        let mut width = 16;
1941        while width > 0 {
1942            let before = lanes;
1943            for (j, lane) in lanes.iter_mut().enumerate() {
1944                *lane = before[j] + before[j ^ width];
1945            }
1946            width /= 2;
1947        }
1948        lanes
1949    }
1950
1951    fn values(seed: u64, n: usize) -> Vec<f64> {
1952        let mut x = seed;
1953        (0..n)
1954            .map(|_| {
1955                x ^= x << 13;
1956                x ^= x >> 7;
1957                x ^= x << 17;
1958                ((x >> 11) as f64 / (1_u64 << 53) as f64 - 0.5) * 2_f64.powi((x % 31) as i32 - 15)
1959            })
1960            .collect()
1961    }
1962
1963    #[test]
1964    fn a_warps_butterfly_holds_lane_sums_total_in_every_lane() {
1965        for (seed, n) in [(3, 1024), (5, 384), (7, 1000), (11, 32), (13, 5)] {
1966            let wide = values(seed, n);
1967            let narrow: Vec<f32> = wide.iter().map(|&v| v as f32).collect();
1968            let total = lane_sum(&wide, |v| v);
1969            assert!(
1970                warp_sum(&wide)
1971                    .iter()
1972                    .all(|l| l.to_bits() == total.to_bits()),
1973                "f64 n {n}"
1974            );
1975            let total = lane_sum(&narrow, |v| v);
1976            assert!(
1977                warp_sum(&narrow)
1978                    .iter()
1979                    .all(|l| l.to_bits() == total.to_bits()),
1980                "f32 n {n}"
1981            );
1982        }
1983    }
1984}