Skip to main content

cortiq_engine/
haru.rs

1//! Haru (higurashi-ai/Haru-4B): full-duplex spoken dialogue at 7.5 Hz.
2//!
3//! One language-model position is one 133 ms frame, and its input is the sum
4//! of three streams at that frame: the model's text token, the model's audio
5//! latent and the user's audio latent, each latent through its projector
6//! (`haru.{model,user}_audio_proj`). The final-normed hidden state at frame t
7//! predicts frame t + 1: the text token through the tied embedding, the audio
8//! latent through the MeanFlow head (`haru.head`, a four-layer adaLN MLP, one
9//! sampling step). The VibeVoice codec (`haru.codec`, causal convolution
10//! stacks) turns 3200 samples of 24 kHz audio into one 64-dim latent and back.
11//! The language model is a Qwen3.5 text stack driven row by row through
12//! `Pipeline::speech_*`; everything else runs in f32, its big products on the
13//! device through `gemm_nt`.
14//!
15//! The prompt (character card as a ChatML system turn, the voice reference as
16//! audio on the model's stream), the sampling (DRY, PAD / EOP in float32,
17//! top-k) and the offline loop follow higurashi-ai/Haru's `haru` package
18//! (`DuplexSession`, `haru-inference`). The codec is causal, so encoding a
19//! whole recording and decoding the whole reply give the frame-by-frame
20//! stream's results exactly.
21
22use crate::inference::{gelu_erf, silu};
23use crate::pipeline::Pipeline;
24use crate::pool::Pool;
25use crate::qwen3_tts::{Lin, SendMut, par_rows, rms, vec_n};
26use crate::sampler::SplitMix64;
27use cortiq_core::CmfModel;
28use serde_json::Value;
29use std::sync::Arc;
30
31/// Whether the file is a Haru conversion.
32pub fn is_haru(model: &CmfModel) -> bool {
33    model.header.provenance.as_ref().is_some_and(|p| p.get("haru").is_some())
34}
35
36fn ju(v: &Value, k: &str) -> Result<usize, String> {
37    v.get(k).and_then(|x| x.as_u64()).map(|x| x as usize).ok_or_else(|| format!("haru: config lacks {k}"))
38}
39
40fn jf(v: &Value, k: &str, d: f64) -> f64 {
41    v.get(k).and_then(|x| x.as_f64()).unwrap_or(d)
42}
43
44fn jv(v: &Value, k: &str) -> Result<Vec<usize>, String> {
45    v.get(k)
46        .and_then(|x| x.as_array())
47        .map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect())
48        .ok_or_else(|| format!("haru: config lacks {k}"))
49}
50
51/// What the loop needs from `provenance.haru.config`.
52#[derive(Clone, Debug)]
53pub struct HaruConfig {
54    pub sample_rate: u32,
55    pub frame_samples: usize,
56    pub latent_dim: usize,
57    pub pad: u32,
58    pub eop: u32,
59    pub eos: Option<u32>,
60    pub hidden: usize,
61    base: usize,
62    ratios: Vec<usize>,
63    enc_depths: Vec<usize>,
64    dec_depths: Vec<usize>,
65    codec_eps: f32,
66    latent_std: f32,
67    head_layers: usize,
68    head_ffn: usize,
69    head_eps: f32,
70    interval_embed: f32,
71    pub num_steps: usize,
72    pub guidance: f32,
73}
74
75impl HaruConfig {
76    pub fn from_model(model: &CmfModel) -> Result<Self, String> {
77        let c = model
78            .header
79            .provenance
80            .as_ref()
81            .and_then(|p| p.get("haru"))
82            .and_then(|p| p.get("config"))
83            .ok_or("haru: the file has no provenance.haru.config")?;
84        let codec = c.get("codec").ok_or("haru: no codec config")?;
85        let head = c.get("head").ok_or("haru: no head config")?;
86        let lm = c.get("lm").ok_or("haru: no lm config")?;
87        let hidden = ju(head, "hidden_size")?;
88        let cfg = Self {
89            sample_rate: ju(c, "sample_rate")? as u32,
90            frame_samples: ju(c, "frame_samples")?,
91            latent_dim: ju(c, "latent_dim")?,
92            pad: ju(c, "pad_token_id")? as u32,
93            eop: ju(c, "eop_token_id")? as u32,
94            eos: lm.get("eos_token_id").and_then(|v| v.as_u64()).map(|v| v as u32),
95            hidden,
96            base: ju(codec, "base_channels")?,
97            ratios: jv(codec, "ratios")?,
98            enc_depths: jv(codec, "encoder_depths")?,
99            dec_depths: jv(codec, "decoder_depths")?,
100            codec_eps: jf(codec, "norm_eps", 1e-5) as f32,
101            latent_std: jf(codec, "latent_std", 0.5) as f32,
102            head_layers: ju(head, "num_layers")?,
103            head_ffn: (hidden as f64 * jf(head, "ffn_ratio", 3.0)) as usize,
104            head_eps: jf(head, "norm_eps", 1e-5) as f32,
105            interval_embed: jf(head, "interval_embed", 7.0) as f32,
106            num_steps: ju(head, "num_steps").unwrap_or(1),
107            guidance: jf(head, "guidance_scale", 1.5) as f32,
108        };
109        if cfg.ratios.iter().product::<usize>() != cfg.frame_samples {
110            return Err("haru: codec ratios do not match frame_samples".into());
111        }
112        Ok(cfg)
113    }
114}
115
116/// A standard normal draw (Box–Muller).
117fn normal(rng: &mut SplitMix64) -> f32 {
118    let u1 = (rng.next_f32() as f64).max(1e-12);
119    let u2 = rng.next_f32() as f64;
120    ((-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()) as f32
121}
122
123// ───────────────────────────── codec ─────────────────────────────
124
125/// A causal convolution over `[T][cin]` (channels last), stride `s`, the
126/// left context `k - s` zero (a whole clip from a zero state); a partial
127/// final hop is padded on the right.
128struct Conv {
129    /// `[cout][k][cin]` from the source `[cout][cin][k]`.
130    w: Vec<f32>,
131    b: Vec<f32>,
132    cin: usize,
133    cout: usize,
134    k: usize,
135    s: usize,
136}
137
138impl Conv {
139    fn load(model: &CmfModel, name: &str, cin: usize, cout: usize, k: usize, s: usize) -> Result<Self, String> {
140        let src = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
141        if src.len() != cout * cin * k {
142            return Err(format!("{name}.weight: {} values, expected [{cout}, {cin}, {k}]", src.len()));
143        }
144        let mut w = vec![0f32; src.len()];
145        for o in 0..cout {
146            for i in 0..cin {
147                for t in 0..k {
148                    w[(o * k + t) * cin + i] = src[(o * cin + i) * k + t];
149                }
150            }
151        }
152        Ok(Self { w, b: vec_n(model, &format!("{name}.bias"), cout)?, cin, cout, k, s })
153    }
154
155    /// `x [t][cin]` → `[ceil(t / s)][cout]`.
156    fn apply(&self, x: &[f32], t: usize, pool: Option<&Pool>) -> (Vec<f32>, usize) {
157        let (cin, k, s) = (self.cin, self.k, self.s);
158        let ctx = k - s;
159        let tout = t.div_ceil(s);
160        let mut y = vec![0f32; tout * self.cout];
161        let block = ((1usize << 22) / (k * cin).max(1)).clamp(1, tout.max(1));
162        let mut col = vec![0f32; block * k * cin];
163        let mut t0 = 0;
164        while t0 < tout {
165            let nb = block.min(tout - t0);
166            let cp = SendMut(col.as_mut_ptr());
167            par_rows(pool, nb, &|lo, hi| {
168                for r in lo..hi {
169                    let start = (t0 + r) * s;
170                    for j in 0..k {
171                        let src = start as isize + j as isize - ctx as isize;
172                        // SAFETY: row r of `col` belongs to this worker alone
173                        let dst = unsafe { std::slice::from_raw_parts_mut(cp.get().add((r * k + j) * cin), cin) };
174                        if src < 0 || src as usize >= t {
175                            dst.fill(0.0);
176                        } else {
177                            dst.copy_from_slice(&x[src as usize * cin..(src as usize + 1) * cin]);
178                        }
179                    }
180                }
181            });
182            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);
183            t0 += nb;
184        }
185        add_bias(&mut y, &self.b, pool);
186        (y, tout)
187    }
188}
189
190fn add_bias(y: &mut [f32], b: &[f32], pool: Option<&Pool>) {
191    let c = b.len();
192    let rows = y.len() / c;
193    let yp = SendMut(y.as_mut_ptr());
194    par_rows(pool, rows, &|lo, hi| {
195        // SAFETY: rows lo..hi of `y` belong to this worker alone
196        let part = unsafe { std::slice::from_raw_parts_mut(yp.get().add(lo * c), (hi - lo) * c) };
197        for r in part.chunks_mut(c) {
198            for (v, &bb) in r.iter_mut().zip(b) {
199                *v += bb;
200            }
201        }
202    });
203}
204
205/// `CausalConvTranspose1d`: kernel `2s`, stride `s`, the overlap tail of a
206/// whole sequence dropped: `[t][cin]` → `[t·s][cout]`.
207struct ConvT {
208    /// `[cout·k][cin]` (rows `(o, j)`), from the source `[cin][cout][k]`.
209    w: Vec<f32>,
210    b: Vec<f32>,
211    cin: usize,
212    cout: usize,
213    k: usize,
214    s: usize,
215}
216
217impl ConvT {
218    fn load(model: &CmfModel, name: &str, cin: usize, cout: usize, s: usize) -> Result<Self, String> {
219        let k = 2 * s;
220        let src = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
221        if src.len() != cin * cout * k {
222            return Err(format!("{name}.weight: {} values, expected [{cin}, {cout}, {k}]", src.len()));
223        }
224        let mut w = vec![0f32; src.len()];
225        for i in 0..cin {
226            for o in 0..cout {
227                for j in 0..k {
228                    w[(o * k + j) * cin + i] = src[(i * cout + o) * k + j];
229                }
230            }
231        }
232        Ok(Self { w, b: vec_n(model, &format!("{name}.bias"), cout)?, cin, cout, k, s })
233    }
234
235    fn apply(&self, x: &[f32], t: usize, pool: Option<&Pool>) -> Vec<f32> {
236        let (cout, k, s) = (self.cout, self.k, self.s);
237        let keep = t * s;
238        let mut y = vec![0f32; keep * cout];
239        let block = ((1usize << 22) / (cout * k)).clamp(1, t.max(1));
240        let mut part = vec![0f32; block * cout * k];
241        let mut t0 = 0;
242        while t0 < t {
243            let nb = block.min(t - t0);
244            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);
245            let (yp, part) = (SendMut(y.as_mut_ptr()), &part);
246            par_rows(pool, cout, &|o0, o1| {
247                for r in 0..nb {
248                    let tt = t0 + r;
249                    for o in o0..o1 {
250                        for j in 0..k {
251                            let at = tt * s + j;
252                            if at < keep {
253                                // SAFETY: column o of `y` belongs to this worker alone
254                                unsafe { *yp.get().add(at * cout + o) += part[(r * cout + o) * k + j] };
255                            }
256                        }
257                    }
258                }
259            });
260            t0 += nb;
261        }
262        add_bias(&mut y, &self.b, pool);
263        y
264    }
265}
266
267/// `Block`: a depthwise causal k7 mixer and an MLP, each with a scaled
268/// residual, RMS norms in front.
269struct Block {
270    norm: Vec<f32>,
271    dw: Vec<f32>,
272    dw_b: Vec<f32>,
273    gamma: Vec<f32>,
274    ffn_norm: Vec<f32>,
275    fc1: Lin,
276    fc2: Lin,
277    ffn_gamma: Vec<f32>,
278    dim: usize,
279}
280
281impl Block {
282    fn load(model: &CmfModel, p: &str, dim: usize) -> Result<Self, String> {
283        let dw = crate::dit::cmf_f32(model, &format!("{p}.conv.weight"))?;
284        if dw.len() != dim * 7 {
285            return Err(format!("{p}.conv.weight: {} values", dw.len()));
286        }
287        Ok(Self {
288            norm: vec_n(model, &format!("{p}.norm.weight"), dim)?,
289            dw,
290            dw_b: vec_n(model, &format!("{p}.conv.bias"), dim)?,
291            gamma: vec_n(model, &format!("{p}.gamma"), dim)?,
292            ffn_norm: vec_n(model, &format!("{p}.ffn_norm.weight"), dim)?,
293            fc1: Lin::load(model, &format!("{p}.fc1"), 4 * dim, dim, true)?,
294            fc2: Lin::load(model, &format!("{p}.fc2"), dim, 4 * dim, true)?,
295            ffn_gamma: vec_n(model, &format!("{p}.ffn_gamma"), dim)?,
296            dim,
297        })
298    }
299
300    fn apply(&self, x: &mut [f32], t: usize, eps: f32, pool: Option<&Pool>) {
301        let c = self.dim;
302        let xn: Vec<f32> = x.chunks(c).flat_map(|r| rms(r, &self.norm, eps)).collect();
303        let xp = SendMut(x.as_mut_ptr());
304        let xn = &xn;
305        par_rows(pool, t, &|lo, hi| {
306            // rows lo..hi read only rows ≤ their own of `xn`, write their own of `x`
307            for r in lo..hi {
308                // SAFETY: row r of `x` belongs to this worker alone
309                let row = unsafe { std::slice::from_raw_parts_mut(xp.get().add(r * c), c) };
310                for (ch, out) in row.iter_mut().enumerate() {
311                    let mut acc = self.dw_b[ch];
312                    for j in 0..7 {
313                        let src = r as isize + j as isize - 6;
314                        if src >= 0 {
315                            acc += self.dw[ch * 7 + j] * xn[src as usize * c + ch];
316                        }
317                    }
318                    *out += acc * self.gamma[ch];
319                }
320            }
321        });
322        let hn: Vec<f32> = x.chunks(c).flat_map(|r| rms(r, &self.ffn_norm, eps)).collect();
323        let mut h = self.fc1.apply(&hn, t, pool);
324        let hp = SendMut(h.as_mut_ptr());
325        let n = h.len();
326        par_rows(pool, t, &|lo, hi| {
327            let w = n / t;
328            // SAFETY: rows lo..hi of `h` belong to this worker alone
329            let part = unsafe { std::slice::from_raw_parts_mut(hp.get().add(lo * w), (hi - lo) * w) };
330            for v in part {
331                *v = gelu_erf(*v);
332            }
333        });
334        let h = self.fc2.apply(&h, t, pool);
335        for (row, hr) in x.chunks_mut(c).zip(h.chunks(c)) {
336            for ((v, &a), &g) in row.iter_mut().zip(hr).zip(&self.ffn_gamma) {
337                *v += a * g;
338            }
339        }
340    }
341}
342
343/// The VibeVoice acoustic codec.
344pub struct Codec {
345    enc_stem: Conv,
346    enc_down: Vec<Conv>,
347    enc_stages: Vec<Vec<Block>>,
348    enc_head: Conv,
349    dec_stem: Conv,
350    dec_up: Vec<ConvT>,
351    dec_stages: Vec<Vec<Block>>,
352    dec_head: Conv,
353    eps: f32,
354    latent_dim: usize,
355    frame: usize,
356    latent_std: f32,
357    pool: Option<Arc<Pool>>,
358}
359
360impl Codec {
361    pub fn from_model(model: &CmfModel, c: &HaruConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
362        let (b, n) = (c.base, c.ratios.len());
363        let p = "haru.codec";
364        // encoder: strides are the ratios reversed, the channels double
365        let strides: Vec<usize> = c.ratios.iter().rev().copied().collect();
366        let mut enc_down = Vec::new();
367        for (i, &s) in strides.iter().enumerate() {
368            enc_down.push(Conv::load(model, &format!("{p}.encoder.down.{i}"), b << i, b << (i + 1), 2 * s, s)?);
369        }
370        let mut enc_stages = Vec::new();
371        for (i, &d) in c.enc_depths.iter().enumerate() {
372            let mut st = Vec::new();
373            for j in 0..d {
374                st.push(Block::load(model, &format!("{p}.encoder.stages.{i}.{j}"), b << i)?);
375            }
376            enc_stages.push(st);
377        }
378        let mut dec_up = Vec::new();
379        for (i, &s) in c.ratios.iter().enumerate() {
380            dec_up.push(ConvT::load(model, &format!("{p}.decoder.up.{i}"), b << (n - i), b << (n - i - 1), s)?);
381        }
382        let mut dec_stages = Vec::new();
383        for (i, &d) in c.dec_depths.iter().enumerate() {
384            let mut st = Vec::new();
385            for j in 0..d {
386                st.push(Block::load(model, &format!("{p}.decoder.stages.{i}.{j}"), b << (n - i))?);
387            }
388            dec_stages.push(st);
389        }
390        Ok(Self {
391            enc_stem: Conv::load(model, &format!("{p}.encoder.stem"), 1, b, 7, 1)?,
392            enc_down,
393            enc_stages,
394            enc_head: Conv::load(model, &format!("{p}.encoder.head"), b << n, c.latent_dim, 7, 1)?,
395            dec_stem: Conv::load(model, &format!("{p}.decoder.stem"), c.latent_dim, b << n, 7, 1)?,
396            dec_up,
397            dec_stages,
398            dec_head: Conv::load(model, &format!("{p}.decoder.head"), b, 1, 7, 1)?,
399            eps: c.codec_eps,
400            latent_dim: c.latent_dim,
401            frame: c.frame_samples,
402            latent_std: c.latent_std,
403            pool,
404        })
405    }
406
407    /// Latent means `[ceil(len / 3200)][64]` of a whole clip.
408    pub fn encode(&self, audio: &[f32]) -> Vec<f32> {
409        let pool = self.pool.as_deref();
410        let mut t = audio.len();
411        let mut x = audio.to_vec();
412        for (i, stage) in self.enc_stages.iter().enumerate() {
413            let conv = if i == 0 { &self.enc_stem } else { &self.enc_down[i - 1] };
414            let (y, tn) = conv.apply(&x, t, pool);
415            x = y;
416            t = tn;
417            for blk in stage {
418                blk.apply(&mut x, t, self.eps, pool);
419            }
420        }
421        self.enc_head.apply(&x, t, pool).0
422    }
423
424    /// The waveform of `latents [t][64]` (raw codec space), 3200 samples a latent.
425    pub fn decode(&self, latents: &[f32]) -> Vec<f32> {
426        let pool = self.pool.as_deref();
427        let mut t = latents.len() / self.latent_dim;
428        let mut x = latents.to_vec();
429        for (i, stage) in self.dec_stages.iter().enumerate() {
430            if i == 0 {
431                x = self.dec_stem.apply(&x, t, pool).0;
432            } else {
433                let up = &self.dec_up[i - 1];
434                x = up.apply(&x, t, pool);
435                t *= up.s;
436            }
437            for blk in stage {
438                blk.apply(&mut x, t, self.eps, pool);
439            }
440        }
441        let mut wav = self.dec_head.apply(&x, t, pool).0;
442        for v in &mut wav {
443            *v = v.clamp(-1.0, 1.0);
444        }
445        wav
446    }
447
448    /// Latents drawn around `means [n][64]` with one noise scale for all
449    /// of them (`VibeVoiceCodec.sample` over one call's rows).
450    pub fn sample(&self, means: &[f32], rng: &mut SplitMix64) -> Vec<f32> {
451        let scale = normal(rng) * self.latent_std / 0.8;
452        means.iter().map(|&m| m + scale * normal(rng)).collect()
453    }
454
455    /// The latent of digital silence (the last of sixteen silent frames).
456    pub fn silence(&self) -> Vec<f32> {
457        let m = self.encode(&vec![0f32; 16 * self.frame]);
458        m[m.len() - self.latent_dim..].to_vec()
459    }
460}
461
462// ───────────────────────────── projectors and head ─────────────────────────────
463
464/// Audio latent → embedding space: `fc2(rms(fc1(x)))`.
465struct Projector {
466    fc1: Lin,
467    norm: Vec<f32>,
468    fc2: Lin,
469}
470
471impl Projector {
472    fn load(model: &CmfModel, p: &str, latent: usize, hidden: usize) -> Result<Self, String> {
473        Ok(Self {
474            fc1: Lin::load(model, &format!("{p}.fc1"), hidden, latent, true)?,
475            norm: vec_n(model, &format!("{p}.norm.weight"), hidden)?,
476            fc2: Lin::load(model, &format!("{p}.fc2"), hidden, hidden, true)?,
477        })
478    }
479
480    fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
481        let h = self.fc1.apply(x, n, pool);
482        let hidden = h.len() / n.max(1);
483        let hn: Vec<f32> = h.chunks(hidden).flat_map(|r| rms(r, &self.norm, 1e-6)).collect();
484        self.fc2.apply(&hn, n, pool)
485    }
486}
487
488struct ScalarEmbed {
489    fc1: Lin,
490    fc2: Lin,
491}
492
493impl ScalarEmbed {
494    fn apply(&self, v: f32) -> Vec<f32> {
495        const HALF: usize = 128;
496        let mut f = vec![0f32; 2 * HALF];
497        for i in 0..HALF {
498            let freq = (-(10000f64.ln()) * i as f64 / HALF as f64).exp() as f32;
499            let a = v * freq;
500            f[i] = a.cos();
501            f[HALF + i] = a.sin();
502        }
503        let mut h = self.fc1.apply(&f, 1, None);
504        for x in &mut h {
505            *x = silu(*x);
506        }
507        self.fc2.apply(&h, 1, None)
508    }
509}
510
511struct HeadLayer {
512    ada: Lin,
513    norm: Vec<f32>,
514    gate: Lin,
515    up: Lin,
516    down: Lin,
517}
518
519/// The MeanFlow head: a latent from a hidden state and noise.
520pub struct Head {
521    cond_proj: Lin,
522    latent_proj: Lin,
523    t_embed: ScalarEmbed,
524    dt_embed: ScalarEmbed,
525    h_embed: ScalarEmbed,
526    omega_embed: ScalarEmbed,
527    layers: Vec<HeadLayer>,
528    final_ada: Lin,
529    final_proj: Lin,
530    hidden: usize,
531    eps: f32,
532    interval: f32,
533    pool: Option<Arc<Pool>>,
534}
535
536/// RMS norm without a weight.
537fn rms_plain(x: &[f32], eps: f32) -> Vec<f32> {
538    let ms = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
539    let r = 1.0 / (ms + eps as f64).sqrt();
540    x.iter().map(|&v| (v as f64 * r) as f32).collect()
541}
542
543impl Head {
544    pub fn from_model(model: &CmfModel, c: &HaruConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
545        let (hd, ld, ffn) = (c.hidden, c.latent_dim, c.head_ffn);
546        let p = "haru.head";
547        let se = |n: &str| -> Result<ScalarEmbed, String> {
548            Ok(ScalarEmbed { fc1: Lin::load(model, &format!("{p}.{n}.fc1"), hd, 256, false)?, fc2: Lin::load(model, &format!("{p}.{n}.fc2"), hd, hd, false)? })
549        };
550        let mut layers = Vec::new();
551        for i in 0..c.head_layers {
552            let b = format!("{p}.layers.{i}");
553            layers.push(HeadLayer {
554                ada: Lin::load(model, &format!("{b}.ada"), 3 * hd, hd, false)?,
555                norm: vec_n(model, &format!("{b}.norm.weight"), hd)?,
556                gate: Lin::load(model, &format!("{b}.ffn.gate_proj"), ffn, hd, false)?,
557                up: Lin::load(model, &format!("{b}.ffn.up_proj"), ffn, hd, false)?,
558                down: Lin::load(model, &format!("{b}.ffn.down_proj"), hd, ffn, false)?,
559            });
560        }
561        Ok(Self {
562            cond_proj: Lin::load(model, &format!("{p}.cond_proj"), hd, hd, false)?,
563            latent_proj: Lin::load(model, &format!("{p}.latent_proj"), hd, ld, false)?,
564            t_embed: se("t_embed")?,
565            dt_embed: se("dt_embed")?,
566            h_embed: se("h_embed")?,
567            omega_embed: se("omega_embed")?,
568            layers,
569            final_ada: Lin::load(model, &format!("{p}.final.ada"), 2 * hd, hd, false)?,
570            final_proj: Lin::load(model, &format!("{p}.final.proj"), ld, hd, false)?,
571            hidden: hd,
572            eps: c.head_eps,
573            interval: c.interval_embed,
574            pool,
575        })
576    }
577
578    /// The scalar terms of the condition at step time `t`, interval `h`
579    /// and guidance `w` (constant across frames).
580    pub fn scalars(&self, t: f32, h: f32, w: f32) -> Vec<f32> {
581        let mut c = self.t_embed.apply(t);
582        for e in [self.dt_embed.apply(self.interval), self.h_embed.apply(h), self.omega_embed.apply(1.0 - 1.0 / w)] {
583            for (a, b) in c.iter_mut().zip(e) {
584                *a += b;
585            }
586        }
587        c
588    }
589
590    /// Normalized latent from `hidden` (final-normed) and `noise`, `steps`
591    /// steps of the mean flow; `scalars[i]` from [`Self::scalars`].
592    pub fn sample(&self, hidden: &[f32], noise: &[f32], scalars: &[Vec<f32>]) -> Vec<f32> {
593        let pool = self.pool.as_deref();
594        let hd = self.hidden;
595        let steps = scalars.len();
596        let cond = self.cond_proj.apply(hidden, 1, pool);
597        let mut z = noise.to_vec();
598        let dh = 1.0 / steps as f32;
599        for sc in scalars {
600            let c: Vec<f32> = cond.iter().zip(sc).map(|(&a, &b)| silu(a + b)).collect();
601            let mut x = self.latent_proj.apply(&z, 1, pool);
602            for l in &self.layers {
603                let ada = l.ada.apply(&c, 1, pool);
604                let (shift, scale, gate) = (&ada[..hd], &ada[hd..2 * hd], &ada[2 * hd..]);
605                let h: Vec<f32> = rms_plain(&x, self.eps).iter().zip(&l.norm).map(|(&v, &w)| v * w).collect();
606                let m: Vec<f32> = h.iter().zip(scale).zip(shift).map(|((&v, &s), &b)| v * (1.0 + s) + b).collect();
607                let g = l.gate.apply(&m, 1, pool);
608                let u = l.up.apply(&m, 1, pool);
609                let mid: Vec<f32> = g.iter().zip(&u).map(|(&a, &b)| silu(a) * b).collect();
610                let f = l.down.apply(&mid, 1, pool);
611                for ((xv, &fv), &gv) in x.iter_mut().zip(&f).zip(gate) {
612                    *xv += gv * fv;
613                }
614            }
615            let ada = self.final_ada.apply(&c, 1, pool);
616            let (shift, scale) = (&ada[..hd], &ada[hd..]);
617            let m: Vec<f32> = rms_plain(&x, self.eps).iter().zip(scale).zip(shift).map(|((&v, &s), &b)| v * (1.0 + s) + b).collect();
618            let v = self.final_proj.apply(&m, 1, pool);
619            for (zv, &vv) in z.iter_mut().zip(&v) {
620                *zv += dh * vv;
621            }
622        }
623        z
624    }
625}
626
627// ───────────────────────────── sampling ─────────────────────────────
628
629/// DRY: discourage extending a token sequence that already occurred.
630#[derive(Clone, Copy, Debug)]
631pub struct Dry {
632    pub multiplier: f32,
633    pub base: f32,
634    pub allowed_length: usize,
635    pub lookback: usize,
636    pub max_match_length: usize,
637    pub max_penalty: f32,
638}
639
640impl Default for Dry {
641    fn default() -> Self {
642        Self { multiplier: 0.8, base: 1.75, allowed_length: 1, lookback: 1024, max_match_length: 32, max_penalty: 32.0 }
643    }
644}
645
646/// `{token: penalty}` for the tokens that would extend an earlier repeat.
647fn dry_penalties(history: &[u32], d: &Dry) -> Vec<(u32, f32)> {
648    let n = history.len();
649    if n < d.allowed_length.max(1) {
650        return Vec::new();
651    }
652    let mut longest: std::collections::HashMap<u32, usize> = std::collections::HashMap::new();
653    let last = history[n - 1];
654    let lo = (n as isize - 1 - d.lookback as isize).max(0) as usize;
655    let mut j = n as isize - 2;
656    while j >= lo as isize {
657        let ju = j as usize;
658        if history[ju] == last {
659            let mut length = 1;
660            while length < d.max_match_length && ju >= length && history[ju - length] == history[n - 1 - length] {
661                length += 1;
662            }
663            if length >= d.allowed_length {
664                let cand = history[ju + 1];
665                let e = longest.entry(cand).or_insert(0);
666                if length > *e {
667                    *e = length;
668                }
669            }
670        }
671        j -= 1;
672    }
673    longest
674        .into_iter()
675        .map(|(t, l)| (t, (d.multiplier * d.base.powi((l - d.allowed_length) as i32)).min(d.max_penalty)))
676        .collect()
677}
678
679/// `torch.topk` + softmax + multinomial over `logits / temperature`
680/// (greedy at temperature 0).
681fn sample_token(logits: &[f32], temperature: f32, top_k: usize, rng: &mut SplitMix64) -> u32 {
682    if temperature <= 0.0 {
683        return logits.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, &v)| if v > b.1 { (i, v) } else { b }).0 as u32;
684    }
685    let mut idx: Vec<usize> = (0..logits.len()).filter(|&i| logits[i].is_finite()).collect();
686    if top_k > 0 && top_k < idx.len() {
687        idx.select_nth_unstable_by(top_k - 1, |&a, &b| logits[b].total_cmp(&logits[a]));
688        idx.truncate(top_k);
689    }
690    let mx = idx.iter().map(|&i| logits[i]).fold(f32::NEG_INFINITY, f32::max);
691    let w: Vec<f64> = idx.iter().map(|&i| (((logits[i] - mx) / temperature) as f64).exp()).collect();
692    let total: f64 = w.iter().sum();
693    let mut r = rng.next_f32() as f64 * total;
694    for (&i, &wi) in idx.iter().zip(&w) {
695        r -= wi;
696        if r <= 0.0 {
697            return i as u32;
698        }
699    }
700    *idx.last().unwrap() as u32
701}
702
703// ───────────────────────────── the conversation ─────────────────────────────
704
705/// How a conversation is sampled (the `DuplexConfig` defaults).
706#[derive(Clone, Debug)]
707pub struct Options {
708    pub guidance: Option<f32>,
709    pub temperature: f32,
710    pub top_k: usize,
711    pub dry: Option<Dry>,
712    pub eop_bias: f32,
713    pub speak_first: bool,
714    pub seed: u64,
715}
716
717impl Default for Options {
718    fn default() -> Self {
719        Self { guidance: None, temperature: 0.7, top_k: 25, dry: Some(Dry::default()), eop_bias: 0.0, speak_first: false, seed: 0 }
720    }
721}
722
723/// The model's side of a conversation.
724pub struct Reply {
725    pub audio: Vec<f32>,
726    /// Per frame: the new text (`" "` for a run of silent frames).
727    pub text: Vec<String>,
728    pub frames: usize,
729    pub step_ms: Vec<f64>,
730}
731
732/// Everything besides the language model.
733pub struct Haru {
734    pub cfg: HaruConfig,
735    pub codec: Codec,
736    head: Head,
737    model_proj: Projector,
738    user_proj: Projector,
739    latent_scale: f32,
740    latent_bias: f32,
741    pool: Option<Arc<Pool>>,
742}
743
744impl Haru {
745    pub fn from_model(model: &CmfModel, pool: Option<Arc<Pool>>) -> Result<Self, String> {
746        let cfg = HaruConfig::from_model(model)?;
747        let one = |n: &str| -> Result<f32, String> {
748            let v = crate::dit::cmf_f32(model, n)?;
749            v.first().copied().ok_or_else(|| format!("{n}: empty"))
750        };
751        Ok(Self {
752            codec: Codec::from_model(model, &cfg, pool.clone())?,
753            head: Head::from_model(model, &cfg, pool.clone())?,
754            model_proj: Projector::load(model, "haru.model_audio_proj", cfg.latent_dim, cfg.hidden)?,
755            user_proj: Projector::load(model, "haru.user_audio_proj", cfg.latent_dim, cfg.hidden)?,
756            latent_scale: one("haru.latent_scale")?,
757            latent_bias: one("haru.latent_bias")?,
758            cfg,
759            pool,
760        })
761    }
762
763    fn scaled(&self, raw: &[f32]) -> Vec<f32> {
764        raw.iter().map(|&v| (v + self.latent_bias) * self.latent_scale).collect()
765    }
766
767    fn unscaled(&self, n: &[f32]) -> Vec<f32> {
768        n.iter().map(|&v| v / self.latent_scale - self.latent_bias).collect()
769    }
770
771    /// A position's input: the token's embedding plus each projected stream.
772    fn row(&self, pipe: &Pipeline, token: u32, model_latent: Option<&[f32]>, user_latent: Option<&[f32]>) -> Vec<f32> {
773        let pool = self.pool.as_deref();
774        let mut x = pipe.embed_id(token);
775        for (proj, lat) in [(&self.model_proj, model_latent), (&self.user_proj, user_latent)] {
776            if let Some(l) = lat {
777                let y = proj.apply(&self.scaled(l), 1, pool);
778                for (a, b) in x.iter_mut().zip(&y) {
779                    *a += b;
780                }
781            }
782        }
783        x
784    }
785
786    /// Play `user` (mono 24 kHz) to the model frame by frame, as in a live
787    /// call, and return what it says over the same span (`haru-inference`).
788    pub fn converse(
789        &self,
790        pipe: &mut Pipeline,
791        system_prompt: &str,
792        reference: Option<&[f32]>,
793        user: &[f32],
794        o: &Options,
795    ) -> Result<Reply, String> {
796        let cfg = &self.cfg;
797        let (fs, ld) = (cfg.frame_samples, cfg.latent_dim);
798        let mut rng = SplitMix64::new(o.seed);
799        let guidance = o.guidance.unwrap_or(cfg.guidance);
800        let steps = cfg.num_steps.max(1);
801        let scalars: Vec<Vec<f32>> = (0..steps).map(|i| self.head.scalars(i as f32 / steps as f32, 1.0 / steps as f32, guidance)).collect();
802        // ── the prompt: the card, the reference on the model's stream, the grid
803        let card: Vec<u32> = if system_prompt.is_empty() {
804            Vec::new()
805        } else {
806            pipe.tokenizer.encode(&format!("<|im_start|>system\n{system_prompt}<|im_end|>\n"))
807        };
808        let (ref_lat, ref_raw) = match reference.filter(|r| !r.is_empty()) {
809            Some(r) => (Some(self.codec.sample(&self.codec.encode(r), &mut rng)), Some(r)),
810            None => (None, None),
811        };
812        let n_ref = ref_lat.as_ref().map_or(0, |l| l.len() / ld);
813        let mut grid: Vec<u32> = if o.speak_first { vec![cfg.pad, cfg.eop] } else { Vec::new() };
814        if card.is_empty() && n_ref == 0 && grid.is_empty() {
815            grid.push(cfg.pad);
816        }
817        let mut tokens = card.clone();
818        if n_ref > 0 {
819            tokens.extend(std::iter::repeat_n(cfg.pad, n_ref - 1));
820            tokens.push(cfg.eop);
821        }
822        tokens.extend(&grid);
823        let (n, n_card, n_grid) = (tokens.len(), card.len(), grid.len());
824        let silence = self.codec.silence();
825        // the speaker's noise floor: the reference's quietest whole frame
826        let room = match (&ref_lat, ref_raw) {
827            (Some(l), Some(r)) if r.len() >= fs => {
828                let whole = r.len() / fs;
829                let quiet = (0..whole)
830                    .min_by(|&a, &b| {
831                        let e = |i: usize| r[i * fs..(i + 1) * fs].iter().map(|v| v * v).sum::<f32>();
832                        e(a).total_cmp(&e(b))
833                    })
834                    .unwrap_or(0);
835                l[quiet * ld..(quiet + 1) * ld].to_vec()
836            }
837            _ => silence.clone(),
838        };
839        let mut rows = Vec::with_capacity(n * cfg.hidden);
840        for (i, &tok) in tokens.iter().enumerate() {
841            let model_lat: Option<Vec<f32>> = if i < n_card {
842                None
843            } else if i < n_card + n_ref {
844                ref_lat.as_ref().map(|l| l[(i - n_card) * ld..(i - n_card + 1) * ld].to_vec())
845            } else if i >= n - n_grid {
846                Some(room.clone())
847            } else {
848                Some(vec![0f32; ld])
849            };
850            let user_lat = (i >= n - n_grid).then(|| silence.clone());
851            rows.extend(self.row(pipe, tok, model_lat.as_deref(), user_lat.as_deref()));
852        }
853        let dummy = vec![0u32; n];
854        let t0 = std::time::Instant::now();
855        let h = pipe.speech_prefill(&dummy, Some(&rows))?;
856        let logits = pipe.speech_logits(&h);
857        // ── the user's latents: the whole recording encoded once (the codec
858        // is causal), each frame drawn with its own noise scale as the
859        // stream's per-frame calls do
860        let count = user.len().div_ceil(fs).max(1);
861        let mut padded = user.to_vec();
862        padded.resize(count * fs, 0.0);
863        let user_means = self.codec.encode(&padded);
864        let mut state = Emit { history: Vec::new(), force_text: usize::from(o.speak_first), pending: Vec::new(), in_gap: false };
865        let mut reply = Reply { audio: Vec::new(), text: Vec::new(), frames: 0, step_ms: Vec::new() };
866        let mut latents: Vec<f32> = Vec::with_capacity(count * ld);
867        let (mut token, mut latent) = self.emit(pipe, &h, logits, &scalars, o, &mut state, &mut rng, &mut reply);
868        reply.step_ms.push(t0.elapsed().as_secs_f64() * 1e3);
869        latents.extend(&latent);
870        let mut pos = n;
871        for f in 0..count - 1 {
872            let t = std::time::Instant::now();
873            let ul = self.codec.sample(&user_means[f * ld..(f + 1) * ld], &mut rng);
874            let row = self.row(pipe, token, Some(&latent), Some(&ul));
875            let (h, logits) = pipe.speech_step_logits(&row, pos);
876            pos += 1;
877            (token, latent) = self.emit(pipe, &h, logits, &scalars, o, &mut state, &mut rng, &mut reply);
878            latents.extend(&latent);
879            reply.step_ms.push(t.elapsed().as_secs_f64() * 1e3);
880        }
881        reply.frames = count;
882        reply.audio = self.codec.decode(&latents);
883        Ok(reply)
884    }
885
886    /// The next frame's text token and audio latent (raw codec space).
887    #[allow(clippy::too_many_arguments)]
888    fn emit(
889        &self,
890        pipe: &Pipeline,
891        hidden: &[f32],
892        mut logits: Vec<f32>,
893        scalars: &[Vec<f32>],
894        o: &Options,
895        st: &mut Emit,
896        rng: &mut SplitMix64,
897        reply: &mut Reply,
898    ) -> (u32, Vec<f32>) {
899        let cfg = &self.cfg;
900        let silent = [cfg.pad, cfg.eop];
901        if let Some(d) = &o.dry {
902            for (t, p) in dry_penalties(&st.history, d) {
903                if !silent.contains(&t) && Some(t) != cfg.eos {
904                    logits[t as usize] -= p;
905                }
906            }
907        }
908        // PAD / EOP (stay silent or start speaking) in float32 against the
909        // exact embedding rows: the decision is often closer than the
910        // device head's resolution
911        for &t in &silent {
912            let e = pipe.embed_id(t);
913            logits[t as usize] = hidden.iter().zip(&e).map(|(a, b)| a * b).sum();
914        }
915        logits[cfg.eop as usize] += o.eop_bias;
916        if st.force_text > 0 {
917            for t in silent.iter().copied().chain(cfg.eos) {
918                logits[t as usize] = f32::NEG_INFINITY;
919            }
920            st.force_text -= 1;
921        }
922        let token = sample_token(&logits, o.temperature, o.top_k, rng);
923        let noise: Vec<f32> = (0..cfg.latent_dim).map(|_| normal(rng)).collect();
924        let latent = self.unscaled(&self.head.sample(hidden, &noise, scalars));
925        if !silent.contains(&token) && Some(token) != cfg.eos {
926            st.history.push(token);
927            let keep = o.dry.map_or(usize::MAX, |d| d.lookback + d.max_match_length + 1);
928            if st.history.len() > keep {
929                let drop = st.history.len() - keep;
930                st.history.drain(..drop);
931            }
932        }
933        // the frame's text: a run of silent frames is one space, a character
934        // waits for all of its tokens
935        let text = if silent.contains(&token) {
936            if st.in_gap {
937                String::new()
938            } else {
939                st.in_gap = true;
940                " ".into()
941            }
942        } else {
943            st.in_gap = false;
944            // the token's own bytes (its leading space kept), a character
945            // split over tokens held back until it is whole
946            pipe.tokenizer.decode_token_stream(token, &mut st.pending)
947        };
948        reply.text.push(text);
949        (token, latent)
950    }
951}
952
953struct Emit {
954    history: Vec<u32>,
955    force_text: usize,
956    pending: Vec<u8>,
957    in_gap: bool,
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963
964    /// DRY penalizes the token that would extend a repeat, harder for a
965    /// longer one.
966    #[test]
967    fn dry_penalizes_repeats() {
968        let d = Dry::default();
969        // … 5 6 7 … 5 6: 7 would repeat a run of two
970        let h = [1u32, 5, 6, 7, 2, 3, 5, 6];
971        let p = dry_penalties(&h, &d);
972        let p7 = p.iter().find(|(t, _)| *t == 7).map(|x| x.1).unwrap();
973        assert!((p7 - 0.8 * 1.75).abs() < 1e-5, "{p7}");
974    }
975
976    /// A temperature of zero is the argmax.
977    #[test]
978    fn greedy_token() {
979        let mut rng = SplitMix64::new(3);
980        assert_eq!(sample_token(&[0.1, 2.0, 1.0], 0.0, 25, &mut rng), 1);
981    }
982}