Skip to main content

cortiq_engine/
gigaam.rs

1//! GigaAM-v4 speech recognition (ai-sage/GigaAM-v4): a Zapformer encoder
2//! over 64 log-mel bins with two recognition heads on top — `e2e` (case,
3//! punctuation, digits) and `raw` (lower-case words) — as RNN-T or CTC.
4//!
5//! The encoder is three stacks (768 → 1024 at half the frame rate → 768)
6//! behind a causal convolutional front end that takes 100 mel frames a
7//! second down to 25. A layer is: feed-forward, gated rotary self-attention
8//! whose queries and keys come from the layer's input, a gated depthwise
9//! convolution with a global mean, a second feed-forward, and a blend with
10//! the layer input under an RMS norm.
11//!
12//! A clip of up to 30 s is one segment. A longer recording is cut by the
13//! file's voice-activity model ([`vad`]) into speech segments of at most
14//! 30 s, and the segments go through the encoder as one ragged batch: every
15//! matrix product sees all their frames at once, attention and the
16//! convolutions stay inside a segment, and nothing is padded.
17//!
18//! Products run on the selected device when one is up (`CMF_GPU`), and on
19//! the host through `ops::matmul` otherwise: weight rows are widened a
20//! cache-sized tile at a time and multiplied by the frame batch with a
21//! float GEMM.
22
23mod decode;
24mod ops;
25pub mod vad;
26
27use crate::pool::Pool;
28use crate::qtensor::QTensor;
29use cortiq_core::CmfModel;
30use cortiq_core::TensorDtype;
31use cortiq_core::quant::{bf16_to_f32, f16_to_f32};
32use std::sync::{Arc, OnceLock};
33use std::time::Instant;
34
35pub use decode::Word;
36
37/// The architecture name in the file header.
38pub const ARCH_NAME: &str = "gigaam";
39/// Sample rate of the model's input.
40pub const SR: usize = 16_000;
41/// Samples in one segment at most: a longer clip is cut by the VAD.
42pub const MAX_SEGMENT: usize = 30 * SR;
43
44const N_FFT: usize = 320;
45const HOP: usize = 160;
46const QDIM: usize = 32;
47const ENC: &str = "model.encoder.encoder";
48const EMBED: &str = "model.encoder.encoder_embed";
49
50/// Is this file a GigaAM checkpoint?
51pub fn is_gigaam(model: &CmfModel) -> bool {
52    model.header.arch.arch_name == ARCH_NAME
53}
54
55// ---------------------------------------------------------------------
56// tensors
57// ---------------------------------------------------------------------
58
59pub(crate) fn tensor_f32(m: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
60    let e = m.tensor(name).ok_or_else(|| format!("missing GigaAM tensor {name}"))?;
61    let b = m.entry_bytes(e);
62    let n = e.n_elems();
63    match e.dtype {
64        TensorDtype::F32 if b.len() == n * 4 => Ok(b.chunks_exact(4).map(|x| f32::from_le_bytes(x.try_into().unwrap())).collect()),
65        TensorDtype::F16 if b.len() == n * 2 => Ok(b.chunks_exact(2).map(|x| f16_to_f32(u16::from_le_bytes([x[0], x[1]]))).collect()),
66        TensorDtype::Bf16 if b.len() == n * 2 => Ok(b.chunks_exact(2).map(|x| bf16_to_f32(u16::from_le_bytes([x[0], x[1]]))).collect()),
67        _ => Err(format!("{name}: expected a float tensor, got {:?}", e.dtype)),
68    }
69}
70
71fn scalar(m: &CmfModel, name: &str) -> Result<f32, String> {
72    tensor_f32(m, name)?.first().copied().ok_or_else(|| format!("{name}: empty"))
73}
74
75/// How the host multiplies by a weight.
76enum HostW {
77    /// floats in memory (an exact file, or a small matrix)
78    Dense(Vec<f32>),
79    /// the file's int8 codes, with the row scales and the column field
80    Q8 { row_scale: Vec<f32>, col_field: Vec<f32> },
81    /// any other codec, through the tensor's own row decoder
82    Rows,
83}
84
85/// One product `y = x·Wᵀ + b` over a batch of rows.
86pub(crate) struct Lin {
87    model: Arc<CmfModel>,
88    idx: usize,
89    pub rows: usize,
90    pub cols: usize,
91    host: HostW,
92    bias: Vec<f32>,
93    /// the tensor as the device paths take it (built on first use)
94    dev: OnceLock<Option<QTensor>>,
95}
96
97impl Lin {
98    fn load(m: &Arc<CmfModel>, prefix: &str) -> Result<Self, String> {
99        Self::load_named(m, &format!("{prefix}.weight"), Some(&format!("{prefix}.bias")))
100    }
101
102    fn load_named(m: &Arc<CmfModel>, weight: &str, bias: Option<&str>) -> Result<Self, String> {
103        let idx = m.tensor_index(weight).ok_or_else(|| format!("missing GigaAM tensor {weight}"))?;
104        let e = &m.tensors[idx];
105        // a 1×1 convolution is a matrix with a trailing unit axis
106        let shape: Vec<usize> = e.shape.iter().copied().filter(|d| *d != 1).collect();
107        let (rows, cols) = match (e.shape.len(), shape.as_slice()) {
108            (2, _) => (e.shape[0], e.shape[1]),
109            (_, [r, c]) => (*r, *c),
110            (_, [c]) => (1, *c),
111            _ => return Err(format!("{weight}: expected a matrix, got {:?}", e.shape)),
112        };
113        let host = match e.dtype {
114            TensorDtype::F32 | TensorDtype::F16 | TensorDtype::Bf16 => HostW::Dense(tensor_f32(m, weight)?),
115            TensorDtype::Q8Row | TensorDtype::Q8_2f if rows * cols < 1 << 16 => {
116                // a small matrix: floats cost nothing and skip the tile
117                let q = QTensor::from_model(m, weight)?;
118                let mut d = vec![0f32; rows * cols];
119                for (r, row) in d.chunks_exact_mut(cols).enumerate() {
120                    q.row_f32(r, row);
121                }
122                HostW::Dense(d)
123            }
124            TensorDtype::Q8Row | TensorDtype::Q8_2f => {
125                let b = m.entry_bytes(e);
126                let f16s = |off: usize, n: usize| -> Vec<f32> {
127                    (0..n).map(|i| f16_to_f32(u16::from_le_bytes([b[off + 2 * i], b[off + 2 * i + 1]]))).collect()
128                };
129                let row_scale = f16s(rows * cols, rows);
130                let col_field = if e.dtype == TensorDtype::Q8_2f { f16s(rows * cols + rows * 2, cols) } else { Vec::new() };
131                HostW::Q8 { row_scale, col_field }
132            }
133            _ => HostW::Rows,
134        };
135        let bias = match bias {
136            Some(b) if m.tensor(b).is_some() => tensor_f32(m, b)?,
137            _ => Vec::new(),
138        };
139        if !bias.is_empty() && bias.len() != rows {
140            return Err(format!("{weight}: bias of {} for {rows} rows", bias.len()));
141        }
142        let mut lin = Self { model: m.clone(), idx, rows, cols, host, bias, dev: OnceLock::new() };
143        if matches!(lin.host, HostW::Rows) && lin.qtensor().is_none() {
144            return Err(format!("{weight}: codec {:?} is not supported here", e.dtype));
145        }
146        // `CMF_GIGAAM_DENSE=1`: keep every weight as floats in memory (four
147        // bytes a weight, about 0.95 GB for the model) — a short clip then
148        // pays no widening at all; a four-bit file is always expanded on the
149        // host, its row decoder being slower than the product it feeds.
150        let dense_all = std::env::var("CMF_GIGAAM_DENSE").is_ok_and(|v| v == "1");
151        let host_only = !crate::gpu::enabled_here();
152        if (dense_all && matches!(lin.host, HostW::Q8 { .. })) || (matches!(lin.host, HostW::Rows) && (dense_all || host_only)) {
153            let mut d = vec![0f32; rows * cols];
154            crate::gpu::GaWeight::fill(&lin, &mut d);
155            lin.host = HostW::Dense(d);
156        }
157        Ok(lin)
158    }
159
160    /// The weight as a `QTensor` over the file (quantized codecs only).
161    fn qtensor(&self) -> Option<&QTensor> {
162        self.dev
163            .get_or_init(|| {
164                let e = &self.model.tensors[self.idx];
165                if e.shape.len() != 2 || matches!(self.host, HostW::Dense(_)) {
166                    return None;
167                }
168                QTensor::from_model(&self.model, &e.name).ok()
169            })
170            .as_ref()
171    }
172
173    /// This product for a device that keeps the weight itself.
174    fn ga(&self) -> crate::gpu::GaLin<'_> {
175        crate::gpu::GaLin { rows: self.rows, cols: self.cols, weight: self, bias: &self.bias }
176    }
177
178    /// `y[n, rows] = x[n, cols]·Wᵀ + b`.
179    fn apply(&self, x: &[f32], n: usize, ex: &Exec) -> Vec<f32> {
180        debug_assert_eq!(x.len(), n * self.cols);
181        let mut y = vec![0f32; n * self.rows];
182        let t0 = ex.prof.then(Instant::now);
183        let on_device = ex.gpu
184            && n >= 8
185            && n * self.rows * self.cols >= ex.gpu_min_macs
186            && self.qtensor().is_some_and(|q| q.device_matmat(x, n, &mut y));
187        if !on_device {
188            let w = match &self.host {
189                HostW::Dense(d) => ops::Weight::Dense(d),
190                HostW::Q8 { row_scale, col_field } => {
191                    let e = &self.model.tensors[self.idx];
192                    ops::Weight::Q8 { codes: &self.model.entry_bytes(e)[..self.rows * self.cols], row_scale, col_field }
193                }
194                HostW::Rows => ops::Weight::Rows(self.qtensor().expect("checked at load")),
195            };
196            ops::matmul(&w, self.rows, self.cols, x, n, &mut y, ex.pool);
197        }
198        if let Some(t0) = t0 {
199            ex.add(if on_device { Slot::GemmDev } else { Slot::GemmHost }, t0);
200        }
201        if !self.bias.is_empty() {
202            let (rows, yp) = (self.rows, ops::Shared(y.as_mut_ptr()));
203            ops::par(ex.pool, n, 256, &|a, b| {
204                // SAFETY: disjoint row ranges of `y`.
205                let part = unsafe { yp.slice(a * rows, (b - a) * rows) };
206                for row in part.chunks_exact_mut(rows) {
207                    ops::axpy(row, 1.0, &self.bias);
208                }
209            });
210        }
211        y
212    }
213}
214
215impl crate::gpu::GaWeight for Lin {
216    fn fill(&self, dst: &mut [f32]) {
217        let (rows, cols) = (self.rows, self.cols);
218        debug_assert_eq!(dst.len(), rows * cols);
219        match &self.host {
220            HostW::Dense(d) => dst.copy_from_slice(d),
221            HostW::Q8 { row_scale, col_field } => {
222                let codes = &self.model.entry_bytes(&self.model.tensors[self.idx])[..rows * cols];
223                for (r, row) in dst.chunks_exact_mut(cols).enumerate() {
224                    ops::widen_i8(row, &codes[r * cols..(r + 1) * cols]);
225                    let rs = row_scale[r];
226                    if col_field.is_empty() {
227                        row.iter_mut().for_each(|v| *v *= rs);
228                    } else {
229                        row.iter_mut().zip(col_field).for_each(|(v, &c)| *v *= rs * c);
230                    }
231                }
232            }
233            HostW::Rows => {
234                let q = self.qtensor().expect("checked at load");
235                for (r, row) in dst.chunks_exact_mut(cols).enumerate() {
236                    q.row_f32(r, row);
237                }
238            }
239        }
240    }
241}
242
243// ---------------------------------------------------------------------
244// execution context and timers
245// ---------------------------------------------------------------------
246
247#[derive(Clone, Copy)]
248enum Slot {
249    GemmHost,
250    GemmDev,
251    Attention,
252    Conv,
253    Glue,
254}
255const SLOTS: usize = 5;
256const SLOT_NAMES: [&str; SLOTS] = ["products (host)", "products (device)", "attention", "convolution", "activations and norms"];
257
258/// What a forward pass runs on.
259pub(crate) struct Exec<'a> {
260    pub pool: Option<&'a Pool>,
261    /// send products and attention to the device
262    pub gpu: bool,
263    /// a product smaller than this many multiply-adds stays on the host
264    pub gpu_min_macs: usize,
265    /// try the whole encoder on the device before the per-product path
266    pub resident: bool,
267    prof: bool,
268    times: [std::sync::atomic::AtomicU64; SLOTS],
269}
270
271impl<'a> Exec<'a> {
272    pub(crate) fn new(pool: Option<&'a Pool>) -> Self {
273        let gpu = crate::gpu::enabled_here() && std::env::var("CMF_GIGAAM_GPU").as_deref() != Ok("0");
274        let gpu_min_macs = std::env::var("CMF_GIGAAM_GPU_MIN").ok().and_then(|v| v.parse().ok()).unwrap_or(1 << 23);
275        Self {
276            pool,
277            gpu,
278            gpu_min_macs,
279            resident: gpu && std::env::var("CMF_GIGAAM_RESIDENT").as_deref() != Ok("0"),
280            prof: std::env::var("CMF_GIGAAM_PROF").is_ok_and(|v| v == "1"),
281            times: Default::default(),
282        }
283    }
284
285    fn add(&self, slot: Slot, since: Instant) {
286        self.times[slot as usize].fetch_add(since.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
287    }
288
289    fn timed<R>(&self, slot: Slot, f: impl FnOnce() -> R) -> R {
290        if !self.prof {
291            return f();
292        }
293        let t0 = Instant::now();
294        let r = f();
295        self.add(slot, t0);
296        r
297    }
298
299    fn report(&self) {
300        if !self.prof {
301            return;
302        }
303        let parts: Vec<String> = (0..SLOTS)
304            .map(|i| (SLOT_NAMES[i], self.times[i].swap(0, std::sync::atomic::Ordering::Relaxed)))
305            .filter(|(_, ns)| *ns > 0)
306            .map(|(name, ns)| format!("{name} {:.1} ms", ns as f64 / 1e6))
307            .collect();
308        eprintln!("gigaam encoder: {}", parts.join(" | "));
309    }
310}
311
312// ---------------------------------------------------------------------
313// front end: log-mel and the convolutional subsampling
314// ---------------------------------------------------------------------
315
316/// The mel front end: 20 ms Hann windows every 10 ms, no centering, the
317/// power spectrum through the checkpoint's own filter bank, natural log.
318struct Mel {
319    window: Vec<f32>,
320    /// per mel bin: `(first frequency bin, weights)`
321    bands: Vec<(usize, Vec<f32>)>,
322    fft: Arc<dyn rustfft::Fft<f32>>,
323}
324
325impl Mel {
326    fn load(m: &CmfModel, prefix: &str) -> Result<Self, String> {
327        let window = tensor_f32(m, &format!("{prefix}.featurizer.0.spectrogram.window"))?;
328        if window.len() != N_FFT {
329            return Err(format!("GigaAM front end: a window of {} samples (expected {N_FFT})", window.len()));
330        }
331        let fb_name = format!("{prefix}.featurizer.0.mel_scale.fb");
332        let fb = tensor_f32(m, &fb_name)?;
333        let shape = &m.tensor(&fb_name).unwrap().shape;
334        let bins = N_FFT / 2 + 1;
335        if shape.len() != 2 || shape[0] != bins {
336            return Err(format!("{fb_name}: shape {shape:?}, expected [{bins}, mel]"));
337        }
338        let n_mel = shape[1];
339        let bands = (0..n_mel)
340            .map(|mb| {
341                let col: Vec<f32> = (0..bins).map(|k| fb[k * n_mel + mb]).collect();
342                let first = col.iter().position(|v| *v != 0.0).unwrap_or(0);
343                let last = col.iter().rposition(|v| *v != 0.0).map_or(first, |l| l + 1);
344                (first, col[first..last].to_vec())
345            })
346            .collect();
347        Ok(Self { window, bands, fft: rustfft::FftPlanner::<f32>::new().plan_fft_forward(N_FFT) })
348    }
349
350    fn n_mel(&self) -> usize {
351        self.bands.len()
352    }
353
354    /// Mel frames of `samples`.
355    fn frames(samples: usize) -> usize {
356        if samples < N_FFT { 0 } else { (samples - N_FFT) / HOP + 1 }
357    }
358
359    /// `[frames, mel]` log-mel features.
360    fn features(&self, samples: &[f32], pool: Option<&Pool>) -> Vec<f32> {
361        let (frames, n_mel) = (Self::frames(samples.len()), self.n_mel());
362        let mut out = vec![0f32; frames * n_mel];
363        let op = ops::Shared(out.as_mut_ptr());
364        ops::par(pool, frames, 256, &|a, b| {
365            use rustfft::num_complex::Complex;
366            let mut buf = vec![Complex::new(0f32, 0f32); N_FFT];
367            let mut scratch = vec![Complex::new(0f32, 0f32); self.fft.get_inplace_scratch_len()];
368            let mut power = vec![0f32; N_FFT / 2 + 1];
369            for t in a..b {
370                let frame = &samples[t * HOP..t * HOP + N_FFT];
371                for ((c, &s), &w) in buf.iter_mut().zip(frame).zip(&self.window) {
372                    *c = Complex::new(s * w, 0.0);
373                }
374                self.fft.process_with_scratch(&mut buf, &mut scratch);
375                for (p, c) in power.iter_mut().zip(&buf) {
376                    *p = c.norm_sqr();
377                }
378                // SAFETY: frame `t` belongs to this range alone.
379                let row = unsafe { op.slice(t * n_mel, n_mel) };
380                for (v, (first, w)) in row.iter_mut().zip(&self.bands) {
381                    let e: f32 = w.iter().zip(&power[*first..]).map(|(w, p)| w * p).sum();
382                    *v = e.clamp(1e-9, 1e9).ln();
383                }
384            }
385        });
386        out
387    }
388}
389
390/// The causal convolutional front end: 3×3, 3×3 stride 2, 3×3 stride 2, a
391/// ConvNeXt block, and a projection of the 64 × 15 map to the model width.
392struct Embed {
393    conv: [(Vec<f32>, Vec<f32>, usize); 3],
394    dw: (Vec<f32>, Vec<f32>),
395    pw1: Lin,
396    pw2: Lin,
397    out: Lin,
398}
399
400impl Embed {
401    fn load(m: &Arc<CmfModel>) -> Result<Self, String> {
402        let conv = |i: usize| -> Result<(Vec<f32>, Vec<f32>, usize), String> {
403            let name = format!("{EMBED}.conv{i}.weight");
404            let co = m.tensor(&name).ok_or_else(|| format!("missing GigaAM tensor {name}"))?.shape[0];
405            Ok((tensor_f32(m, &name)?, tensor_f32(m, &format!("{EMBED}.conv{i}.bias"))?, co))
406        };
407        Ok(Self {
408            conv: [conv(1)?, conv(2)?, conv(3)?],
409            dw: (
410                tensor_f32(m, &format!("{EMBED}.convnext.depthwise_conv.weight"))?,
411                tensor_f32(m, &format!("{EMBED}.convnext.depthwise_conv.bias"))?,
412            ),
413            pw1: Lin::load(m, &format!("{EMBED}.convnext.pointwise_conv1"))?,
414            pw2: Lin::load(m, &format!("{EMBED}.convnext.pointwise_conv2"))?,
415            out: Lin::load(m, &format!("{EMBED}.out"))?,
416        })
417    }
418
419    /// The front end for a device that runs it itself.
420    fn ga(&self, n_mel: usize) -> crate::gpu::GaFront<'_> {
421        let c = |i: usize| (self.conv[i].0.as_slice(), self.conv[i].1.as_slice(), self.conv[i].2);
422        crate::gpu::GaFront { n_mel, conv: [c(0), c(1), c(2)], dw: (&self.dw.0, &self.dw.1), pw1: self.pw1.ga(), pw2: self.pw2.ga(), out: self.out.ga() }
423    }
424
425    /// Encoder frames for `frames` mel frames.
426    fn out_frames(frames: usize) -> usize {
427        frames.div_ceil(2).div_ceil(2)
428    }
429
430    /// `[mel frames, mel]` features of one segment to `[T, width]` rows.
431    fn forward(&self, feats: &[f32], frames: usize, n_mel: usize, ex: &Exec) -> Vec<f32> {
432        // [1, t, f]: the features are already time-major
433        let mut x = ops::Vol { c: 1, t: frames, f: n_mel, d: feats.to_vec() };
434        for (i, (w, b, co)) in self.conv.iter().enumerate() {
435            x = if i == 0 {
436                ops::conv3x3(&x, w, b, *co, 1, (2, 0), 1, ex.pool)
437            } else {
438                ops::conv3x3(&x, w, b, *co, 2, (1, 1), 0, ex.pool)
439            };
440            silu_par(&mut x.d, ex.pool);
441        }
442        // ConvNeXt: depthwise 3×3, 1×1 up, SiLU, 1×1 down, residual
443        let y = ops::depthwise3x3_causal(&x, &self.dw.0, &self.dw.1, ex.pool);
444        let (c, t, f) = (x.c, x.t, x.f);
445        let n = t * f;
446        let mut rows = vec![0f32; n * c];
447        for ch in 0..c {
448            for p in 0..n {
449                rows[p * c + ch] = y.d[ch * n + p];
450            }
451        }
452        let mut h = self.pw1.apply(&rows, n, ex);
453        silu_par(&mut h, ex.pool);
454        let h = self.pw2.apply(&h, n, ex);
455        // [t, c·f] rows for the projection: channel-major inside a frame
456        let mut flat = vec![0f32; t * c * f];
457        for tt in 0..t {
458            for ch in 0..c {
459                for ff in 0..f {
460                    flat[(tt * c + ch) * f + ff] = x.d[(ch * t + tt) * f + ff] + h[(tt * f + ff) * c + ch];
461                }
462            }
463        }
464        self.out.apply(&flat, t, ex)
465    }
466}
467
468fn silu_par(x: &mut [f32], pool: Option<&Pool>) {
469    let xp = ops::Shared(x.as_mut_ptr());
470    ops::par(pool, x.len().div_ceil(4096), 8, &|a, b| {
471        let end = (b * 4096).min(x.len());
472        // SAFETY: disjoint ranges of `x`.
473        ops::silu(unsafe { xp.slice(a * 4096, end - a * 4096) });
474    });
475}
476
477// ---------------------------------------------------------------------
478// the encoder
479// ---------------------------------------------------------------------
480
481struct Ff {
482    inp: Lin,
483    out: Lin,
484}
485
486impl Ff {
487    fn load(m: &Arc<CmfModel>, p: &str) -> Result<Self, String> {
488        Ok(Self { inp: Lin::load(m, &format!("{p}.in_proj"))?, out: Lin::load(m, &format!("{p}.out_proj"))? })
489    }
490
491    fn forward(&self, x: &[f32], n: usize, ex: &Exec) -> Vec<f32> {
492        let mut h = self.inp.apply(x, n, ex);
493        ex.timed(Slot::Glue, || silu_par(&mut h, ex.pool));
494        self.out.apply(&h, n, ex)
495    }
496}
497
498struct Attn {
499    in_norm: Vec<f32>,
500    qk: Lin,
501    vg: Lin,
502    out: Lin,
503    heads: usize,
504}
505
506struct ConvMod {
507    inp: Lin,
508    dw_w: Vec<f32>,
509    /// the same taps as `[kernel][channel]`
510    taps: Vec<f32>,
511    dw_b: Vec<f32>,
512    kernel: usize,
513    mean_w: Vec<f32>,
514    out: Lin,
515}
516
517struct Layer {
518    ff1: Ff,
519    attn: Attn,
520    conv: Option<ConvMod>,
521    ff2: Option<Ff>,
522    norm: Vec<f32>,
523}
524
525struct Stack {
526    /// frames folded into one row
527    ds: usize,
528    dim: usize,
529    proj: Lin,
530    proj_t: Lin,
531    residual_scales: Vec<f32>,
532    input_scale: f32,
533    layers: Vec<Layer>,
534}
535
536/// `out[r] = x[r] · rsqrt(mean(x[r]²) + eps) ⊙ w` over rows.
537fn rms_rows(x: &[f32], dim: usize, w: &[f32], eps: f32, pool: Option<&Pool>) -> Vec<f32> {
538    let n = x.len() / dim;
539    let mut out = vec![0f32; x.len()];
540    let op = ops::Shared(out.as_mut_ptr());
541    ops::par(pool, n, 128, &|a, b| {
542        for r in a..b {
543            let src = &x[r * dim..(r + 1) * dim];
544            let inv = 1.0 / (ops::sumsq(src) / dim as f32 + eps).sqrt();
545            // SAFETY: row `r` belongs to this range alone.
546            let dst = unsafe { op.slice(r * dim, dim) };
547            for ((d, &v), &w) in dst.iter_mut().zip(src).zip(w) {
548                *d = v * inv * w;
549            }
550        }
551    });
552    out
553}
554
555fn add_rows(x: &mut [f32], y: &[f32], pool: Option<&Pool>) {
556    let xp = ops::Shared(x.as_mut_ptr());
557    ops::par(pool, x.len().div_ceil(8192), 8, &|a, b| {
558        let (s, e) = (a * 8192, (b * 8192).min(x.len()));
559        // SAFETY: disjoint ranges of `x`.
560        ops::axpy(unsafe { xp.slice(s, e - s) }, 1.0, &y[s..e]);
561    });
562}
563
564impl Attn {
565    fn load(m: &Arc<CmfModel>, p: &str, heads: usize) -> Result<Self, String> {
566        let a = Self {
567            in_norm: tensor_f32(m, &format!("{p}.in_norm.weight"))?,
568            qk: Lin::load(m, &format!("{p}.qk_in_proj"))?,
569            vg: Lin::load(m, &format!("{p}.vg_in_proj"))?,
570            out: Lin::load(m, &format!("{p}.out_proj"))?,
571            heads,
572        };
573        let hw = heads * QDIM;
574        if a.qk.rows != 2 * hw || a.vg.rows != 3 * hw || a.out.cols != hw {
575            return Err(format!("{p}: attention shapes do not match {heads} heads of {QDIM}"));
576        }
577        Ok(a)
578    }
579
580    /// `x_qk` is the layer input (queries and keys), `x_vg` the stream after
581    /// the first feed-forward (values and both gates). Rows are the segments
582    /// of `segs` back to back; attention stays inside a segment.
583    fn forward(&self, x_qk: &[f32], x_vg: &[f32], segs: &[usize], rope: &Rope, ex: &Exec) -> Vec<f32> {
584        let n: usize = segs.iter().sum();
585        let dim = self.in_norm.len();
586        let (heads, hw) = (self.heads, self.heads * QDIM);
587        let normed = ex.timed(Slot::Glue, || rms_rows(x_qk, dim, &self.in_norm, 1e-6, ex.pool));
588        let qk = self.qk.apply(&normed, n, ex);
589        drop(normed);
590        let vg = self.vg.apply(x_vg, n, ex);
591        let mut ctx = vec![0f32; n * hw];
592        let t0 = ex.prof.then(Instant::now);
593        let scale = (QDIM as f32).powf(-0.5);
594        let mut row0 = 0;
595        for &t in segs {
596            assert!(t <= rope.positions(), "a GigaAM segment of {t} frames is past the rotary table");
597            // head-major planes [head][frame][32]: rotated queries and keys, gated values
598            let mut qh = vec![0f32; heads * t * QDIM];
599            let mut kh = vec![0f32; heads * t * QDIM];
600            let mut vh = vec![0f32; heads * t * QDIM];
601            {
602                let (qp, kp, vp) = (ops::Shared(qh.as_mut_ptr()), ops::Shared(kh.as_mut_ptr()), ops::Shared(vh.as_mut_ptr()));
603                ops::par(ex.pool, t, 64, &|a, b| {
604                    let mut gated = vec![0f32; hw];
605                    for i in a..b {
606                        let r = row0 + i;
607                        let (q, k) = qk[r * 2 * hw..(r + 1) * 2 * hw].split_at(hw);
608                        let v = &vg[r * 3 * hw..r * 3 * hw + hw];
609                        let gate_in = &vg[r * 3 * hw + hw..r * 3 * hw + 2 * hw];
610                        gated.copy_from_slice(v);
611                        ops::mul_sigmoid(&mut gated, gate_in);
612                        let (cos, sin) = rope.at(i);
613                        for h in 0..heads {
614                            // SAFETY: frame `i` of every head belongs to this range alone.
615                            let (qd, kd, vd) = unsafe {
616                                let at = (h * t + i) * QDIM;
617                                (qp.slice(at, QDIM), kp.slice(at, QDIM), vp.slice(at, QDIM))
618                            };
619                            rotate(&q[h * QDIM..(h + 1) * QDIM], cos, sin, qd);
620                            rotate(&k[h * QDIM..(h + 1) * QDIM], cos, sin, kd);
621                            vd.copy_from_slice(&gated[h * QDIM..(h + 1) * QDIM]);
622                        }
623                    }
624                });
625            }
626            let out = &mut ctx[row0 * hw..(row0 + t) * hw];
627            let on_device = ex.gpu && t >= ex.attn_min() && crate::gpu::dit_attention(&qh, &kh, &vh, heads, heads, t, QDIM, scale, out);
628            if !on_device {
629                attention_host(&qh, &kh, &vh, heads, t, scale, out, ex.pool);
630            }
631            row0 += t;
632        }
633        // gate the context, project
634        {
635            let cp = ops::Shared(ctx.as_mut_ptr());
636            ops::par(ex.pool, n, 128, &|a, b| {
637                for r in a..b {
638                    // SAFETY: row `r` belongs to this range alone.
639                    let row = unsafe { cp.slice(r * hw, hw) };
640                    ops::mul_sigmoid(row, &vg[r * 3 * hw + 2 * hw..(r + 1) * 3 * hw]);
641                }
642            });
643        }
644        if let Some(t0) = t0 {
645            ex.add(Slot::Attention, t0);
646        }
647        self.out.apply(&ctx, n, ex)
648    }
649}
650
651impl Exec<'_> {
652    /// Segments shorter than this attend on the host.
653    fn attn_min(&self) -> usize {
654        64
655    }
656}
657
658/// `dst = rope(x)`: pairs `(2i, 2i+1)` rotated by the position's angles.
659#[inline]
660fn rotate(x: &[f32], cos: &[f32], sin: &[f32], dst: &mut [f32]) {
661    for i in 0..QDIM / 2 {
662        let (x0, x1) = (x[2 * i], x[2 * i + 1]);
663        dst[2 * i] = x0 * cos[i] - x1 * sin[i];
664        dst[2 * i + 1] = x0 * sin[i] + x1 * cos[i];
665    }
666}
667
668/// Full attention of one segment on the host: per head `softmax(scale·q·kᵀ)·v`.
669/// `out` is `[frame][head·32]`.
670#[allow(clippy::too_many_arguments)]
671fn attention_host(qh: &[f32], kh: &[f32], vh: &[f32], heads: usize, t: usize, scale: f32, out: &mut [f32], pool: Option<&Pool>) {
672    let hw = heads * QDIM;
673    let op = ops::Shared(out.as_mut_ptr());
674    let one = |h: usize, scores: &mut Vec<f32>, ctx: &mut Vec<f32>| {
675        let plane = h * t * QDIM..(h + 1) * t * QDIM;
676        scores.resize(t * t, 0.0);
677        ctx.resize(t * QDIM, 0.0);
678        ops::gemm_nt(&qh[plane.clone()], &kh[plane.clone()], scores, t, t, QDIM, None);
679        for row in scores.chunks_exact_mut(t) {
680            ops::softmax_scaled(row, scale);
681        }
682        ops::gemm_nn(scores, &vh[plane], ctx, t, QDIM, t, None);
683        for i in 0..t {
684            // SAFETY: the head's columns of every row belong to this head alone.
685            unsafe { op.slice(i * hw + h * QDIM, QDIM) }.copy_from_slice(&ctx[i * QDIM..(i + 1) * QDIM]);
686        }
687    };
688    ops::par(pool, heads, 2, &|a, b| {
689        let (mut scores, mut ctx) = (Vec::new(), Vec::new());
690        for h in a..b {
691            one(h, &mut scores, &mut ctx);
692        }
693    });
694}
695
696/// The rotary table: `[position][16]` cosines and sines, as the checkpoint
697/// stores them.
698struct Rope {
699    cos: Vec<f32>,
700    sin: Vec<f32>,
701}
702
703impl Rope {
704    fn load(m: &CmfModel) -> Result<Self, String> {
705        let name = |part: &str| format!("{ENC}.rope_bank.tables.ed{QDIM}_S10000_b10000.{part}");
706        let (cos, sin) = match (m.tensor(&name("cos")), m.tensor(&name("sin"))) {
707            (Some(_), Some(_)) => (tensor_f32(m, &name("cos"))?, tensor_f32(m, &name("sin"))?),
708            _ => {
709                let inv: Vec<f32> = (0..QDIM / 2).map(|i| 1.0 / 10000f32.powf(2.0 * i as f32 / QDIM as f32)).collect();
710                let mut cos = Vec::with_capacity(10_000 * QDIM / 2);
711                let mut sin = Vec::with_capacity(10_000 * QDIM / 2);
712                for p in 0..10_000 {
713                    for f in &inv {
714                        let a = p as f32 * f;
715                        cos.push(a.cos());
716                        sin.push(a.sin());
717                    }
718                }
719                (cos, sin)
720            }
721        };
722        Ok(Self { cos, sin })
723    }
724
725    fn positions(&self) -> usize {
726        self.cos.len() / (QDIM / 2)
727    }
728
729    fn at(&self, pos: usize) -> (&[f32], &[f32]) {
730        let h = QDIM / 2;
731        (&self.cos[pos * h..(pos + 1) * h], &self.sin[pos * h..(pos + 1) * h])
732    }
733}
734
735impl ConvMod {
736    fn load(m: &Arc<CmfModel>, p: &str, kernel: usize) -> Result<Self, String> {
737        let dw_w = tensor_f32(m, &format!("{p}.depthwise_conv.weight"))?;
738        let d = dw_w.len() / kernel.max(1);
739        let mut taps = vec![0f32; dw_w.len()];
740        for c in 0..d {
741            for j in 0..kernel {
742                taps[j * d + c] = dw_w[c * kernel + j];
743            }
744        }
745        Ok(Self {
746            inp: Lin::load(m, &format!("{p}.in_proj"))?,
747            dw_w,
748            taps,
749            dw_b: tensor_f32(m, &format!("{p}.depthwise_conv.bias"))?,
750            kernel,
751            mean_w: tensor_f32(m, &format!("{p}.weighted_mean.weights"))?,
752            out: Lin::load(m, &format!("{p}.out_proj"))?,
753        })
754    }
755
756    fn forward(&self, x: &[f32], segs: &[usize], ex: &Exec) -> Vec<f32> {
757        let n: usize = segs.iter().sum();
758        let d = self.mean_w.len();
759        let xg = self.inp.apply(x, n, ex);
760        let t0 = ex.prof.then(Instant::now);
761        // split the stream from its gate
762        let mut xs = vec![0f32; n * d];
763        for (dst, src) in xs.chunks_exact_mut(d).zip(xg.chunks_exact(2 * d)) {
764            dst.copy_from_slice(&src[..d]);
765        }
766        let mut y = vec![0f32; n * d];
767        let mut row0 = 0;
768        for &t in segs {
769            let seg = &xs[row0 * d..(row0 + t) * d];
770            // the segment's mean, weighted per channel
771            let mut mean = vec![0f32; d];
772            for row in seg.chunks_exact(d) {
773                ops::axpy(&mut mean, 1.0, row);
774            }
775            for (m, &w) in mean.iter_mut().zip(&self.mean_w) {
776                *m = *m / t as f32 * w;
777            }
778            let out = &mut y[row0 * d..(row0 + t) * d];
779            ops::depthwise1d(seg, t, d, &self.dw_w, &self.dw_b, self.kernel, out, ex.pool);
780            let op = ops::Shared(out.as_mut_ptr());
781            ops::par(ex.pool, t, 64, &|a, b| {
782                for i in a..b {
783                    // SAFETY: row `i` belongs to this range alone.
784                    let row = unsafe { op.slice(i * d, d) };
785                    ops::add_mul_sigmoid_silu(row, &mean, &xg[(row0 + i) * 2 * d + d..(row0 + i + 1) * 2 * d]);
786                }
787            });
788            row0 += t;
789        }
790        if let Some(t0) = t0 {
791            ex.add(Slot::Conv, t0);
792        }
793        self.out.apply(&y, n, ex)
794    }
795}
796
797impl Layer {
798    fn forward(&self, x: Vec<f32>, dim: usize, segs: &[usize], rope: &Rope, ex: &Exec) -> Vec<f32> {
799        let n: usize = segs.iter().sum();
800        let mut s = x.clone();
801        add_rows(&mut s, &self.ff1.forward(&x, n, ex), ex.pool);
802        let a = self.attn.forward(&x, &s, segs, rope, ex);
803        add_rows(&mut s, &a, ex.pool);
804        if let Some(conv) = &self.conv {
805            let c = conv.forward(&s, segs, ex);
806            add_rows(&mut s, &c, ex.pool);
807        }
808        if let Some(ff2) = &self.ff2 {
809            let f = ff2.forward(&s, n, ex);
810            add_rows(&mut s, &f, ex.pool);
811        }
812        ex.timed(Slot::Glue, || {
813            // norm(residual + ¼·(stream − residual))
814            let sp = ops::Shared(s.as_mut_ptr());
815            ops::par(ex.pool, n, 128, &|a, b| {
816                // SAFETY: disjoint row ranges of `s`.
817                let part = unsafe { sp.slice(a * dim, (b - a) * dim) };
818                for (v, &r) in part.iter_mut().zip(&x[a * dim..b * dim]) {
819                    *v = r + 0.25 * (*v - r);
820                }
821            });
822            rms_rows(&s, dim, &self.norm, 1e-6, ex.pool)
823        })
824    }
825}
826
827impl Stack {
828    fn forward(&self, x_in: &[f32], segs: &[usize], rope: &Rope, ex: &Exec) -> Vec<f32> {
829        let n: usize = segs.iter().sum();
830        let mut x = self.proj.apply(x_in, n, ex);
831        let mut bypass: Vec<f32> = x.iter().map(|v| v * self.residual_scales[0]).collect();
832        for v in &mut x {
833            *v *= self.input_scale;
834        }
835        for (i, layer) in self.layers.iter().enumerate() {
836            x = layer.forward(x, self.dim, segs, rope, ex);
837            let (bp, w) = (ops::Shared(bypass.as_mut_ptr()), self.residual_scales[i + 1]);
838            ops::par(ex.pool, bypass.len().div_ceil(8192), 8, &|a, b| {
839                let (s, e) = (a * 8192, (b * 8192).min(x.len()));
840                // SAFETY: disjoint ranges of `bypass`.
841                ops::axpy(unsafe { bp.slice(s, e - s) }, w, &x[s..e]);
842            });
843        }
844        let mut out = self.proj_t.apply(&bypass, n, ex);
845        add_rows(&mut out, x_in, ex.pool);
846        out
847    }
848}
849
850struct Encoder {
851    stacks: Vec<Stack>,
852    rope: Rope,
853    out_scale: f32,
854    out_eps: f32,
855    width: usize,
856    /// the model's key in a device weight cache
857    key: u64,
858    /// the device declined the whole-encoder path: do not ask again
859    resident_off: std::sync::atomic::AtomicBool,
860}
861
862impl Encoder {
863    fn load(m: &Arc<CmfModel>, cfg: &serde_json::Value) -> Result<Self, String> {
864        let tuple = |key: &str| -> Result<Vec<usize>, String> {
865            let v = match cfg.get(key) {
866                Some(serde_json::Value::String(s)) => s.split(',').map(|x| x.trim().parse::<usize>()).collect::<Result<Vec<_>, _>>().ok(),
867                Some(serde_json::Value::Number(n)) => n.as_u64().map(|v| vec![v as usize]),
868                _ => None,
869            };
870            v.filter(|v| !v.is_empty()).ok_or_else(|| format!("GigaAM config: encoder.{key}"))
871        };
872        let ds = tuple("downsampling_factor")?;
873        let n = ds.len();
874        let per = |key: &str| -> Result<Vec<usize>, String> {
875            let v = tuple(key)?;
876            match v.len() {
877                1 => Ok(vec![v[0]; n]),
878                l if l == n => Ok(v),
879                _ => Err(format!("GigaAM config: encoder.{key} has {} entries for {n} stacks", v.len())),
880            }
881        };
882        let (dims, layers, heads, kernels) = (per("encoder_dim")?, per("num_encoder_layers")?, per("num_heads")?, per("conv_params")?);
883        if per("query_head_dim")?.iter().chain(&per("value_head_dim")?).any(|d| *d != QDIM) {
884            return Err(format!("GigaAM: only {QDIM}-wide attention heads are supported"));
885        }
886        if cfg.get("activation").and_then(|v| v.as_str()).is_some_and(|a| !a.eq_ignore_ascii_case("silu")) {
887            return Err("GigaAM: only the SiLU activation is supported".into());
888        }
889        if ds.iter().any(|d| *d != 1 && *d != 2) {
890            return Err("GigaAM: stacks at 1× or 2× the frame step only".into());
891        }
892        let width = dims[0];
893        let mut stacks = Vec::with_capacity(n);
894        for s in 0..n {
895            let p = format!("{ENC}.encoders.{s}");
896            let mut ls = Vec::with_capacity(layers[s]);
897            for l in 0..layers[s] {
898                let lp = format!("{p}.layers.{l}");
899                let (conv, ff2) = if kernels[s] > 0 {
900                    (Some(ConvMod::load(m, &format!("{lp}.conv_module"), kernels[s])?), Some(Ff::load(m, &format!("{lp}.feed_forward2"))?))
901                } else {
902                    (None, None)
903                };
904                ls.push(Layer {
905                    ff1: Ff::load(m, &format!("{lp}.feed_forward1"))?,
906                    attn: Attn::load(m, &format!("{lp}.self_attn"), heads[s])?,
907                    conv,
908                    ff2,
909                    norm: tensor_f32(m, &format!("{lp}.norm.weight"))?,
910                });
911            }
912            let proj = Lin::load_named(m, &format!("{p}.proj.weight"), None)?;
913            let proj_t = Lin::load_named(m, &format!("{p}.proj_t.weight"), None)?;
914            if proj.cols != ds[s] * width || proj.rows != dims[s] || proj_t.rows != proj.cols {
915                return Err(format!("{p}: projection {}×{} does not fit the stack", proj.rows, proj.cols));
916            }
917            let residual_scales = tensor_f32(m, &format!("{p}.residual_scales"))?;
918            if residual_scales.len() != layers[s] + 1 {
919                return Err(format!("{p}: {} residual scales for {} layers", residual_scales.len(), layers[s]));
920            }
921            stacks.push(Stack { ds: ds[s], dim: dims[s], proj, proj_t, residual_scales, input_scale: scalar(m, &format!("{p}.input_scale"))?, layers: ls });
922        }
923        Ok(Self {
924            stacks,
925            rope: Rope::load(m)?,
926            out_scale: scalar(m, &format!("{ENC}.out_norm.scale"))?,
927            out_eps: scalar(m, &format!("{ENC}.out_norm.eps"))?,
928            width,
929            key: m.uid(),
930            resident_off: Default::default(),
931        })
932    }
933
934    /// The stacks as the device's whole-encoder path takes them.
935    fn ga_args(&self, prof: bool) -> crate::gpu::GigaamArgs<'_> {
936        use crate::gpu::{GaConv, GaLayer, GaStack, GigaamArgs};
937        let stacks = self
938            .stacks
939            .iter()
940            .map(|st| GaStack {
941                fold: st.ds,
942                dim: st.dim,
943                heads: st.layers.first().map_or(1, |l| l.attn.heads),
944                proj: st.proj.ga(),
945                proj_t: st.proj_t.ga(),
946                residual_scales: &st.residual_scales,
947                input_scale: st.input_scale,
948                layers: st
949                    .layers
950                    .iter()
951                    .map(|l| GaLayer {
952                        ff1_in: l.ff1.inp.ga(),
953                        ff1_out: l.ff1.out.ga(),
954                        in_norm: &l.attn.in_norm,
955                        qk: l.attn.qk.ga(),
956                        vg: l.attn.vg.ga(),
957                        attn_out: l.attn.out.ga(),
958                        conv: l.conv.as_ref().map(|c| GaConv { inp: c.inp.ga(), taps: &c.taps, bias: &c.dw_b, kernel: c.kernel, mean_w: &c.mean_w, out: c.out.ga() }),
959                        ff2: l.ff2.as_ref().map(|f| (f.inp.ga(), f.out.ga())),
960                        norm: &l.norm,
961                    })
962                    .collect(),
963            })
964            .collect();
965        GigaamArgs { key: self.key, width: self.width, head_dim: QDIM, stacks, cos: &self.rope.cos, sin: &self.rope.sin, out_scale: self.out_scale, out_eps: self.out_eps, prof, front: None }
966    }
967
968    /// The whole encoder on the device, a segment at a time; `None` when it declines.
969    fn forward_resident(&self, x: &[f32], segs: &[usize], ex: &Exec) -> Option<Vec<f32>> {
970        use std::sync::atomic::Ordering;
971        if !ex.resident || self.resident_off.load(Ordering::Relaxed) {
972            return None;
973        }
974        let args = self.ga_args(ex.prof);
975        let w = self.width;
976        let mut out = x.to_vec();
977        let mut row0 = 0;
978        for &t in segs {
979            if !crate::gpu::gigaam_encode(&args, &mut out[row0 * w..(row0 + t) * w], t) {
980                self.resident_off.store(true, Ordering::Relaxed);
981                return None;
982            }
983            row0 += t;
984        }
985        Some(out)
986    }
987
988    /// `[Σ segs, width]` front-end rows to encoder output rows.
989    fn forward(&self, mut x: Vec<f32>, segs: &[usize], ex: &Exec) -> Vec<f32> {
990        let w = self.width;
991        if let Some(out) = self.forward_resident(&x, segs, ex) {
992            return out;
993        }
994        for stack in &self.stacks {
995            if stack.ds == 1 {
996                x = stack.forward(&x, segs, &self.rope, ex);
997                continue;
998            }
999            // fold pairs of frames into rows (an odd last frame pairs with zeros)
1000            let half: Vec<usize> = segs.iter().map(|t| t.div_ceil(2)).collect();
1001            let nh: usize = half.iter().sum();
1002            let mut folded = vec![0f32; nh * 2 * w];
1003            let (mut src, mut dst) = (0, 0);
1004            for &t in segs {
1005                folded[dst * 2 * w..dst * 2 * w + t * w].copy_from_slice(&x[src * w..(src + t) * w]);
1006                src += t;
1007                dst += t.div_ceil(2);
1008            }
1009            let y = stack.forward(&folded, &half, &self.rope, ex);
1010            let (mut src, mut dst) = (0, 0);
1011            for &t in segs {
1012                x[dst * w..(dst + t) * w].copy_from_slice(&y[src * 2 * w..src * 2 * w + t * w]);
1013                dst += t;
1014                src += t.div_ceil(2);
1015            }
1016        }
1017        ex.timed(Slot::Glue, || {
1018            let (scale, eps2) = (self.out_scale, self.out_eps * self.out_eps);
1019            let xp = ops::Shared(x.as_mut_ptr());
1020            ops::par(ex.pool, x.len() / w, 128, &|a, b| {
1021                for r in a..b {
1022                    // SAFETY: row `r` belongs to this range alone.
1023                    let row = unsafe { xp.slice(r * w, w) };
1024                    let k = scale / (ops::sumsq(row) / w as f32 + eps2).sqrt();
1025                    for v in row.iter_mut() {
1026                        *v *= k;
1027                    }
1028                }
1029            });
1030        });
1031        x
1032    }
1033}
1034
1035// ---------------------------------------------------------------------
1036// the transcriber
1037// ---------------------------------------------------------------------
1038
1039/// Which transcripts to produce.
1040#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1041pub enum Heads {
1042    /// formatted text: case, punctuation, digits
1043    E2e,
1044    /// lower-case words
1045    Raw,
1046    Both,
1047}
1048
1049/// Transcription settings.
1050#[derive(Clone, Debug)]
1051pub struct Options {
1052    pub heads: Heads,
1053    /// word start and end times
1054    pub words: bool,
1055    /// cut the recording by voice activity even when it fits one segment
1056    pub force_vad: bool,
1057    /// encoder frames in one batch of segments at most
1058    pub batch_frames: usize,
1059    pub vad: vad::Settings,
1060}
1061
1062impl Default for Options {
1063    fn default() -> Self {
1064        Self {
1065            heads: Heads::E2e,
1066            words: false,
1067            force_vad: false,
1068            batch_frames: std::env::var("CMF_GIGAAM_BATCH_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(4500),
1069            vad: vad::Settings::default(),
1070        }
1071    }
1072}
1073
1074/// One stretch of speech and what was said in it.
1075#[derive(Clone, Debug)]
1076pub struct Segment {
1077    /// seconds from the start of the recording
1078    pub start: f64,
1079    pub end: f64,
1080    pub text: String,
1081    /// present when [`Options::words`] was set (times from the start of the recording)
1082    pub words: Vec<Word>,
1083}
1084
1085/// The transcript of one head.
1086#[derive(Clone, Debug, Default)]
1087pub struct Transcript {
1088    pub text: String,
1089    pub segments: Vec<Segment>,
1090}
1091
1092/// What [`Transcriber::transcribe`] returns.
1093#[derive(Clone, Debug, Default)]
1094pub struct Output {
1095    /// formatted text (when asked for)
1096    pub e2e: Option<Transcript>,
1097    /// lower-case words (when asked for)
1098    pub raw: Option<Transcript>,
1099    pub audio_s: f64,
1100    /// seconds of speech sent through the encoder
1101    pub speech_s: f64,
1102    pub vad_s: f64,
1103    pub features_s: f64,
1104    pub encoder_s: f64,
1105    pub decode_s: f64,
1106}
1107
1108impl Output {
1109    /// The transcript a caller who asked for one head wants: formatted when present.
1110    pub fn text(&self) -> &str {
1111        self.e2e.as_ref().or(self.raw.as_ref()).map_or("", |t| t.text.as_str())
1112    }
1113
1114    /// Seconds of work: everything after the audio was read.
1115    pub fn total_s(&self) -> f64 {
1116        self.vad_s + self.features_s + self.encoder_s + self.decode_s
1117    }
1118}
1119
1120/// A loaded GigaAM model.
1121pub struct Transcriber {
1122    mel: Mel,
1123    embed: Embed,
1124    encoder: Encoder,
1125    e2e: decode::Head,
1126    raw: decode::Head,
1127    vad: Option<vad::Vad>,
1128    /// the device declined the front end: the host runs it
1129    front_dev_off: std::sync::atomic::AtomicBool,
1130    /// `rnnt` or `ctc`
1131    pub revision: String,
1132}
1133
1134impl Transcriber {
1135    pub fn load(model: &Arc<CmfModel>) -> Result<Self, String> {
1136        if !is_gigaam(model) {
1137            return Err(format!("not a GigaAM file (arch '{}')", model.header.arch.arch_name));
1138        }
1139        let meta = model
1140            .header
1141            .provenance
1142            .as_ref()
1143            .and_then(|p| p.get("gigaam"))
1144            .ok_or("GigaAM file without its config (header provenance.gigaam)")?;
1145        let cfg = meta.pointer("/config/cfg").ok_or("GigaAM file: no config.cfg")?;
1146        let enc_cfg = cfg.get("encoder").ok_or("GigaAM config: no encoder")?;
1147        let mel = Mel::load(model, "model.preprocessor")?;
1148        let head = |name: &str| decode::Head::load(model, cfg, meta.get("tokenizers"), name);
1149        let vad = match meta.get("vad_config").filter(|v| !v.is_null()) {
1150            Some(vc) if model.tensor("vad.head.decoder_layers.0.weight").is_some() => Some(vad::Vad::load(model, vc)?),
1151            _ => None,
1152        };
1153        Ok(Self {
1154            mel,
1155            embed: Embed::load(model)?,
1156            encoder: Encoder::load(model, enc_cfg)?,
1157            e2e: head("e2e")?,
1158            raw: head("raw")?,
1159            vad,
1160            front_dev_off: Default::default(),
1161            revision: meta.get("revision").and_then(|v| v.as_str()).unwrap_or("").to_string(),
1162        })
1163    }
1164
1165    /// Does the file carry the voice-activity model (recordings over 30 s)?
1166    pub fn has_vad(&self) -> bool {
1167        self.vad.is_some()
1168    }
1169
1170    /// Encoder output of one clip of at most 30 s: `[T, width]` rows.
1171    pub fn encode(&self, samples: &[f32], pool: Option<&Pool>) -> Result<(Vec<f32>, usize), String> {
1172        if samples.len() > MAX_SEGMENT {
1173            return Err("encode takes one segment of at most 30 s".into());
1174        }
1175        let ex = Exec::new(pool);
1176        let (x, segs) = self.front(&[samples], &ex);
1177        let t = segs.first().copied().unwrap_or(0);
1178        if t == 0 {
1179            return Ok((Vec::new(), 0));
1180        }
1181        Ok((self.encoder.forward(x, &segs, &ex), t))
1182    }
1183
1184    /// Features and the front end of each segment: `[Σ T, width]` rows and
1185    /// the frame counts (zero for a segment shorter than one window).
1186    fn front(&self, segments: &[&[f32]], ex: &Exec) -> (Vec<f32>, Vec<usize>) {
1187        let n_mel = self.mel.n_mel();
1188        let mut rows = Vec::new();
1189        let mut segs = Vec::with_capacity(segments.len());
1190        for s in segments {
1191            let frames = Mel::frames(s.len());
1192            if frames == 0 {
1193                segs.push(0);
1194                continue;
1195            }
1196            let feats = self.mel.features(s, ex.pool);
1197            let x = self.embed.forward(&feats, frames, n_mel, ex);
1198            debug_assert_eq!(x.len(), Embed::out_frames(frames) * self.encoder.width);
1199            segs.push(Embed::out_frames(frames));
1200            rows.extend_from_slice(&x);
1201        }
1202        (rows, segs)
1203    }
1204
1205    /// Features on the host, the front end and the stacks on the device, a
1206    /// segment at a time: the encoder rows of the batch and its frame counts,
1207    /// with the seconds spent on features and on the device. `None` when the
1208    /// device has no such path (nothing was computed that the host path
1209    /// would not compute again).
1210    fn encode_on_device(&self, segments: &[&[f32]], ex: &Exec) -> Option<(Vec<f32>, Vec<usize>, f64, f64)> {
1211        use std::sync::atomic::Ordering;
1212        if !ex.resident || self.encoder.resident_off.load(Ordering::Relaxed) || self.front_dev_off.load(Ordering::Relaxed) {
1213            return None;
1214        }
1215        let mut args = self.encoder.ga_args(ex.prof);
1216        args.front = Some(self.embed.ga(self.mel.n_mel()));
1217        let w = self.encoder.width;
1218        let (mut rows, mut segs) = (Vec::new(), Vec::with_capacity(segments.len()));
1219        let (mut feat_s, mut enc_s) = (0.0, 0.0);
1220        for s in segments {
1221            let frames = Mel::frames(s.len());
1222            let t = Embed::out_frames(frames);
1223            segs.push(t);
1224            if t == 0 {
1225                continue;
1226            }
1227            let t0 = Instant::now();
1228            let feats = self.mel.features(s, ex.pool);
1229            feat_s += t0.elapsed().as_secs_f64();
1230            let t1 = Instant::now();
1231            let at = rows.len();
1232            rows.resize(at + t * w, 0.0);
1233            if !crate::gpu::gigaam_encode_feats(&args, &feats, frames, &mut rows[at..]) {
1234                self.front_dev_off.store(true, Ordering::Relaxed);
1235                return None;
1236            }
1237            enc_s += t1.elapsed().as_secs_f64();
1238        }
1239        Some((rows, segs, feat_s, enc_s))
1240    }
1241
1242    /// Transcribe mono 16 kHz samples.
1243    pub fn transcribe(&self, samples: &[f32], opts: &Options, pool: Option<&Pool>) -> Result<Output, String> {
1244        let mut out = Output { audio_s: samples.len() as f64 / SR as f64, ..Default::default() };
1245        // where the speech is: the whole clip, or the VAD's segments
1246        let t0 = Instant::now();
1247        let bounds: Vec<(f64, f64)> = if samples.len() <= MAX_SEGMENT && !opts.force_vad {
1248            vec![(0.0, out.audio_s)]
1249        } else {
1250            let vad = self.vad.as_ref().ok_or(
1251                "this recording is longer than 30 s and the file has no voice-activity model to cut it \
1252                 (convert from a checkpoint directory that holds vad.safetensors and vad_config.json)",
1253            )?;
1254            vad.segments(samples, &opts.vad, pool)
1255        };
1256        out.vad_s = t0.elapsed().as_secs_f64();
1257        let clips: Vec<&[f32]> = bounds
1258            .iter()
1259            .map(|&(s, e)| {
1260                let a = ((s * SR as f64).round_ties_even() as usize).min(samples.len());
1261                let b = ((e * SR as f64).round_ties_even() as usize).clamp(a, samples.len());
1262                &samples[a..b]
1263            })
1264            .collect();
1265        let want = |h: Heads| opts.heads == h || opts.heads == Heads::Both;
1266        let mut e2e = want(Heads::E2e).then(Transcript::default);
1267        let mut raw = want(Heads::Raw).then(Transcript::default);
1268        let ex = Exec::new(pool);
1269        let w = self.encoder.width;
1270        let mut i = 0;
1271        while i < clips.len() {
1272            // a batch: segments until the frame budget is spent
1273            let mut j = i;
1274            let mut frames = 0;
1275            while j < clips.len() && (j == i || frames + Embed::out_frames(Mel::frames(clips[j].len())) <= opts.batch_frames) {
1276                frames += Embed::out_frames(Mel::frames(clips[j].len()));
1277                j += 1;
1278            }
1279            let (enc, segs) = match self.encode_on_device(&clips[i..j], &ex) {
1280                Some((enc, segs, feat_s, enc_s)) => {
1281                    out.features_s += feat_s;
1282                    out.encoder_s += enc_s;
1283                    (enc, segs)
1284                }
1285                None => {
1286                    let t1 = Instant::now();
1287                    let (x, segs) = self.front(&clips[i..j], &ex);
1288                    out.features_s += t1.elapsed().as_secs_f64();
1289                    let t2 = Instant::now();
1290                    let live: Vec<usize> = segs.iter().copied().filter(|t| *t > 0).collect();
1291                    let enc = if live.is_empty() { Vec::new() } else { self.encoder.forward(x, &live, &ex) };
1292                    out.encoder_s += t2.elapsed().as_secs_f64();
1293                    (enc, segs)
1294                }
1295            };
1296            let t3 = Instant::now();
1297            // every (segment, head) decodes on its own: spread them over the pool
1298            let mut jobs: Vec<(usize, usize, &decode::Head)> = Vec::new();
1299            let mut row0 = 0;
1300            let mut starts = Vec::with_capacity(segs.len());
1301            for &t in &segs {
1302                starts.push(row0);
1303                row0 += t;
1304            }
1305            for (k, &t) in segs.iter().enumerate() {
1306                if t == 0 {
1307                    continue;
1308                }
1309                if e2e.is_some() {
1310                    jobs.push((k, 0, &self.e2e));
1311                }
1312                if raw.is_some() {
1313                    jobs.push((k, 1, &self.raw));
1314                }
1315            }
1316            let results: Vec<std::sync::Mutex<Option<decode::Decoded>>> = jobs.iter().map(|_| std::sync::Mutex::new(None)).collect();
1317            // one job a worker; inside a job the products are a thread's own (a segment's greedy search is a
1318            // few hundred small products: handing each to the pool costs more than it saves)
1319            ops::par(pool, jobs.len(), 2, &|a, b| {
1320                for q in a..b {
1321                    let (k, _, head) = jobs[q];
1322                    let rows = &enc[starts[k] * w..(starts[k] + segs[k]) * w];
1323                    *results[q].lock().unwrap() = Some(head.decode(rows, segs[k], w, None));
1324                }
1325            });
1326            for (q, (k, which, head)) in jobs.iter().enumerate() {
1327                let d = results[q].lock().unwrap().take().expect("decoded");
1328                let (start, end) = bounds[i + k];
1329                let words = if opts.words {
1330                    let shift = clips[i + k].len() as f64 / SR as f64 / segs[*k] as f64;
1331                    head.words(&d, shift, start)
1332                } else {
1333                    Vec::new()
1334                };
1335                let seg = Segment { start, end, text: head.text(&d.ids), words };
1336                match which {
1337                    0 => e2e.as_mut().unwrap().segments.push(seg),
1338                    _ => raw.as_mut().unwrap().segments.push(seg),
1339                }
1340            }
1341            out.decode_s += t3.elapsed().as_secs_f64();
1342            out.speech_s += clips[i..j].iter().map(|c| c.len() as f64 / SR as f64).sum::<f64>();
1343            i = j;
1344        }
1345        ex.report();
1346        for t in [&mut e2e, &mut raw].into_iter().flatten() {
1347            t.text = t.segments.iter().map(|s| s.text.as_str()).collect::<Vec<_>>().join(" ");
1348        }
1349        out.e2e = e2e;
1350        out.raw = raw;
1351        Ok(out)
1352    }
1353
1354    /// Parity tooling: the front-end rows, every stack's output and the
1355    /// encoder output of one clip of at most 30 s, as `(name, rows, width)`.
1356    pub fn trace(&self, samples: &[f32], pool: Option<&Pool>) -> Result<Vec<(String, Vec<f32>, usize)>, String> {
1357        if samples.len() > MAX_SEGMENT {
1358            return Err("trace takes one segment of at most 30 s".into());
1359        }
1360        let ex = Exec::new(pool);
1361        let frames = Mel::frames(samples.len());
1362        let feats = self.mel.features(samples, pool);
1363        let mut out = vec![("features".to_string(), feats.clone(), self.mel.n_mel())];
1364        let x = self.embed.forward(&feats, frames, self.mel.n_mel(), &ex);
1365        let w = self.encoder.width;
1366        out.push(("frontend".into(), x.clone(), w));
1367        let t = x.len() / w;
1368        let mut cur = x;
1369        for (s, stack) in self.encoder.stacks.iter().enumerate() {
1370            if stack.ds == 1 {
1371                cur = stack.forward(&cur, &[t], &self.encoder.rope, &ex);
1372            } else {
1373                let mut folded = vec![0f32; t.div_ceil(2) * 2 * w];
1374                folded[..t * w].copy_from_slice(&cur);
1375                let y = stack.forward(&folded, &[t.div_ceil(2)], &self.encoder.rope, &ex);
1376                cur = y[..t * w].to_vec();
1377            }
1378            out.push((format!("stack{s}"), cur.clone(), w));
1379        }
1380        let (enc, _) = self.encode(samples, pool)?;
1381        out.push(("encoded".into(), enc, w));
1382        Ok(out)
1383    }
1384}
1385
1386/// Mono 16 kHz samples of an audio file: WAV here, other containers through `ffmpeg`.
1387pub fn read_audio(path: &std::path::Path) -> Result<Vec<f32>, String> {
1388    let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
1389    decode_audio(&bytes).map_err(|e| format!("{}: {e}", path.display()))
1390}
1391
1392/// Mono 16 kHz samples of an audio file's bytes.
1393pub fn decode_audio(bytes: &[u8]) -> Result<Vec<f32>, String> {
1394    match pcm16_mono_16k(bytes) {
1395        Some(samples) => Ok(samples),
1396        None => crate::egemma2_audio::decode_audio(bytes),
1397    }
1398}
1399
1400/// The samples of a plain 16-bit PCM, mono, 16 kHz WAV — the format the
1401/// model takes as it is, read without the general decoder's passes.
1402fn pcm16_mono_16k(b: &[u8]) -> Option<Vec<f32>> {
1403    if b.len() < 44 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" {
1404        return None;
1405    }
1406    let mut plain = false;
1407    let mut i = 12;
1408    while i + 8 <= b.len() {
1409        let len = u32::from_le_bytes(b[i + 4..i + 8].try_into().ok()?) as usize;
1410        let st = i + 8;
1411        match &b[i..i + 4] {
1412            b"fmt " if st + 16 <= b.len() => {
1413                let u16_at = |o: usize| u16::from_le_bytes([b[st + o], b[st + o + 1]]);
1414                let rate = u32::from_le_bytes(b[st + 4..st + 8].try_into().ok()?);
1415                plain = u16_at(0) == 1 && u16_at(2) == 1 && rate as usize == SR && u16_at(14) == 16;
1416            }
1417            b"data" => {
1418                if !plain {
1419                    return None;
1420                }
1421                let end = st.saturating_add(len).min(b.len());
1422                return Some(b[st..end].chunks_exact(2).map(|s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0).collect());
1423            }
1424            _ => {}
1425        }
1426        i = st.saturating_add(len).saturating_add(len & 1);
1427    }
1428    None
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433    use super::*;
1434
1435    #[test]
1436    fn rope_rotates_interleaved_pairs() {
1437        let x: Vec<f32> = (0..QDIM).map(|i| i as f32 + 1.0).collect();
1438        let cos: Vec<f32> = (0..QDIM / 2).map(|i| (0.1 * i as f32).cos()).collect();
1439        let sin: Vec<f32> = (0..QDIM / 2).map(|i| (0.1 * i as f32).sin()).collect();
1440        let mut y = vec![0f32; QDIM];
1441        rotate(&x, &cos, &sin, &mut y);
1442        assert_eq!((y[0], y[1]), (1.0, 2.0));
1443        assert!((y[2] - (3.0 * cos[1] - 4.0 * sin[1])).abs() < 1e-6);
1444        assert!((y[3] - (3.0 * sin[1] + 4.0 * cos[1])).abs() < 1e-6);
1445        // a rotation keeps the pair's length
1446        for i in 0..QDIM / 2 {
1447            let (a, b) = (x[2 * i].hypot(x[2 * i + 1]), y[2 * i].hypot(y[2 * i + 1]));
1448            assert!((a - b).abs() < 1e-4);
1449        }
1450    }
1451
1452    #[test]
1453    fn plain_wav_is_read_directly() {
1454        let mut wav = Vec::new();
1455        let data: Vec<u8> = [0i16, 16384, -32768, 32767].iter().flat_map(|v| v.to_le_bytes()).collect();
1456        wav.extend_from_slice(b"RIFF");
1457        wav.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
1458        wav.extend_from_slice(b"WAVEfmt ");
1459        wav.extend_from_slice(&16u32.to_le_bytes());
1460        for v in [1u16, 1] {
1461            wav.extend_from_slice(&v.to_le_bytes());
1462        }
1463        wav.extend_from_slice(&16000u32.to_le_bytes());
1464        wav.extend_from_slice(&32000u32.to_le_bytes());
1465        for v in [2u16, 16] {
1466            wav.extend_from_slice(&v.to_le_bytes());
1467        }
1468        wav.extend_from_slice(b"data");
1469        wav.extend_from_slice(&(data.len() as u32).to_le_bytes());
1470        wav.extend_from_slice(&data);
1471        assert_eq!(pcm16_mono_16k(&wav).unwrap(), vec![0.0, 0.5, -1.0, 32767.0 / 32768.0]);
1472        // another rate goes to the general decoder
1473        wav[24..28].copy_from_slice(&8000u32.to_le_bytes());
1474        assert!(pcm16_mono_16k(&wav).is_none());
1475        assert!(pcm16_mono_16k(b"not a wav").is_none());
1476    }
1477
1478    #[test]
1479    fn frame_counts_follow_the_front_end() {
1480        assert_eq!(Mel::frames(319), 0);
1481        assert_eq!(Mel::frames(320), 1);
1482        assert_eq!(Mel::frames(71_136), 443);
1483        assert_eq!(Embed::out_frames(443), 111);
1484        assert_eq!(Embed::out_frames(1), 1);
1485        assert_eq!(Embed::out_frames(MAX_SEGMENT / HOP - 1), 750);
1486    }
1487
1488    #[test]
1489    fn host_attention_is_softmax_weighted_values() {
1490        let (heads, t) = (2usize, 5usize);
1491        let fill = |seed: usize| -> Vec<f32> { (0..heads * t * QDIM).map(|i| (((i * 7 + seed * 13) % 23) as f32 - 11.0) * 0.05).collect() };
1492        let (q, k, v) = (fill(1), fill(2), fill(3));
1493        let scale = (QDIM as f32).powf(-0.5);
1494        let mut out = vec![0f32; t * heads * QDIM];
1495        attention_host(&q, &k, &v, heads, t, scale, &mut out, None);
1496        for h in 0..heads {
1497            for i in 0..t {
1498                let qi = &q[(h * t + i) * QDIM..][..QDIM];
1499                let s: Vec<f32> = (0..t).map(|j| scale * qi.iter().zip(&k[(h * t + j) * QDIM..][..QDIM]).map(|(a, b)| a * b).sum::<f32>()).collect();
1500                let m = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1501                let z: f32 = s.iter().map(|x| (x - m).exp()).sum();
1502                for d in 0..QDIM {
1503                    let want: f32 = (0..t).map(|j| (s[j] - m).exp() / z * v[(h * t + j) * QDIM + d]).sum();
1504                    assert!((out[i * heads * QDIM + h * QDIM + d] - want).abs() < 1e-5);
1505                }
1506            }
1507        }
1508    }
1509}