Skip to main content

cortiq_engine/
qwen3_tts.rs

1//! Qwen3-TTS 12 Hz (CustomVoice): text to 24 kHz speech.
2//!
3//! The talker is a Qwen3 decoder over the codec vocabulary — the file's
4//! language model, driven row by row through `Pipeline::speech_*`. Its
5//! prompt is built from the text embedding and its projection
6//! (`qtts.text_*`), the codec's control codes and the speaker's code; each
7//! step samples the first codebook of a 12.5 Hz frame from the codec head.
8//! The code predictor, a five-layer Qwen3 over the frame's sixteen slots
9//! (`qtts.code_predictor.*`), samples the other fifteen; the frame's sixteen
10//! code embeddings, summed with the text pad, are the next step's input. The
11//! speech tokenizer's decoder (`qtts.codec.decoder.*`) turns the frames into
12//! audio: RVQ, a causal convolution, an eight-layer sliding-window
13//! transformer, two ConvNeXt upsamplings and a SnakeBeta vocoder, 1920
14//! samples a frame. Everything past the talker runs in f32 on the host.
15//!
16//! The prompt and the sampling follow `qwen_tts` 0.1.1
17//! (`Qwen3TTSForConditionalGeneration.generate`, non-streaming text, the
18//! release's `generation_config.json`).
19
20use crate::inference::{gelu_erf, silu};
21use crate::pipeline::Pipeline;
22use crate::pool::Pool;
23use crate::sampler::SplitMix64;
24use cortiq_core::CmfModel;
25use serde_json::Value;
26use std::sync::Arc;
27
28/// Samples a frame decodes to at 24 kHz.
29pub const FRAME_SAMPLES: usize = 1920;
30
31/// Stage clocks of `CMF_QTTS_PROF=1` (microseconds): the code predictor's
32/// prefill, steps and heads; the decoder's RVQ + causal conv, transformer,
33/// upsampling, vocoder input, its four blocks and the output.
34static PROF: [std::sync::atomic::AtomicU64; 12] = [const { std::sync::atomic::AtomicU64::new(0) }; 12];
35const PROF_NAMES: [&str; 12] =
36    ["cp prefill", "cp steps", "cp heads", "rvq+conv", "transformer", "upsample", "conv in", "block 1", "block 2", "block 3", "block 4", "out"];
37
38fn prof_on() -> bool {
39    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
40    *ON.get_or_init(|| std::env::var_os("CMF_QTTS_PROF").is_some())
41}
42
43fn prof(slot: usize, t: std::time::Instant) {
44    if prof_on() {
45        PROF[slot].fetch_add(t.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
46    }
47}
48
49/// The stage clocks, one line, `CMF_QTTS_PROF=1` only.
50pub fn prof_report() -> Option<String> {
51    prof_on().then(|| {
52        PROF_NAMES
53            .iter()
54            .zip(&PROF)
55            .map(|(n, a)| format!("{n} {:.0} ms", a.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e3))
56            .collect::<Vec<_>>()
57            .join(" · ")
58    })
59}
60
61/// `f(lo, hi)` over `rows`, split across the pool when there is one.
62pub(crate) fn par_rows(pool: Option<&Pool>, rows: usize, f: &(dyn Fn(usize, usize) + Sync)) {
63    match pool {
64        Some(p) if rows > 1 => p.run_rows(rows, f),
65        _ => f(0, rows),
66    }
67}
68/// Output sample rate.
69pub const SAMPLE_RATE: u32 = 24_000;
70
71/// Whether the file is a Qwen3-TTS conversion.
72pub fn is_qwen3_tts(model: &CmfModel) -> bool {
73    model.header.provenance.as_ref().is_some_and(|p| p.get("qwen3_tts").is_some())
74}
75
76fn ju(v: &Value, k: &str) -> Result<usize, String> {
77    v.get(k).and_then(|x| x.as_u64()).map(|x| x as usize).ok_or_else(|| format!("qwen3_tts: config lacks {k}"))
78}
79
80fn jf(v: &Value, k: &str, d: f64) -> f64 {
81    v.get(k).and_then(|x| x.as_f64()).unwrap_or(d)
82}
83
84/// The sampling of one level (the talker's first codebook, or the code
85/// predictor's fifteen).
86#[derive(Clone, Copy, Debug)]
87pub struct Sampling {
88    pub do_sample: bool,
89    pub temperature: f32,
90    pub top_k: usize,
91    pub top_p: f32,
92}
93
94/// What `generate` needs from the file's `provenance.qwen3_tts`.
95#[derive(Clone, Debug)]
96pub struct Qwen3TtsConfig {
97    pub tts_bos: u32,
98    pub tts_eos: u32,
99    pub tts_pad: u32,
100    pub codec_bos: u32,
101    pub codec_eos: u32,
102    pub codec_pad: u32,
103    pub think: u32,
104    pub nothink: u32,
105    pub think_bos: u32,
106    pub think_eos: u32,
107    /// `(name, codec id)`, lowercase.
108    pub languages: Vec<(String, u32)>,
109    /// `(name, codec id, dialect)`, lowercase.
110    pub speakers: Vec<(String, u32, Option<String>)>,
111    pub hidden: usize,
112    pub text_hidden: usize,
113    pub groups: usize,
114    pub vocab: usize,
115    pub talker: Sampling,
116    pub sub: Sampling,
117    pub repetition_penalty: f32,
118    pub max_frames: usize,
119    cp: Value,
120    codec: Value,
121}
122
123impl Qwen3TtsConfig {
124    pub fn from_model(model: &CmfModel) -> Result<Self, String> {
125        let p = model
126            .header
127            .provenance
128            .as_ref()
129            .and_then(|p| p.get("qwen3_tts"))
130            .ok_or("qwen3_tts: the file has no provenance.qwen3_tts")?;
131        let cfg = p.get("config").ok_or("qwen3_tts: provenance has no config")?;
132        let tc = cfg.get("talker_config").ok_or("qwen3_tts: config has no talker_config")?;
133        let gcfg = p.get("generation").cloned().unwrap_or(Value::Null);
134        let id = |v: &Value, k: &str| ju(v, k).map(|x| x as u32);
135        let mut languages: Vec<(String, u32)> = tc
136            .get("codec_language_id")
137            .and_then(|m| m.as_object())
138            .map(|m| m.iter().filter_map(|(k, v)| Some((k.to_lowercase(), v.as_u64()? as u32))).collect())
139            .unwrap_or_default();
140        languages.sort();
141        let dialects = tc.get("spk_is_dialect").and_then(|m| m.as_object());
142        let mut speakers: Vec<(String, u32, Option<String>)> = tc
143            .get("spk_id")
144            .and_then(|m| m.as_object())
145            .map(|m| {
146                m.iter()
147                    .filter_map(|(k, v)| {
148                        let d = dialects.and_then(|d| d.get(k)).and_then(|d| d.as_str()).map(|s| s.to_lowercase());
149                        Some((k.to_lowercase(), v.as_u64()? as u32, d))
150                    })
151                    .collect()
152            })
153            .unwrap_or_default();
154        speakers.sort();
155        let samp = |pre: &str| Sampling {
156            do_sample: gcfg.get(&format!("{pre}dosample")).or_else(|| gcfg.get(&format!("{pre}do_sample"))).and_then(|v| v.as_bool()).unwrap_or(true),
157            temperature: jf(&gcfg, &format!("{pre}temperature"), 0.9) as f32,
158            top_k: jf(&gcfg, &format!("{pre}top_k"), 50.0) as usize,
159            top_p: jf(&gcfg, &format!("{pre}top_p"), 1.0) as f32,
160        };
161        Ok(Self {
162            tts_bos: id(cfg, "tts_bos_token_id")?,
163            tts_eos: id(cfg, "tts_eos_token_id")?,
164            tts_pad: id(cfg, "tts_pad_token_id")?,
165            codec_bos: id(tc, "codec_bos_id")?,
166            codec_eos: id(tc, "codec_eos_token_id")?,
167            codec_pad: id(tc, "codec_pad_id")?,
168            think: id(tc, "codec_think_id")?,
169            nothink: id(tc, "codec_nothink_id")?,
170            think_bos: id(tc, "codec_think_bos_id")?,
171            think_eos: id(tc, "codec_think_eos_id")?,
172            languages,
173            speakers,
174            hidden: ju(tc, "hidden_size")?,
175            text_hidden: ju(tc, "text_hidden_size")?,
176            groups: ju(tc, "num_code_groups")?,
177            vocab: ju(tc, "vocab_size")?,
178            talker: Sampling { do_sample: gcfg.get("do_sample").and_then(|v| v.as_bool()).unwrap_or(true), ..samp("") },
179            sub: samp("subtalker_"),
180            repetition_penalty: jf(&gcfg, "repetition_penalty", 1.05) as f32,
181            max_frames: jf(&gcfg, "max_new_tokens", 8192.0) as usize,
182            cp: tc.get("code_predictor_config").cloned().ok_or("qwen3_tts: no code_predictor_config")?,
183            codec: p.get("codec").and_then(|c| c.get("decoder_config")).cloned().ok_or("qwen3_tts: no speech tokenizer decoder_config")?,
184        })
185    }
186
187    pub fn speaker_names(&self) -> Vec<&str> {
188        self.speakers.iter().map(|s| s.0.as_str()).collect()
189    }
190
191    pub fn language_names(&self) -> Vec<&str> {
192        self.languages.iter().map(|s| s.0.as_str()).collect()
193    }
194}
195
196// ───────────────────────────── weights ─────────────────────────────
197
198/// A matrix in f32 for the host GEMM: `y[n, rows] = x[n, cols] · Wᵀ (+ b)`.
199pub(crate) struct Lin {
200    w: Vec<f32>,
201    b: Option<Vec<f32>>,
202    rows: usize,
203    cols: usize,
204}
205
206impl Lin {
207    pub(crate) fn load(model: &CmfModel, name: &str, rows: usize, cols: usize, bias: bool) -> Result<Self, String> {
208        let w = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
209        if w.len() != rows * cols {
210            return Err(format!("{name}.weight: {} values, expected [{rows}, {cols}]", w.len()));
211        }
212        let b = if bias { Some(vec_n(model, &format!("{name}.bias"), rows)?) } else { None };
213        Ok(Self { w, b, rows, cols })
214    }
215
216    pub(crate) fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
217        let mut y = vec![0f32; n * self.rows];
218        crate::fcd_ops::gemm_nt(x, &self.w, &mut y, n, self.cols, self.rows, pool);
219        if let Some(b) = &self.b {
220            for r in y.chunks_mut(self.rows) {
221                for (v, &bb) in r.iter_mut().zip(b) {
222                    *v += bb;
223                }
224            }
225        }
226        y
227    }
228}
229
230pub(crate) fn vec_n(model: &CmfModel, name: &str, n: usize) -> Result<Vec<f32>, String> {
231    let v = crate::dit::cmf_f32(model, name)?;
232    if v.len() != n {
233        return Err(format!("{name}: {} values, expected {n}", v.len()));
234    }
235    Ok(v)
236}
237
238pub(crate) fn rms(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
239    let ms = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
240    let r = 1.0 / (ms + eps as f64).sqrt();
241    x.iter().zip(w).map(|(&v, &g)| (v as f64 * r) as f32 * g).collect()
242}
243
244/// RoPE (`rotate_half`) on one head of `hd` at `pos`.
245fn rope(x: &mut [f32], pos: usize, theta: f64) {
246    let half = x.len() / 2;
247    let hd = x.len() as f64;
248    for j in 0..half {
249        let inv = 1.0 / theta.powf(2.0 * j as f64 / hd);
250        let (s, c) = (pos as f64 * inv as f32 as f64).sin_cos();
251        let (a, b) = (x[j] as f64, x[j + half] as f64);
252        x[j] = (a * c - b * s) as f32;
253        x[j + half] = (b * c + a * s) as f32;
254    }
255}
256
257// ───────────────────────────── text side ─────────────────────────────
258
259/// The talker's text input: the text embedding row of a token through the
260/// text projection (`fc2(silu(fc1(e) + b1)) + b2`).
261struct TextIn {
262    model: Arc<CmfModel>,
263    emb: usize,
264    width: usize,
265    fc1: Lin,
266    fc2: Lin,
267}
268
269impl TextIn {
270    fn load(model: &Arc<CmfModel>, c: &Qwen3TtsConfig) -> Result<Self, String> {
271        let name = "qtts.text_embedding.weight";
272        let emb = model.tensor_index(name).ok_or("qwen3_tts: no qtts.text_embedding.weight")?;
273        let e = &model.tensors[emb];
274        if e.shape.len() != 2 || e.shape[1] != c.text_hidden {
275            return Err(format!("{name}: shape {:?}", e.shape));
276        }
277        Ok(Self {
278            model: model.clone(),
279            emb,
280            width: c.text_hidden,
281            fc1: Lin::load(model, "qtts.text_projection.linear_fc1", c.text_hidden, c.text_hidden, true)?,
282            fc2: Lin::load(model, "qtts.text_projection.linear_fc2", c.hidden, c.text_hidden, true)?,
283        })
284    }
285
286    fn embed_row(&self, id: u32) -> Result<Vec<f32>, String> {
287        let e = &self.model.tensors[self.emb];
288        let rows = e.shape[0];
289        if id as usize >= rows {
290            return Err(format!("qwen3_tts: text token {id} past the embedding's {rows} rows"));
291        }
292        let bytes = self.model.entry_bytes(e);
293        let w = self.width;
294        match e.dtype {
295            cortiq_core::TensorDtype::F16 => {
296                let r = &bytes[id as usize * w * 2..(id as usize + 1) * w * 2];
297                Ok(r.chunks_exact(2).map(|b| cortiq_core::quant::f16_to_f32(u16::from_le_bytes([b[0], b[1]]))).collect())
298            }
299            cortiq_core::TensorDtype::F32 => {
300                let r = &bytes[id as usize * w * 4..(id as usize + 1) * w * 4];
301                Ok(r.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
302            }
303            d => Err(format!("qwen3_tts: text embedding stored as {d:?}, expected F16 or F32")),
304        }
305    }
306
307    /// The projected rows of `ids`, `[n][hidden]`.
308    fn rows(&self, ids: &[u32], pool: Option<&Pool>) -> Result<Vec<f32>, String> {
309        let mut e = Vec::with_capacity(ids.len() * self.width);
310        for &id in ids {
311            e.extend(self.embed_row(id)?);
312        }
313        let mut h = self.fc1.apply(&e, ids.len(), pool);
314        for v in &mut h {
315            *v = silu(*v);
316        }
317        Ok(self.fc2.apply(&h, ids.len(), pool))
318    }
319}
320
321// ───────────────────────────── code predictor ─────────────────────────────
322
323/// The code predictor: a Qwen3 decoder over a frame's slots
324/// `[talker hidden, code 0, code 1 …]`, each step one more code. Its layers
325/// run as a pipeline of their own — the file opened again as a five-layer
326/// Qwen3 (`CmfModel::open_view`) — so they reach the same device graphs as
327/// the talker; its per-codebook embeddings and heads stay on the host.
328pub struct CodePredictor {
329    pipe: Pipeline,
330    /// A frame ran: the next ones rewind the sequence instead of resetting it.
331    warm: bool,
332    /// `[group - 1]`: the embedding of codebook g (1..groups).
333    emb: Vec<Vec<f32>>,
334    /// `[group - 1]`: the head that predicts codebook g.
335    heads: Vec<Lin>,
336    hidden: usize,
337    vocab: usize,
338    pool: Option<Arc<Pool>>,
339}
340
341impl CodePredictor {
342    pub fn from_model(model: &CmfModel, c: &Qwen3TtsConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
343        let cp = &c.cp;
344        let (hidden, nl, nh, nkv, hd, ffn, vocab) = (
345            ju(cp, "hidden_size")?,
346            ju(cp, "num_hidden_layers")?,
347            ju(cp, "num_attention_heads")?,
348            ju(cp, "num_key_value_heads")?,
349            ju(cp, "head_dim")?,
350            ju(cp, "intermediate_size")?,
351            ju(cp, "vocab_size")?,
352        );
353        if hidden != c.hidden {
354            return Err("qwen3_tts: a code predictor of another width (small_to_mtp_projection) is not supported".into());
355        }
356        let mut arch = model.header.arch.clone();
357        if (arch.num_attention_heads, arch.num_kv_heads, arch.head_dim) != (nh, nkv, hd) {
358            return Err("qwen3_tts: the code predictor's heads differ from the talker's".into());
359        }
360        arch.num_layers = nl;
361        arch.layer_types.truncate(nl);
362        arch.intermediate_size = ffn;
363        arch.vocab_size = vocab;
364        let p = "qtts.code_predictor.";
365        let rename = |n: &str| -> Option<String> {
366            let r = n.strip_prefix(p)?;
367            if let Some(l) = r.strip_prefix("model.layers.") {
368                return Some(format!("model.layers.{l}"));
369            }
370            match r {
371                "model.norm.weight" => Some("model.norm.weight".into()),
372                // the pipeline wants an embedding and a head; rows come in
373                // as embeddings and each step reads its own head below
374                "model.codec_embedding.0.weight" => Some("model.embed_tokens.weight".into()),
375                "lm_head.0.weight" => Some("lm_head.weight".into()),
376                _ => None,
377            }
378        };
379        let view = CmfModel::open_view(&model.path, &rename, arch).map_err(|e| format!("qwen3_tts: code predictor view: {e}"))?;
380        let pipe = Pipeline::from_model(&Arc::new(view), crate::SamplerConfig::default()).map_err(|e| format!("qwen3_tts: code predictor: {e}"))?;
381        let g = c.groups - 1;
382        let mut emb = Vec::with_capacity(g);
383        let mut heads = Vec::with_capacity(g);
384        for i in 0..g {
385            let e = crate::dit::cmf_f32(model, &format!("{p}model.codec_embedding.{i}.weight"))?;
386            if e.len() != vocab * hidden {
387                return Err(format!("{p}model.codec_embedding.{i}: {} values", e.len()));
388            }
389            emb.push(e);
390            heads.push(Lin::load(model, &format!("{p}lm_head.{i}"), vocab, hidden, false)?);
391        }
392        Ok(Self { pipe, warm: false, emb, heads, hidden, vocab, pool })
393    }
394
395    /// Codebook `g`'s embedding row of `code` (g in 1..groups).
396    pub fn code_row(&self, g: usize, code: u32) -> &[f32] {
397        let e = &self.emb[g - 1];
398        &e[code as usize * self.hidden..(code as usize + 1) * self.hidden]
399    }
400
401    /// The other codebooks of a frame: `talker_h` (the talker's
402    /// final-normed state) and `code0_row` (the talker's embedding of the
403    /// first code) are the prefix; each step reads its own head.
404    pub fn frame(&mut self, talker_h: &[f32], code0_row: &[f32], s: &Sampling, rng: &mut SplitMix64) -> Result<Vec<u32>, String> {
405        let g = self.heads.len();
406        let t = std::time::Instant::now();
407        // the first frame sets the sequence up; later ones rewind it (a full
408        // reset frees and rebuilds the device mirrors, 20-40 ms a frame)
409        let rewind = std::env::var("CMF_QTTS_REWIND").as_deref() != Ok("0");
410        let mut h = if self.warm && rewind && self.pipe.speech_rewind() {
411            self.pipe.speech_step(talker_h, 0);
412            self.pipe.speech_step(code0_row, 1)
413        } else {
414            self.warm = true;
415            let rows = [talker_h, code0_row].concat();
416            self.pipe.speech_prefill(&[0, 0], Some(&rows))?
417        };
418        prof(0, t);
419        let mut codes = Vec::with_capacity(g);
420        for gi in 0..g {
421            let t = std::time::Instant::now();
422            let logits = self.heads[gi].apply(&h, 1, self.pool.as_deref());
423            let code = sample(&logits, s, None, 1.0, &[], rng);
424            prof(2, t);
425            debug_assert!((code as usize) < self.vocab);
426            codes.push(code);
427            if gi + 1 == g {
428                break;
429            }
430            let row = self.code_row(gi + 1, code).to_vec();
431            let t = std::time::Instant::now();
432            h = self.pipe.speech_step(&row, 2 + gi);
433            prof(1, t);
434        }
435        Ok(codes)
436    }
437}
438
439// ───────────────────────────── sampling ─────────────────────────────
440
441/// HF's processors in their order: repetition penalty over `seen`,
442/// suppressed ids, temperature, top-k, top-p; then a draw (or the argmax).
443fn sample(logits: &[f32], s: &Sampling, suppress: Option<&dyn Fn(usize) -> bool>, rep: f32, seen: &[u32], rng: &mut SplitMix64) -> u32 {
444    let mut l: Vec<f32> = logits.to_vec();
445    if rep != 1.0 {
446        let mut done = std::collections::HashSet::new();
447        for &t in seen {
448            if done.insert(t) {
449                let v = &mut l[t as usize];
450                *v = if *v < 0.0 { *v * rep } else { *v / rep };
451            }
452        }
453    }
454    if let Some(f) = suppress {
455        for (i, v) in l.iter_mut().enumerate() {
456            if f(i) {
457                *v = f32::NEG_INFINITY;
458            }
459        }
460    }
461    if !s.do_sample || s.temperature <= 0.0 {
462        return l.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, &v)| if v > b.1 { (i, v) } else { b }).0 as u32;
463    }
464    for v in &mut l {
465        *v /= s.temperature;
466    }
467    let mut idx: Vec<usize> = (0..l.len()).filter(|&i| l[i].is_finite()).collect();
468    idx.sort_by(|&a, &b| l[b].total_cmp(&l[a]));
469    if s.top_k > 0 && s.top_k < idx.len() {
470        idx.truncate(s.top_k);
471    }
472    let mx = l[idx[0]];
473    let mut w: Vec<f64> = idx.iter().map(|&i| ((l[i] - mx) as f64).exp()).collect();
474    let total: f64 = w.iter().sum();
475    if s.top_p < 1.0 {
476        let mut cum = 0.0;
477        let mut keep = w.len();
478        for (j, &wi) in w.iter().enumerate() {
479            cum += wi / total;
480            if cum >= s.top_p as f64 {
481                keep = j + 1;
482                break;
483            }
484        }
485        w.truncate(keep);
486        idx.truncate(keep);
487    }
488    let total: f64 = w.iter().sum();
489    let mut r = rng.next_f32() as f64 * total;
490    for (&i, &wi) in idx.iter().zip(&w) {
491        r -= wi;
492        if r <= 0.0 {
493            return i as u32;
494        }
495    }
496    *idx.last().unwrap() as u32
497}
498
499// ───────────────────────────── generation ─────────────────────────────
500
501/// What to say and how.
502pub struct Request<'a> {
503    pub text: &'a str,
504    /// A language name (`russian`, `english` …) or `auto`.
505    pub language: &'a str,
506    /// A built-in speaker name (`serena` …), or empty for none.
507    pub speaker: &'a str,
508    pub seed: u64,
509    /// At most this many frames (12.5 a second).
510    pub max_frames: Option<usize>,
511    /// `Some`: the talker and the code predictor at these temperatures
512    /// (0 = greedy) instead of the release's.
513    pub temperature: Option<f32>,
514}
515
516/// The frames `[n][groups]` of an utterance.
517pub struct Speech {
518    pub frames: Vec<Vec<u32>>,
519}
520
521/// Map a user language (`ru`, `Russian`, `русский`…) to the file's names.
522pub fn language_name(cfg: &Qwen3TtsConfig, lang: &str) -> Option<String> {
523    let l = lang.trim().to_lowercase();
524    if l == "auto" || l.is_empty() {
525        return Some("auto".into());
526    }
527    let alias = match l.as_str() {
528        "zh" | "cn" => "chinese",
529        "en" => "english",
530        "de" => "german",
531        "it" => "italian",
532        "pt" => "portuguese",
533        "es" => "spanish",
534        "ja" | "jp" => "japanese",
535        "ko" | "kr" => "korean",
536        "fr" => "french",
537        "ru" | "русский" => "russian",
538        other => other,
539    };
540    cfg.languages.iter().any(|(n, _)| n == alias).then(|| alias.to_string())
541}
542
543/// Generate the frames of `req.text` with the talker `pipeline` and the
544/// code predictor `cp`.
545pub fn generate(
546    pipeline: &mut Pipeline,
547    cfg: &Qwen3TtsConfig,
548    model: &Arc<CmfModel>,
549    cp: &mut CodePredictor,
550    req: &Request<'_>,
551    pool: Option<&Pool>,
552) -> Result<Speech, String> {
553    let text_in = TextIn::load(model, cfg)?;
554    let hs = cfg.hidden;
555    if pipeline.hidden_size != hs {
556        return Err(format!("qwen3_tts: talker width {} against the config's {hs}", pipeline.hidden_size));
557    }
558    // the assistant turn of the text (qwen_tts `_build_assistant_text`)
559    let ids = pipeline.tokenizer.encode(&format!("<|im_start|>assistant\n{}<|im_end|>\n<|im_start|>assistant\n", req.text));
560    if ids.len() < 9 {
561        return Err("qwen3_tts: empty text".into());
562    }
563    let (role, text) = (&ids[..3], &ids[3..ids.len() - 5]);
564    let lang = language_name(cfg, req.language).ok_or_else(|| {
565        format!("qwen3_tts: language {:?} is not one of auto, {}", req.language, cfg.language_names().join(", "))
566    })?;
567    let spk = req.speaker.trim().to_lowercase();
568    let speaker = if spk.is_empty() {
569        None
570    } else {
571        Some(cfg.speakers.iter().find(|s| s.0 == spk).ok_or_else(|| {
572            format!("qwen3_tts: speaker {:?} is not one of {}", req.speaker, cfg.speaker_names().join(", "))
573        })?)
574    };
575    // a dialect speaker speaks its dialect when the language is Chinese or auto
576    let mut lang_id = cfg.languages.iter().find(|l| l.0 == lang).map(|l| l.1);
577    if let Some((_, _, Some(d))) = speaker {
578        if lang == "chinese" || lang == "auto" {
579            lang_id = cfg.languages.iter().find(|l| &l.0 == d).map(|l| l.1);
580        }
581    }
582    let mut codec: Vec<u32> = match lang_id {
583        None => vec![cfg.nothink, cfg.think_bos, cfg.think_eos],
584        Some(l) => vec![cfg.think, cfg.think_bos, l, cfg.think_eos],
585    };
586    if let Some(s) = speaker {
587        codec.push(s.1);
588    }
589    codec.extend([cfg.codec_pad, cfg.codec_bos]);
590    let specials = text_in.rows(&[cfg.tts_bos, cfg.tts_eos, cfg.tts_pad], pool)?;
591    let (tts_bos, tts_eos, tts_pad) = (&specials[..hs], &specials[hs..2 * hs], &specials[2 * hs..]);
592    let add = |a: &[f32], b: &[f32]| -> Vec<f32> { a.iter().zip(b).map(|(x, y)| x + y).collect() };
593    let mut rows = text_in.rows(role, pool)?;
594    // tts_pad × (len - 2), tts_bos over the codec's control codes but its last
595    for (j, &c) in codec[..codec.len() - 1].iter().enumerate() {
596        let t = if j + 2 < codec.len() { tts_pad } else { tts_bos };
597        rows.extend(add(t, &pipeline.embed_id(c)));
598    }
599    // non-streaming: the whole text over codec pads, the text's end, then the codec's bos
600    let pad_row = pipeline.embed_id(cfg.codec_pad);
601    let text_rows = text_in.rows(text, pool)?;
602    for r in text_rows.chunks(hs) {
603        rows.extend(add(r, &pad_row));
604    }
605    rows.extend(add(tts_eos, &pad_row));
606    rows.extend(add(tts_pad, &pipeline.embed_id(cfg.codec_bos)));
607    let n = rows.len() / hs;
608    let dummy = vec![0u32; n];
609    let mut h = pipeline.speech_prefill(&dummy, Some(&rows))?;
610    let mut pos = n;
611
612    let mut rng = SplitMix64::new(req.seed);
613    let (mut talk, mut sub) = (cfg.talker, cfg.sub);
614    if let Some(t) = req.temperature {
615        for s in [&mut talk, &mut sub] {
616            s.temperature = t;
617            s.do_sample = t > 0.0;
618        }
619    }
620    // the release's 8192 frames is eleven minutes: an utterance that never
621    // samples its end stops after 6 s plus 0.64 s a text token instead
622    let max = req.max_frames.unwrap_or_else(|| cfg.max_frames.min(75 + 8 * text.len()));
623    let (vocab, eos) = (cfg.vocab, cfg.codec_eos as usize);
624    let mut seen: Vec<u32> = Vec::new();
625    let mut frames = Vec::new();
626    let prof = std::env::var_os("CMF_QTTS_PROF").is_some();
627    let (mut t_cp, mut t_lm) = (0f64, 0f64);
628    for step in 0..max {
629        let logits = pipeline.speech_logits(&h);
630        // the codec's control range is never sampled, its end only after two frames
631        let sup = |i: usize| (i >= vocab - 1024 && i != eos) || (i == eos && step < 2);
632        let code0 = sample(&logits[..vocab.min(logits.len())], &talk, Some(&sup), cfg.repetition_penalty, &seen, &mut rng);
633        if code0 as usize == eos {
634            break;
635        }
636        seen.push(code0);
637        let e0 = pipeline.embed_id(code0);
638        let t0 = std::time::Instant::now();
639        let rest = cp.frame(&h, &e0, &sub, &mut rng)?;
640        t_cp += t0.elapsed().as_secs_f64();
641        let mut row = e0.clone();
642        for (g, &c) in rest.iter().enumerate() {
643            for (a, b) in row.iter_mut().zip(cp.code_row(g + 1, c)) {
644                *a += b;
645            }
646        }
647        for (a, b) in row.iter_mut().zip(tts_pad) {
648            *a += b;
649        }
650        let mut f = Vec::with_capacity(cfg.groups);
651        f.push(code0);
652        f.extend(rest);
653        frames.push(f);
654        let t1 = std::time::Instant::now();
655        h = pipeline.speech_step(&row, pos);
656        t_lm += t1.elapsed().as_secs_f64();
657        pos += 1;
658    }
659    if prof {
660        eprintln!("qwen3-tts: {} frames | code predictor {:.0} ms, talker {:.0} ms", frames.len(), t_cp * 1e3, t_lm * 1e3);
661    }
662    Ok(Speech { frames })
663}
664
665// ───────────────────────────── codec ─────────────────────────────
666
667/// `[Cout][K][Cin]` taps (from the source `[Cout][Cin][K]`) of a causal
668/// convolution: left padding `(K-1)·dil`, stride 1.
669struct Conv {
670    w: Vec<f32>,
671    b: Vec<f32>,
672    cin: usize,
673    cout: usize,
674    k: usize,
675    dil: usize,
676}
677
678impl Conv {
679    fn load(model: &CmfModel, name: &str, cin: usize, cout: usize, k: usize, dil: usize, bias: bool) -> Result<Self, String> {
680        let src = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
681        if src.len() != cout * cin * k {
682            return Err(format!("{name}.weight: {} values, expected [{cout}, {cin}, {k}]", src.len()));
683        }
684        let mut w = vec![0f32; src.len()];
685        for o in 0..cout {
686            for i in 0..cin {
687                for t in 0..k {
688                    w[(o * k + t) * cin + i] = src[(o * cin + i) * k + t];
689                }
690            }
691        }
692        let b = if bias { vec_n(model, &format!("{name}.bias"), cout)? } else { vec![0f32; cout] };
693        Ok(Self { w, b, cin, cout, k, dil })
694    }
695
696    /// `x` `[T][cin]` → `[T][cout]`.
697    fn apply(&self, x: &[f32], t: usize, pool: Option<&Pool>) -> Vec<f32> {
698        let (cin, k, dil) = (self.cin, self.k, self.dil);
699        let pad = (k - 1) * dil;
700        let mut y = vec![0f32; t * self.cout];
701        // im2col a block of rows at a time
702        let block = (1usize << 22) / (k * cin).max(1);
703        let block = block.clamp(1, t.max(1));
704        let mut col = vec![0f32; block * k * cin];
705        let mut t0 = 0;
706        while t0 < t {
707            let nb = block.min(t - t0);
708            let cp = SendMut(col.as_mut_ptr());
709            par_rows(pool, nb, &|lo, hi| {
710                for r in lo..hi {
711                    let tt = t0 + r;
712                    for j in 0..k {
713                        let src = tt as isize + (j * dil) as isize - pad as isize;
714                        // SAFETY: row r of `col` belongs to this worker alone
715                        let dst = unsafe { std::slice::from_raw_parts_mut(cp.get().add((r * k + j) * cin), cin) };
716                        if src < 0 {
717                            dst.fill(0.0);
718                        } else {
719                            dst.copy_from_slice(&x[src as usize * cin..(src as usize + 1) * cin]);
720                        }
721                    }
722                }
723            });
724            crate::fcd_ops::gemm_nt(&col[..nb * k * cin], &self.w, &mut y[t0 * self.cout..(t0 + nb) * self.cout], nb, k * cin, self.cout, pool);
725            t0 += nb;
726        }
727        let (cout, b) = (self.cout, &self.b);
728        let yp = SendMut(y.as_mut_ptr());
729        par_rows(pool, t, &|lo, hi| {
730            // SAFETY: rows lo..hi of `y` belong to this worker alone
731            let rows = unsafe { std::slice::from_raw_parts_mut(yp.get().add(lo * cout), (hi - lo) * cout) };
732            for r in rows.chunks_mut(cout) {
733                for (v, &bb) in r.iter_mut().zip(b) {
734                    *v += bb;
735                }
736            }
737        });
738        y
739    }
740}
741
742/// A transposed convolution of kernel `2s`, stride `s`, the right `k - s`
743/// samples cut (`Qwen3TTSTokenizerV2CausalTransConvNet`): `[T][cin]` →
744/// `[T·s][cout]`.
745struct ConvT {
746    /// `[cout·k][cin]` (rows `(o, j)`), from the source `[cin][cout][k]`.
747    w: Vec<f32>,
748    b: Vec<f32>,
749    cin: usize,
750    cout: usize,
751    k: usize,
752    s: usize,
753}
754
755impl ConvT {
756    fn load(model: &CmfModel, name: &str, cin: usize, cout: usize, k: usize, s: usize) -> Result<Self, String> {
757        let src = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
758        if src.len() != cin * cout * k {
759            return Err(format!("{name}.weight: {} values, expected [{cin}, {cout}, {k}]", src.len()));
760        }
761        let mut w = vec![0f32; src.len()];
762        for i in 0..cin {
763            for o in 0..cout {
764                for j in 0..k {
765                    w[(o * k + j) * cin + i] = src[(i * cout + o) * k + j];
766                }
767            }
768        }
769        Ok(Self { w, b: vec_n(model, &format!("{name}.bias"), cout)?, cin, cout, k, s })
770    }
771
772    fn apply(&self, x: &[f32], t: usize, pool: Option<&Pool>) -> Vec<f32> {
773        let (cout, k, s) = (self.cout, self.k, self.s);
774        let full = (t - 1) * s + k;
775        let keep = full - (k - s);
776        let mut y = vec![0f32; keep * cout];
777        let block = ((1usize << 22) / (cout * k)).clamp(1, t.max(1));
778        let mut part = vec![0f32; block * cout * k];
779        let mut t0 = 0;
780        while t0 < t {
781            let nb = block.min(t - t0);
782            crate::fcd_ops::gemm_nt(&x[t0 * self.cin..(t0 + nb) * self.cin], &self.w, &mut part[..nb * cout * k], nb, self.cin, cout * k, pool);
783            let (yp, part) = (SendMut(y.as_mut_ptr()), &part);
784            // output channels split across workers: the overlapping taps of
785            // neighbouring input rows land in one worker's columns
786            par_rows(pool, cout, &|o0, o1| {
787                for r in 0..nb {
788                    let tt = t0 + r;
789                    for o in o0..o1 {
790                        for j in 0..k {
791                            let at = tt * s + j;
792                            if at < keep {
793                                // SAFETY: column o of `y` belongs to this worker alone
794                                unsafe { *yp.get().add(at * cout + o) += part[(r * cout + o) * k + j] };
795                            }
796                        }
797                    }
798                }
799            });
800            t0 += nb;
801        }
802        let (b, yp) = (&self.b, SendMut(y.as_mut_ptr()));
803        par_rows(pool, keep, &|lo, hi| {
804            // SAFETY: rows lo..hi of `y` belong to this worker alone
805            let rows = unsafe { std::slice::from_raw_parts_mut(yp.get().add(lo * cout), (hi - lo) * cout) };
806            for r in rows.chunks_mut(cout) {
807                for (v, &bb) in r.iter_mut().zip(b) {
808                    *v += bb;
809                }
810            }
811        });
812        y
813    }
814}
815
816/// SnakeBeta with its parameters stored as logs: `x + sin²(x·e^α) / (e^β + 1e-9)`.
817struct Snake {
818    a: Vec<f32>,
819    inv_b: Vec<f32>,
820}
821
822impl Snake {
823    fn load(model: &CmfModel, name: &str, c: usize) -> Result<Self, String> {
824        let a = vec_n(model, &format!("{name}.alpha"), c)?.iter().map(|v| v.exp()).collect();
825        let inv_b = vec_n(model, &format!("{name}.beta"), c)?.iter().map(|v| 1.0 / (v.exp() + 1e-9)).collect();
826        Ok(Self { a, inv_b })
827    }
828
829    fn apply(&self, x: &mut [f32], pool: Option<&Pool>) {
830        let c = self.a.len();
831        let rows = x.len() / c;
832        let xp = SendMut(x.as_mut_ptr());
833        par_rows(pool, rows, &|lo, hi| {
834            // SAFETY: rows lo..hi of `x` belong to this worker alone
835            let part = unsafe { std::slice::from_raw_parts_mut(xp.get().add(lo * c), (hi - lo) * c) };
836            for r in part.chunks_mut(c) {
837                for ((v, &a), &ib) in r.iter_mut().zip(&self.a).zip(&self.inv_b) {
838                    let s = (*v * a).sin();
839                    *v += ib * s * s;
840                }
841            }
842        });
843    }
844}
845
846struct ResUnit {
847    act1: Snake,
848    conv1: Conv,
849    act2: Snake,
850    conv2: Conv,
851}
852
853struct DecBlock {
854    act: Snake,
855    up: ConvT,
856    units: Vec<ResUnit>,
857    cout: usize,
858}
859
860struct XLayer {
861    in_norm: Vec<f32>,
862    q: Lin,
863    k: Lin,
864    v: Lin,
865    o: Lin,
866    attn_scale: Vec<f32>,
867    post_norm: Vec<f32>,
868    gate: Lin,
869    up: Lin,
870    down: Lin,
871    mlp_scale: Vec<f32>,
872}
873
874struct ConvNext {
875    dw: Vec<f32>,
876    dw_b: Vec<f32>,
877    ln_w: Vec<f32>,
878    ln_b: Vec<f32>,
879    pw1: Lin,
880    pw2: Lin,
881    gamma: Vec<f32>,
882}
883
884/// The speech tokenizer's decoder (`Qwen3TTSTokenizerV2Decoder`).
885pub struct Codec {
886    /// `[quantizer][code][256]`, the first the semantic one.
887    books: Vec<Vec<f32>>,
888    book_dim: usize,
889    proj_first: Lin,
890    proj_rest: Lin,
891    pre_conv: Conv,
892    in_proj: Lin,
893    layers: Vec<XLayer>,
894    norm: Vec<f32>,
895    out_proj: Lin,
896    ups: Vec<(ConvT, ConvNext)>,
897    conv_in: Conv,
898    blocks: Vec<DecBlock>,
899    act_out: Snake,
900    conv_out: Conv,
901    hidden: usize,
902    heads: usize,
903    hd: usize,
904    eps: f32,
905    theta: f64,
906    window: usize,
907    pool: Option<Arc<Pool>>,
908}
909
910impl Codec {
911    pub fn from_model(model: &CmfModel, cfg: &Qwen3TtsConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
912        let c = &cfg.codec;
913        let (latent, cbd, cbs, dec_dim, hidden, ffn, nl, heads, hd, nq) = (
914            ju(c, "latent_dim")?,
915            ju(c, "codebook_dim")?,
916            ju(c, "codebook_size")?,
917            ju(c, "decoder_dim")?,
918            ju(c, "hidden_size")?,
919            ju(c, "intermediate_size")?,
920            ju(c, "num_hidden_layers")?,
921            ju(c, "num_attention_heads")?,
922            ju(c, "head_dim")?,
923            ju(c, "num_quantizers")?,
924        );
925        let ups: Vec<usize> = c.get("upsample_rates").and_then(|v| v.as_array()).ok_or("qwen3_tts: no upsample_rates")?.iter().filter_map(|v| v.as_u64().map(|x| x as usize)).collect();
926        let ratios: Vec<usize> = c.get("upsampling_ratios").and_then(|v| v.as_array()).ok_or("qwen3_tts: no upsampling_ratios")?.iter().filter_map(|v| v.as_u64().map(|x| x as usize)).collect();
927        if ups.iter().chain(&ratios).product::<usize>() != FRAME_SAMPLES {
928            return Err("qwen3_tts: the decoder does not upsample 1920×".into());
929        }
930        let p = "qtts.codec.decoder";
931        let bd = cbd / 2;
932        let book = |pre: &str, i: usize| -> Result<Vec<f32>, String> {
933            let sum = crate::dit::cmf_f32(model, &format!("{p}.quantizer.{pre}.vq.layers.{i}._codebook.embedding_sum"))?;
934            let usage = vec_n(model, &format!("{p}.quantizer.{pre}.vq.layers.{i}._codebook.cluster_usage"), cbs)?;
935            if sum.len() != cbs * bd {
936                return Err(format!("qwen3_tts: codebook {pre}.{i} has {} values", sum.len()));
937            }
938            Ok(sum.chunks(bd).zip(&usage).flat_map(|(r, &u)| r.iter().map(move |v| v / u.max(1e-5))).collect())
939        };
940        let mut books = vec![book("rvq_first", 0)?];
941        for i in 0..nq - 1 {
942            books.push(book("rvq_rest", i)?);
943        }
944        let proj = |pre: &str| -> Result<Lin, String> {
945            let w = crate::dit::cmf_f32(model, &format!("{p}.quantizer.{pre}.output_proj.weight"))?;
946            if w.len() != cbd * bd {
947                return Err(format!("qwen3_tts: {pre}.output_proj has {} values", w.len()));
948            }
949            Ok(Lin { w, b: None, rows: cbd, cols: bd })
950        };
951        let mut layers = Vec::with_capacity(nl);
952        for l in 0..nl {
953            let b = format!("{p}.pre_transformer.layers.{l}");
954            layers.push(XLayer {
955                in_norm: vec_n(model, &format!("{b}.input_layernorm.weight"), hidden)?,
956                q: Lin::load(model, &format!("{b}.self_attn.q_proj"), heads * hd, hidden, false)?,
957                k: Lin::load(model, &format!("{b}.self_attn.k_proj"), heads * hd, hidden, false)?,
958                v: Lin::load(model, &format!("{b}.self_attn.v_proj"), heads * hd, hidden, false)?,
959                o: Lin::load(model, &format!("{b}.self_attn.o_proj"), hidden, heads * hd, false)?,
960                attn_scale: vec_n(model, &format!("{b}.self_attn_layer_scale.scale"), hidden)?,
961                post_norm: vec_n(model, &format!("{b}.post_attention_layernorm.weight"), hidden)?,
962                gate: Lin::load(model, &format!("{b}.mlp.gate_proj"), ffn, hidden, false)?,
963                up: Lin::load(model, &format!("{b}.mlp.up_proj"), ffn, hidden, false)?,
964                down: Lin::load(model, &format!("{b}.mlp.down_proj"), hidden, ffn, false)?,
965                mlp_scale: vec_n(model, &format!("{b}.mlp_layer_scale.scale"), hidden)?,
966            });
967        }
968        let mut upsample = Vec::new();
969        for (i, &f) in ratios.iter().enumerate() {
970            let b = format!("{p}.upsample.{i}");
971            let dw_raw = crate::dit::cmf_f32(model, &format!("{b}.1.dwconv.conv.weight"))?;
972            if dw_raw.len() != latent * 7 {
973                return Err(format!("qwen3_tts: {b} dwconv has {} values", dw_raw.len()));
974            }
975            upsample.push((
976                ConvT::load(model, &format!("{b}.0.conv"), latent, latent, f, f)?,
977                ConvNext {
978                    dw: dw_raw,
979                    dw_b: vec_n(model, &format!("{b}.1.dwconv.conv.bias"), latent)?,
980                    ln_w: vec_n(model, &format!("{b}.1.norm.weight"), latent)?,
981                    ln_b: vec_n(model, &format!("{b}.1.norm.bias"), latent)?,
982                    pw1: Lin::load(model, &format!("{b}.1.pwconv1"), 4 * latent, latent, true)?,
983                    pw2: Lin::load(model, &format!("{b}.1.pwconv2"), latent, 4 * latent, true)?,
984                    gamma: vec_n(model, &format!("{b}.1.gamma"), latent)?,
985                },
986            ));
987        }
988        let mut blocks = Vec::new();
989        for (i, &r) in ups.iter().enumerate() {
990            let (cin, cout) = (dec_dim >> i, dec_dim >> (i + 1));
991            let b = format!("{p}.decoder.{}.block", i + 1);
992            let mut units = Vec::new();
993            for (u, dil) in [1usize, 3, 9].into_iter().enumerate() {
994                let ub = format!("{b}.{}", u + 2);
995                units.push(ResUnit {
996                    act1: Snake::load(model, &format!("{ub}.act1"), cout)?,
997                    conv1: Conv::load(model, &format!("{ub}.conv1.conv"), cout, cout, 7, dil, true)?,
998                    act2: Snake::load(model, &format!("{ub}.act2"), cout)?,
999                    conv2: Conv::load(model, &format!("{ub}.conv2.conv"), cout, cout, 1, 1, true)?,
1000                });
1001            }
1002            blocks.push(DecBlock {
1003                act: Snake::load(model, &format!("{b}.0"), cin)?,
1004                up: ConvT::load(model, &format!("{b}.1.conv"), cin, cout, 2 * r, r)?,
1005                units,
1006                cout,
1007            });
1008        }
1009        let out_dim = dec_dim >> ups.len();
1010        let last = ups.len() + 1;
1011        Ok(Self {
1012            books,
1013            book_dim: bd,
1014            proj_first: proj("rvq_first")?,
1015            proj_rest: proj("rvq_rest")?,
1016            pre_conv: Conv::load(model, &format!("{p}.pre_conv.conv"), cbd, latent, 3, 1, true)?,
1017            in_proj: Lin::load(model, &format!("{p}.pre_transformer.input_proj"), hidden, latent, true)?,
1018            layers,
1019            norm: vec_n(model, &format!("{p}.pre_transformer.norm.weight"), hidden)?,
1020            out_proj: Lin::load(model, &format!("{p}.pre_transformer.output_proj"), latent, hidden, true)?,
1021            ups: upsample,
1022            conv_in: Conv::load(model, &format!("{p}.decoder.0.conv"), latent, dec_dim, 7, 1, true)?,
1023            blocks,
1024            act_out: Snake::load(model, &format!("{p}.decoder.{last}"), out_dim)?,
1025            conv_out: Conv::load(model, &format!("{p}.decoder.{}.conv", last + 1), out_dim, 1, 7, 1, true)?,
1026            hidden,
1027            heads,
1028            hd,
1029            eps: jf(c, "rms_norm_eps", 1e-5) as f32,
1030            theta: jf(c, "rope_theta", 1e4),
1031            window: c.get("sliding_window").and_then(|v| v.as_u64()).unwrap_or(72) as usize,
1032            pool,
1033        })
1034    }
1035
1036    /// One forward over `frames` (positions from 0): 1920 samples a frame.
1037    fn forward(&self, frames: &[Vec<u32>]) -> Vec<f32> {
1038        let pool = self.pool.as_deref();
1039        let t = frames.len();
1040        let bd = self.book_dim;
1041        let t_stage = std::time::Instant::now();
1042        // RVQ: the semantic codebook and the sum of the acoustic ones, each projected
1043        let mut first = vec![0f32; t * bd];
1044        let mut rest = vec![0f32; t * bd];
1045        for (f, fr) in frames.iter().enumerate() {
1046            for (q, &code) in fr.iter().enumerate().take(self.books.len()) {
1047                let row = &self.books[q][code as usize * bd..(code as usize + 1) * bd];
1048                let dst = if q == 0 { &mut first[f * bd..(f + 1) * bd] } else { &mut rest[f * bd..(f + 1) * bd] };
1049                for (d, &v) in dst.iter_mut().zip(row) {
1050                    *d += v;
1051                }
1052            }
1053        }
1054        let mut x = self.proj_first.apply(&first, t, pool);
1055        for (a, b) in x.iter_mut().zip(self.proj_rest.apply(&rest, t, pool)) {
1056            *a += b;
1057        }
1058        let x = self.pre_conv.apply(&x, t, pool);
1059        prof(3, t_stage);
1060        let t_stage = std::time::Instant::now();
1061        // the transformer, causal within the window
1062        let mut h = self.in_proj.apply(&x, t, pool);
1063        let (hs, nh, hd) = (self.hidden, self.heads, self.hd);
1064        let scale = 1.0 / (hd as f32).sqrt();
1065        for l in &self.layers {
1066            let xn: Vec<f32> = h.chunks(hs).flat_map(|r| rms(r, &l.in_norm, self.eps)).collect();
1067            let mut q = l.q.apply(&xn, t, pool);
1068            let mut k = l.k.apply(&xn, t, pool);
1069            let v = l.v.apply(&xn, t, pool);
1070            for r in 0..t {
1071                for hh in 0..nh {
1072                    rope(&mut q[(r * nh + hh) * hd..(r * nh + hh + 1) * hd], r, self.theta);
1073                    rope(&mut k[(r * nh + hh) * hd..(r * nh + hh + 1) * hd], r, self.theta);
1074                }
1075            }
1076            let mut att = vec![0f32; t * nh * hd];
1077            let w = self.window;
1078            let f = |lo: usize, hi: usize, att: &mut [f32]| {
1079                for r in lo..hi {
1080                    let j0 = (r + 1).saturating_sub(w);
1081                    for hh in 0..nh {
1082                        let qv = &q[(r * nh + hh) * hd..(r * nh + hh + 1) * hd];
1083                        let mut sc: Vec<f32> = (j0..=r)
1084                            .map(|j| qv.iter().zip(&k[(j * nh + hh) * hd..(j * nh + hh + 1) * hd]).map(|(a, b)| a * b).sum::<f32>() * scale)
1085                            .collect();
1086                        let mx = sc.iter().copied().fold(f32::NEG_INFINITY, f32::max);
1087                        let mut z = 0f32;
1088                        for s in &mut sc {
1089                            *s = (*s - mx).exp();
1090                            z += *s;
1091                        }
1092                        let out = &mut att[((r - lo) * nh + hh) * hd..((r - lo) * nh + hh + 1) * hd];
1093                        for (jj, &p) in sc.iter().enumerate() {
1094                            let vv = &v[((j0 + jj) * nh + hh) * hd..((j0 + jj) * nh + hh + 1) * hd];
1095                            for (o, &b) in out.iter_mut().zip(vv) {
1096                                *o += p / z * b;
1097                            }
1098                        }
1099                    }
1100                }
1101            };
1102            match pool {
1103                Some(p) if t > 8 => {
1104                    let ap = SendMut(att.as_mut_ptr());
1105                    p.run_rows(t, &|lo, hi| {
1106                        // SAFETY: rows lo..hi of `att` belong to this worker alone
1107                        let sl = unsafe { std::slice::from_raw_parts_mut(ap.get().add(lo * nh * hd), (hi - lo) * nh * hd) };
1108                        f(lo, hi, sl);
1109                    });
1110                }
1111                _ => f(0, t, &mut att),
1112            }
1113            let o = l.o.apply(&att, t, pool);
1114            for (r, orow) in h.chunks_mut(hs).zip(o.chunks(hs)) {
1115                for ((a, &b), &s) in r.iter_mut().zip(orow).zip(&l.attn_scale) {
1116                    *a += s * b;
1117                }
1118            }
1119            let xn: Vec<f32> = h.chunks(hs).flat_map(|r| rms(r, &l.post_norm, self.eps)).collect();
1120            let g = l.gate.apply(&xn, t, pool);
1121            let u = l.up.apply(&xn, t, pool);
1122            let m: Vec<f32> = g.iter().zip(&u).map(|(&a, &b)| silu(a) * b).collect();
1123            let d = l.down.apply(&m, t, pool);
1124            for (r, drow) in h.chunks_mut(hs).zip(d.chunks(hs)) {
1125                for ((a, &b), &s) in r.iter_mut().zip(drow).zip(&l.mlp_scale) {
1126                    *a += s * b;
1127                }
1128            }
1129        }
1130        let hn: Vec<f32> = h.chunks(hs).flat_map(|r| rms(r, &self.norm, self.eps)).collect();
1131        let mut x = self.out_proj.apply(&hn, t, pool);
1132        prof(4, t_stage);
1133        let t_stage = std::time::Instant::now();
1134        let mut len = t;
1135        // two upsamplings, each a ConvNeXt block after it
1136        for (up, cn) in &self.ups {
1137            x = up.apply(&x, len, pool);
1138            len *= up.s;
1139            x = cn.apply(&x, len, pool);
1140        }
1141        prof(5, t_stage);
1142        let t_stage = std::time::Instant::now();
1143        let mut x = self.conv_in.apply(&x, len, pool);
1144        prof(6, t_stage);
1145        for (bi, b) in self.blocks.iter().enumerate() {
1146            let t_stage = std::time::Instant::now();
1147            b.act.apply(&mut x, pool);
1148            x = b.up.apply(&x, len, pool);
1149            len *= b.up.s;
1150            for u in &b.units {
1151                let mut y = x.clone();
1152                u.act1.apply(&mut y, pool);
1153                let mut y = u.conv1.apply(&y, len, pool);
1154                u.act2.apply(&mut y, pool);
1155                let y = u.conv2.apply(&y, len, pool);
1156                for (a, b2) in x.iter_mut().zip(&y) {
1157                    *a += b2;
1158                }
1159            }
1160            debug_assert_eq!(x.len(), len * b.cout);
1161            prof(7 + bi.min(3), t_stage);
1162        }
1163        let t_stage = std::time::Instant::now();
1164        self.act_out.apply(&mut x, pool);
1165        let mut wav = self.conv_out.apply(&x, len, pool);
1166        for v in &mut wav {
1167            *v = v.clamp(-1.0, 1.0);
1168        }
1169        prof(11, t_stage);
1170        wav
1171    }
1172
1173    /// The waveform of `frames`, decoded 300 frames at a time over 25 frames
1174    /// of left context (`chunked_decode`).
1175    pub fn decode(&self, frames: &[Vec<u32>]) -> Vec<f32> {
1176        const CHUNK: usize = 300;
1177        const LEFT: usize = 25;
1178        let mut out = Vec::with_capacity(frames.len() * FRAME_SAMPLES);
1179        let mut start = 0;
1180        while start < frames.len() {
1181            let end = (start + CHUNK).min(frames.len());
1182            let ctx = if start > LEFT { LEFT } else { start };
1183            let w = self.forward(&frames[start - ctx..end]);
1184            out.extend_from_slice(&w[ctx * FRAME_SAMPLES..]);
1185            start = end;
1186        }
1187        out
1188    }
1189}
1190
1191impl ConvNext {
1192    fn apply(&self, x: &[f32], t: usize, pool: Option<&Pool>) -> Vec<f32> {
1193        let c = self.ln_w.len();
1194        // causal depthwise k7
1195        let mut d = vec![0f32; t * c];
1196        let dp = SendMut(d.as_mut_ptr());
1197        par_rows(pool, t, &|lo, hi| {
1198            for r in lo..hi {
1199                // SAFETY: row r of `d` belongs to this worker alone
1200                let row = unsafe { std::slice::from_raw_parts_mut(dp.get().add(r * c), c) };
1201                for (ch, out) in row.iter_mut().enumerate() {
1202                    let mut acc = self.dw_b[ch];
1203                    for j in 0..7 {
1204                        let src = r as isize + j as isize - 6;
1205                        if src >= 0 {
1206                            acc += self.dw[ch * 7 + j] * x[src as usize * c + ch];
1207                        }
1208                    }
1209                    *out = acc;
1210                }
1211            }
1212        });
1213        for row in d.chunks_mut(c) {
1214            let mean = row.iter().map(|&v| v as f64).sum::<f64>() / c as f64;
1215            let var = row.iter().map(|&v| (v as f64 - mean).powi(2)).sum::<f64>() / c as f64;
1216            let inv = 1.0 / (var + 1e-6).sqrt();
1217            for ((v, &w), &b) in row.iter_mut().zip(&self.ln_w).zip(&self.ln_b) {
1218                *v = ((*v as f64 - mean) * inv) as f32 * w + b;
1219            }
1220        }
1221        let mut m = self.pw1.apply(&d, t, pool);
1222        for v in &mut m {
1223            *v = gelu_erf(*v);
1224        }
1225        let y = self.pw2.apply(&m, t, pool);
1226        let mut out = x.to_vec();
1227        for (orow, yrow) in out.chunks_mut(c).zip(y.chunks(c)) {
1228            for ((o, &v), &g) in orow.iter_mut().zip(yrow).zip(&self.gamma) {
1229                *o += g * v;
1230            }
1231        }
1232        out
1233    }
1234}
1235
1236#[derive(Clone, Copy)]
1237pub(crate) struct SendMut(pub(crate) *mut f32);
1238unsafe impl Send for SendMut {}
1239unsafe impl Sync for SendMut {}
1240impl SendMut {
1241    pub(crate) fn get(self) -> *mut f32 {
1242        self.0
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249
1250    /// The sampler is greedy without sampling and honours suppression and
1251    /// the repetition penalty in HF's order.
1252    #[test]
1253    fn greedy_sample_suppresses_and_penalizes() {
1254        let mut rng = SplitMix64::new(1);
1255        let g = Sampling { do_sample: false, temperature: 0.9, top_k: 50, top_p: 1.0 };
1256        let l = [0.0f32, 3.0, 2.9, 1.0];
1257        assert_eq!(sample(&l, &g, None, 1.0, &[], &mut rng), 1);
1258        assert_eq!(sample(&l, &g, Some(&|i| i == 1), 1.0, &[], &mut rng), 2);
1259        // 3.0 / 1.05 < 2.9: the repeated code yields
1260        assert_eq!(sample(&l, &g, None, 1.05, &[1], &mut rng), 2);
1261    }
1262
1263    /// RoPE keeps the norm and rotates the pair (j, j + half).
1264    #[test]
1265    fn rope_rotates_halves() {
1266        let mut x = vec![1.0f32, 0.0, 0.0, 0.0];
1267        rope(&mut x, 1, 10000.0);
1268        assert!((x[0] - 1f32.cos()).abs() < 1e-6 && (x[2] - 1f32.sin()).abs() < 1e-6);
1269    }
1270}