Skip to main content

cortiq_engine/
moss_image.rs

1//! Native MOSS-Image denoiser.
2//!
3//! MOSS-Image is deliberately not routed through Z-Image: its 42 blocks use
4//! joint [image,text] attention, four-axis RoPE, six-way AdaRMS modulation
5//! and SiTU.  This module keeps source tensor suffixes under `moss.` and
6//! uses CMF's mapped quantized projections.  The hot dense products therefore
7//! use the existing q4tp/q8 device path on Metal/Vulkan, while the portable
8//! f32 implementation remains an exact-shape fallback.
9
10use crate::dit::{Proj, cmf_f32};
11use crate::pool::Pool;
12use cortiq_core::CmfModel;
13use std::sync::Arc;
14
15/// Native MOSS transformer geometry, read from the source config stored in
16/// `moss.config_json`.
17#[derive(Clone, Debug)]
18pub struct MossConfig {
19    pub dim: usize,
20    pub ffn_dim: usize,
21    pub freq_dim: usize,
22    pub latent_channels: usize,
23    pub num_heads: usize,
24    pub num_layers: usize,
25    pub text_dim: usize,
26    pub rope_base: f64,
27}
28
29impl MossConfig {
30    pub fn from_json(v: &serde_json::Value) -> Result<Self, String> {
31        let u = |name: &str| -> Result<usize, String> {
32            v[name]
33                .as_u64()
34                .map(|v| v as usize)
35                .ok_or_else(|| format!("MOSS config missing integer {name}"))
36        };
37        let dim = u("dim")?;
38        let num_heads = u("num_heads")?;
39        let freq_dim = u("freq_dim")?;
40        if dim == 0 || num_heads == 0 || dim % num_heads != 0 || (dim / num_heads) % 8 != 0 {
41            return Err(format!(
42                "invalid MOSS dim/head geometry: dim={dim}, num_heads={num_heads}"
43            ));
44        }
45        if freq_dim == 0 || freq_dim % 2 != 0 {
46            return Err(format!(
47                "MOSS freq_dim must be positive and even, got {freq_dim}"
48            ));
49        }
50        Ok(Self {
51            dim,
52            ffn_dim: u("ffn_dim")?,
53            freq_dim,
54            latent_channels: u("latent_channels")?,
55            num_heads,
56            num_layers: u("num_layers")?,
57            text_dim: u("text_dim")?,
58            rope_base: v["rope_base"].as_f64().unwrap_or(10_000.0),
59        })
60    }
61
62    pub fn head_dim(&self) -> usize {
63        self.dim / self.num_heads
64    }
65}
66
67struct TextBlock {
68    norm1: Vec<f32>,
69    norm2: Vec<f32>,
70    q_norm: Vec<f32>,
71    k_norm: Vec<f32>,
72    qkv: Proj,
73    qkv_b: Vec<f32>,
74    proj: Proj,
75    proj_b: Vec<f32>,
76    ffn_gate: Proj,
77    ffn_gate_b: Vec<f32>,
78    ffn_up: Proj,
79    ffn_up_b: Vec<f32>,
80    ffn_down: Proj,
81    ffn_down_b: Vec<f32>,
82}
83
84struct Block {
85    norm1: Vec<f32>,
86    norm2: Vec<f32>,
87    q_norm: Vec<f32>,
88    k_norm: Vec<f32>,
89    q: Proj,
90    k: Proj,
91    v: Proj,
92    o: Proj,
93    ffn_up_gate: Proj,
94    ffn_down: Proj,
95}
96
97/// The MOSS DiT loaded directly from one CMF.  Quantized projection tensors
98/// remain mmap-backed, rather than being expanded to f32 at load time.
99pub struct MossDit {
100    pub cfg: MossConfig,
101    video_embedder: Proj,
102    video_embedder_b: Vec<f32>,
103    text_proj: Proj,
104    text_proj_b: Vec<f32>,
105    text_blocks: Vec<TextBlock>,
106    time_0_w: Vec<f32>,
107    time_0_b: Vec<f32>,
108    time_2_w: Vec<f32>,
109    time_2_b: Vec<f32>,
110    shared_mod_w: Vec<f32>,
111    shared_mod_b: Vec<f32>,
112    head_mod_w: Vec<f32>,
113    head_mod_b: Vec<f32>,
114    layers: Vec<Block>,
115    final_norm_video: Vec<f32>,
116    final_linear_video: Proj,
117    pool: Option<Arc<Pool>>,
118}
119
120impl MossDit {
121    /// Load the MOSS DiT from `moss.*` tensors in a packaged model.
122    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<Self, String> {
123        let cfg: serde_json::Value = serde_json::from_slice(
124            model
125                .tensor_bytes("moss.config_json")
126                .map_err(|e| e.to_string())?,
127        )
128        .map_err(|e| format!("moss.config_json: {e}"))?;
129        let cfg = MossConfig::from_json(&cfg)?;
130        let f = |suffix: &str| cmf_f32(model, &format!("moss.{suffix}"));
131        let p = |suffix: &str| Proj::from_model(model, &format!("moss.{suffix}"));
132        let text_blocks = (0..2)
133            .map(|i| {
134                let x = format!("text_embedder.blocks.{i}");
135                Ok(TextBlock {
136                    norm1: f(&format!("{x}.norm1.weight"))?,
137                    norm2: f(&format!("{x}.norm2.weight"))?,
138                    q_norm: f(&format!("{x}.q_norm.weight"))?,
139                    k_norm: f(&format!("{x}.k_norm.weight"))?,
140                    qkv: p(&format!("{x}.qkv.weight"))?,
141                    qkv_b: f(&format!("{x}.qkv.bias"))?,
142                    proj: p(&format!("{x}.proj.weight"))?,
143                    proj_b: f(&format!("{x}.proj.bias"))?,
144                    ffn_gate: p(&format!("{x}.ffn_gate.weight"))?,
145                    ffn_gate_b: f(&format!("{x}.ffn_gate.bias"))?,
146                    ffn_up: p(&format!("{x}.ffn_up.weight"))?,
147                    ffn_up_b: f(&format!("{x}.ffn_up.bias"))?,
148                    ffn_down: p(&format!("{x}.ffn_down.weight"))?,
149                    ffn_down_b: f(&format!("{x}.ffn_down.bias"))?,
150                })
151            })
152            .collect::<Result<Vec<_>, String>>()?;
153        let layers = (0..cfg.num_layers)
154            .map(|i| {
155                let x = format!("layers.{i}");
156                Ok(Block {
157                    norm1: f(&format!("{x}.norm1.weight"))?,
158                    norm2: f(&format!("{x}.norm2.weight"))?,
159                    q_norm: f(&format!("{x}.q_norm.weight"))?,
160                    k_norm: f(&format!("{x}.k_norm.weight"))?,
161                    q: p(&format!("{x}.proj.q.weight"))?,
162                    k: p(&format!("{x}.proj.k.weight"))?,
163                    v: p(&format!("{x}.proj.v.weight"))?,
164                    o: p(&format!("{x}.proj.o.weight"))?,
165                    ffn_up_gate: p(&format!("{x}.proj.ffn_up_gate.weight"))?,
166                    ffn_down: p(&format!("{x}.proj.ffn_down.weight"))?,
167                })
168            })
169            .collect::<Result<Vec<_>, String>>()?;
170        let dit = Self {
171            video_embedder: p("video_embedder.weight")?,
172            video_embedder_b: f("video_embedder.bias")?,
173            text_proj: p("text_embedder.proj.weight")?,
174            text_proj_b: f("text_embedder.proj.bias")?,
175            time_0_w: f("time_embedding.0.weight")?,
176            time_0_b: f("time_embedding.0.bias")?,
177            time_2_w: f("time_embedding.2.weight")?,
178            time_2_b: f("time_embedding.2.bias")?,
179            shared_mod_w: f("shared_block_modulation.weight")?,
180            shared_mod_b: f("shared_block_modulation.bias")?,
181            head_mod_w: f("video_head_modulation.weight")?,
182            head_mod_b: f("video_head_modulation.bias")?,
183            final_norm_video: f("final_norm_video.weight")?,
184            final_linear_video: p("final_linear_video.weight")?,
185            text_blocks,
186            layers,
187            pool: Pool::from_env(),
188            cfg,
189        };
190        dit.validate()?;
191        Ok(dit)
192    }
193
194    fn validate(&self) -> Result<(), String> {
195        let d = self.cfg.dim;
196        if self.layers.len() != self.cfg.num_layers || self.text_blocks.len() != 2 {
197            return Err("MOSS block count mismatch".into());
198        }
199        if self.video_embedder.cols() != self.cfg.latent_channels
200            || self.video_embedder.rows() != d
201            || self.text_proj.cols() != self.cfg.text_dim
202            || self.text_proj.rows() != d
203            || self.final_linear_video.cols() != d
204            || self.final_linear_video.rows() != self.cfg.latent_channels
205            || self.final_norm_video.len() != d
206        {
207            return Err("MOSS top-level projection geometry mismatch".into());
208        }
209        if self.shared_mod_w.len() != 6 * d * d || self.shared_mod_b.len() != 6 * d {
210            return Err("MOSS shared modulation geometry mismatch".into());
211        }
212        if self.head_mod_w.len() != 2 * d * d || self.head_mod_b.len() != 2 * d {
213            return Err("MOSS head modulation geometry mismatch".into());
214        }
215        Ok(())
216    }
217
218    fn pool(&self) -> Option<&Pool> {
219        self.pool.as_deref()
220    }
221
222    /// Prepare the encoder's final Qwen3.5 hidden states once per prompt.
223    /// MOSS's text projection/refiner does not depend on the latent or the
224    /// timestep, so retaining this result avoids repeating two blocks on
225    /// every CFG/denoising forward.
226    pub fn prepare_text(&self, text: &[f32], tokens: usize) -> Result<Vec<f32>, String> {
227        if tokens == 0 || text.len() != tokens * self.cfg.text_dim {
228            return Err(format!(
229                "MOSS text conditioning has {} values for {tokens} tokens of width {}",
230                text.len(),
231                self.cfg.text_dim
232            ));
233        }
234        let mut x = linear(
235            &self.text_proj,
236            text,
237            tokens,
238            Some(&self.text_proj_b),
239            self.pool(),
240        );
241        let rope = Rope::new(&self.cfg, 0, 0, tokens);
242        for b in &self.text_blocks {
243            text_block(b, &mut x, tokens, &rope, &self.cfg, self.pool());
244        }
245        Ok(x)
246    }
247
248    /// One MOSS velocity forward.  `latents` is channels-first
249    /// `[latent_channels, h, w]`; `text` is the result of
250    /// [`Self::prepare_text`].  Passing a skip set reproduces MOSS's
251    /// negative-branch layer skip without changing sequence geometry.
252    pub fn forward(
253        &self,
254        latents: &[f32],
255        h: usize,
256        w: usize,
257        timestep: f32,
258        text: &[f32],
259        text_tokens: usize,
260        skip_layers: &[usize],
261    ) -> Result<Vec<f32>, String> {
262        if h == 0 || w == 0 || latents.len() != self.cfg.latent_channels * h * w {
263            return Err("MOSS latent shape is not [C,H,W]".into());
264        }
265        if text_tokens == 0 || text.len() != text_tokens * self.cfg.dim {
266            return Err("MOSS prepared text shape mismatch".into());
267        }
268        if skip_layers.iter().any(|&i| i >= self.layers.len()) {
269            return Err("MOSS skip layer out of range".into());
270        }
271        let image_tokens = h * w;
272        let mut image_in = vec![0f32; image_tokens * self.cfg.latent_channels];
273        for token in 0..image_tokens {
274            for c in 0..self.cfg.latent_channels {
275                image_in[token * self.cfg.latent_channels + c] = latents[c * image_tokens + token];
276            }
277        }
278        let video = linear(
279            &self.video_embedder,
280            &image_in,
281            image_tokens,
282            Some(&self.video_embedder_b),
283            self.pool(),
284        );
285        let mut x = Vec::with_capacity((image_tokens + text_tokens) * self.cfg.dim);
286        x.extend_from_slice(&video);
287        x.extend_from_slice(text);
288        let rope = Rope::new(&self.cfg, h, w, text_tokens);
289        let time = self.time_embedding(timestep);
290        let modulation = linear_small(&time, &self.shared_mod_w, &self.shared_mod_b);
291        let head = linear_small(&time, &self.head_mod_w, &self.head_mod_b);
292        let chained = self.chain(&mut x, image_tokens + text_tokens, &rope, &modulation, skip_layers);
293        for (i, block) in self.layers.iter().enumerate() {
294            if !chained && !skip_layers.contains(&i) {
295                main_block(
296                    block,
297                    &mut x,
298                    image_tokens + text_tokens,
299                    &rope,
300                    &modulation,
301                    &self.cfg,
302                    self.pool(),
303                );
304            }
305        }
306        let d = self.cfg.dim;
307        let mut image = x[..image_tokens * d].to_vec();
308        rms_rows_inplace(
309            &mut image,
310            image_tokens,
311            d,
312            &self.final_norm_video,
313            None,
314            None,
315            self.pool(),
316        );
317        let (shift, scale) = (&head[..d], &head[d..]);
318        for row in image.chunks_exact_mut(d) {
319            for ((v, &s), &a) in row.iter_mut().zip(scale).zip(shift) {
320                *v = *v * (1.0 + s) + a;
321            }
322        }
323        let out = linear(
324            &self.final_linear_video,
325            &image,
326            image_tokens,
327            None,
328            self.pool(),
329        );
330        let mut velocity = vec![0f32; self.cfg.latent_channels * image_tokens];
331        for token in 0..image_tokens {
332            for c in 0..self.cfg.latent_channels {
333                velocity[c * image_tokens + token] = out[token * self.cfg.latent_channels + c];
334            }
335        }
336        Ok(velocity)
337    }
338
339    /// Every block but the skipped ones on the card in one call
340    /// (`gpu::moss_chain`); `false`: nothing was written. `CMF_MOSS_CHAIN=0`
341    /// keeps the per-operation blocks.
342    fn chain(&self, x: &mut [f32], n: usize, rope: &Rope, modulation: &[f32], skip: &[usize]) -> bool {
343        if !crate::gpu::enabled_here() || crate::gpu::mm_killed() || std::env::var("CMF_MOSS_CHAIN").as_deref() == Ok("0") {
344            return false;
345        }
346        let hd = self.cfg.head_dim();
347        let half = hd / 2;
348        let mut model: Option<Arc<CmfModel>> = None;
349        let mut blocks = Vec::with_capacity(self.layers.len());
350        for (i, b) in self.layers.iter().enumerate() {
351            if skip.contains(&i) {
352                continue;
353            }
354            let mut ix = [0usize; 6];
355            for (slot, p) in ix.iter_mut().zip([&b.q, &b.k, &b.v, &b.o, &b.ffn_up_gate, &b.ffn_down]) {
356                let Some((m, g)) = p.graph_w() else { return false };
357                if model.as_ref().is_some_and(|have| !Arc::ptr_eq(have, m)) {
358                    return false;
359                }
360                model.get_or_insert_with(|| m.clone());
361                *slot = g.idx;
362            }
363            blocks.push(crate::gpu::MossChainBlock {
364                norm1: &b.norm1,
365                norm2: &b.norm2,
366                q_norm: &b.q_norm,
367                k_norm: &b.k_norm,
368                q: ix[0],
369                k: ix[1],
370                v: ix[2],
371                o: ix[3],
372                up_gate: ix[4],
373                down: ix[5],
374            });
375        }
376        let Some(model) = model else { return false };
377        // the rotation's first halves (the second repeats them)
378        let mut cos = vec![0f32; n * half];
379        let mut sin = vec![0f32; n * half];
380        for t in 0..n {
381            cos[t * half..(t + 1) * half].copy_from_slice(&rope.cos[t * hd..t * hd + half]);
382            sin[t * half..(t + 1) * half].copy_from_slice(&rope.sin[t * hd..t * hd + half]);
383        }
384        let mut args = crate::gpu::MossChainArgs {
385            x,
386            tokens: n,
387            heads: self.cfg.num_heads,
388            head_dim: hd,
389            modulation,
390            cos: &cos,
391            sin: &sin,
392            blocks: &blocks,
393        };
394        crate::gpu::moss_chain(&model, &mut args)
395    }
396
397    fn time_embedding(&self, t: f32) -> Vec<f32> {
398        // The source deliberately computes phase in f64, then sends the
399        // concatenated [cos, sin] embedding through f32 Linear modules.
400        let half = self.cfg.freq_dim / 2;
401        let mut input = vec![0f32; self.cfg.freq_dim];
402        for i in 0..half {
403            let freq = self.cfg.rope_base.powf(-(i as f64) / half as f64);
404            let p = t as f64 * freq;
405            input[i] = p.cos() as f32;
406            input[half + i] = p.sin() as f32;
407        }
408        let mut h = linear_small(&input, &self.time_0_w, &self.time_0_b);
409        for v in &mut h {
410            *v = silu(*v);
411        }
412        linear_small(&h, &self.time_2_w, &self.time_2_b)
413    }
414}
415
416/// Four-axis MOSS RoPE, represented as fully expanded sin/cos factors for
417/// source `_rotate`: the first 64 dimensions rotate the first half, and the
418/// same factors repeat for the second half.
419struct Rope {
420    sin: Vec<f32>,
421    cos: Vec<f32>,
422}
423
424impl Rope {
425    fn new(cfg: &MossConfig, h: usize, w: usize, text_len: usize) -> Self {
426        let hd = cfg.head_dim();
427        let bands = hd / 8;
428        let n_img = h * w;
429        let n = n_img + text_len;
430        let mut sin = vec![0f32; n * hd];
431        let mut cos = vec![0f32; n * hd];
432        for token in 0..n {
433            let coords = if token < n_img {
434                let yy = token / w;
435                let xx = token % w;
436                [
437                    0.0,
438                    text_len as f64,
439                    yy as f64 - (h.saturating_sub(1) as f64) / 2.0,
440                    xx as f64 - (w.saturating_sub(1) as f64) / 2.0,
441                ]
442            } else {
443                [0.0, (token - n_img) as f64, 0.0, 0.0]
444            };
445            for axis in 0..4 {
446                for band in 0..bands {
447                    let freq = 1.0 / cfg.rope_base.powf(band as f64 / bands as f64);
448                    let phase = coords[axis] * freq;
449                    let j = axis * bands + band;
450                    sin[token * hd + j] = phase.sin() as f32;
451                    cos[token * hd + j] = phase.cos() as f32;
452                    sin[token * hd + hd / 2 + j] = phase.sin() as f32;
453                    cos[token * hd + hd / 2 + j] = phase.cos() as f32;
454                }
455            }
456        }
457        Self { sin, cos }
458    }
459}
460
461// ── portable f32 kernels ────────────────────────────────────────────────
462
463struct SendRows(*mut f32);
464unsafe impl Send for SendRows {}
465unsafe impl Sync for SendRows {}
466impl SendRows {
467    /// SAFETY: callers divide the buffer into non-overlapping row ranges.
468    ///
469    /// The `&self` receiver is deliberate: the wrapper is shared across
470    /// worker closures (`Sync`) while each call carves out a disjoint slice
471    /// of the same backing buffer, so no two live `&mut` ever alias —
472    /// exactly the case `mut_from_ref` cannot see through.
473    #[allow(clippy::mut_from_ref)]
474    unsafe fn row(&self, off: usize, len: usize) -> &mut [f32] {
475        unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
476    }
477}
478
479fn rows(pool: Option<&Pool>, n: usize, f: &(dyn Fn(usize, usize) + Sync)) {
480    match pool {
481        Some(p) => p.run_rows(n, f),
482        None => f(0, n),
483    }
484}
485
486fn silu(x: f32) -> f32 {
487    x / (1.0 + (-x).exp())
488}
489
490fn situ(hidden: f32, gate: f32) -> f32 {
491    (4.0 * (gate / 4.0).tanh() * gate.sigmoid()) * (25.0 * (hidden / 25.0).tanh())
492}
493
494trait Sigmoid {
495    fn sigmoid(self) -> Self;
496}
497impl Sigmoid for f32 {
498    fn sigmoid(self) -> Self {
499        1.0 / (1.0 + (-self).exp())
500    }
501}
502
503fn linear_small(x: &[f32], w: &[f32], bias: &[f32]) -> Vec<f32> {
504    assert_eq!(w.len() % x.len(), 0, "small MOSS linear geometry");
505    let rows = w.len() / x.len();
506    assert_eq!(bias.len(), rows, "small MOSS linear bias geometry");
507    w.chunks_exact(x.len())
508        .zip(bias)
509        .map(|(r, &b)| b + r.iter().zip(x).map(|(&a, &v)| a * v).sum::<f32>())
510        .collect()
511}
512
513fn linear(p: &Proj, x: &[f32], n: usize, bias: Option<&[f32]>, pool: Option<&Pool>) -> Vec<f32> {
514    assert_eq!(x.len(), n * p.cols(), "MOSS projection input geometry");
515    let mut out = vec![0f32; n * p.rows()];
516    p.matmat(x, n, &mut out, pool);
517    if let Some(b) = bias {
518        assert_eq!(b.len(), p.rows(), "MOSS projection bias geometry");
519        for row in out.chunks_exact_mut(p.rows()) {
520            for (v, &b) in row.iter_mut().zip(b) {
521                *v += b;
522            }
523        }
524    }
525    out
526}
527
528/// Plain Diffusers RMSNorm, optionally affine-modulated after normalization.
529fn rms_rows_inplace(
530    x: &mut [f32],
531    n: usize,
532    d: usize,
533    weight: &[f32],
534    scale: Option<&[f32]>,
535    shift: Option<&[f32]>,
536    pool: Option<&Pool>,
537) {
538    assert_eq!(x.len(), n * d);
539    assert_eq!(weight.len(), d);
540    if let Some(s) = scale {
541        assert_eq!(s.len(), d);
542    }
543    if let Some(s) = shift {
544        assert_eq!(s.len(), d);
545    }
546    let ptr = SendRows(x.as_mut_ptr());
547    rows(pool, n, &|lo, hi| {
548        for r in lo..hi {
549            // SAFETY: each worker owns distinct row indices.
550            let row = unsafe { ptr.row(r * d, d) };
551            let mean = row.iter().map(|&v| v * v).sum::<f32>() / d as f32;
552            let inv = 1.0 / (mean + 1e-6).sqrt();
553            for j in 0..d {
554                let mut v = row[j] * inv * weight[j];
555                if let Some(s) = scale {
556                    v *= 1.0 + s[j];
557                }
558                if let Some(a) = shift {
559                    v += a[j];
560                }
561                row[j] = v;
562            }
563        }
564    });
565}
566
567fn qk_norm_rope(
568    q: &mut [f32],
569    n: usize,
570    heads: usize,
571    hd: usize,
572    weight: &[f32],
573    rope: &Rope,
574    pool: Option<&Pool>,
575) {
576    assert_eq!(q.len(), n * heads * hd);
577    assert_eq!(weight.len(), hd);
578    let ptr = SendRows(q.as_mut_ptr());
579    rows(pool, n, &|lo, hi| {
580        for t in lo..hi {
581            for h in 0..heads {
582                // SAFETY: distinct token ranges are disjoint.
583                let row = unsafe { ptr.row((t * heads + h) * hd, hd) };
584                let mean = row.iter().map(|&v| v * v).sum::<f32>() / hd as f32;
585                let inv = 1.0 / (mean + 1e-6).sqrt();
586                for j in 0..hd {
587                    row[j] *= inv * weight[j];
588                }
589                for j in 0..hd / 2 {
590                    let a = row[j];
591                    let b = row[j + hd / 2];
592                    let c = rope.cos[t * hd + j];
593                    let s = rope.sin[t * hd + j];
594                    row[j] = a * c - b * s;
595                    row[j + hd / 2] = b * c + a * s;
596                }
597            }
598        }
599    });
600}
601
602fn softmax(row: &mut [f32]) {
603    let max = row.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
604    let mut sum = 0.0f32;
605    for v in row.iter_mut() {
606        *v = (*v - max).exp();
607        sum += *v;
608    }
609    if sum > 0.0 {
610        for v in row.iter_mut() {
611            *v /= sum;
612        }
613    }
614}
615
616/// Full bidirectional attention.  The GPU path consumes head-major q/k/v
617/// planes and returns token-major rows; portable fallback holds one score
618/// matrix per head (never one per layer) to bound memory.
619fn attention(
620    q: &[f32],
621    k: &[f32],
622    v: &[f32],
623    n: usize,
624    heads: usize,
625    hd: usize,
626    pool: Option<&Pool>,
627) -> Vec<f32> {
628    let hidden = heads * hd;
629    let mut qh = vec![0f32; heads * n * hd];
630    let mut kh = vec![0f32; heads * n * hd];
631    let mut vh = vec![0f32; heads * n * hd];
632    for t in 0..n {
633        for h in 0..heads {
634            let src = &q[(t * heads + h) * hd..(t * heads + h + 1) * hd];
635            qh[(h * n + t) * hd..(h * n + t + 1) * hd].copy_from_slice(src);
636            let src = &k[(t * heads + h) * hd..(t * heads + h + 1) * hd];
637            kh[(h * n + t) * hd..(h * n + t + 1) * hd].copy_from_slice(src);
638            let src = &v[(t * heads + h) * hd..(t * heads + h + 1) * hd];
639            vh[(h * n + t) * hd..(h * n + t + 1) * hd].copy_from_slice(src);
640        }
641    }
642    let mut out = vec![0f32; n * hidden];
643    if n >= 128
644        && crate::gpu::enabled_here()
645        && !crate::gpu::mm_killed()
646        && crate::gpu::dit_attention(
647            &qh,
648            &kh,
649            &vh,
650            heads,
651            heads,
652            n,
653            hd,
654            1.0 / (hd as f32).sqrt(),
655            &mut out,
656        )
657    {
658        return out;
659    }
660    let mut scores = vec![0f32; n * n];
661    let mut vals_t = vec![0f32; hd * n];
662    let mut head_out = vec![0f32; n * hd];
663    for h in 0..heads {
664        let qs = &qh[h * n * hd..(h + 1) * n * hd];
665        let ks = &kh[h * n * hd..(h + 1) * n * hd];
666        let vs = &vh[h * n * hd..(h + 1) * n * hd];
667        // GEMM wants the right operand laid out by output row.  Each score
668        // row is q[t] dot k[j], so transpose logically into k's rows works.
669        crate::fcd_ops::gemm_nt(qs, ks, &mut scores, n, hd, n, pool);
670        let sp = SendRows(scores.as_mut_ptr());
671        rows(pool, n, &|lo, hi| {
672            for r in lo..hi {
673                // SAFETY: row ranges do not overlap.
674                softmax(unsafe { sp.row(r * n, n) });
675            }
676        });
677        for d in 0..hd {
678            for t in 0..n {
679                vals_t[d * n + t] = vs[t * hd + d];
680            }
681        }
682        crate::fcd_ops::gemm_nt(&scores, &vals_t, &mut head_out, n, n, hd, pool);
683        for t in 0..n {
684            out[t * hidden + h * hd..t * hidden + (h + 1) * hd]
685                .copy_from_slice(&head_out[t * hd..(t + 1) * hd]);
686        }
687    }
688    out
689}
690
691fn text_block(
692    b: &TextBlock,
693    x: &mut [f32],
694    n: usize,
695    rope: &Rope,
696    cfg: &MossConfig,
697    pool: Option<&Pool>,
698) {
699    let d = cfg.dim;
700    let mut norm = x.to_vec();
701    rms_rows_inplace(&mut norm, n, d, &b.norm1, None, None, pool);
702    let qkv = linear(&b.qkv, &norm, n, Some(&b.qkv_b), pool);
703    let mut q = qkv[..n * d].to_vec();
704    let mut k = qkv[n * d..2 * n * d].to_vec();
705    let v = qkv[2 * n * d..].to_vec();
706    qk_norm_rope(
707        &mut q,
708        n,
709        cfg.num_heads,
710        cfg.head_dim(),
711        &b.q_norm,
712        rope,
713        pool,
714    );
715    qk_norm_rope(
716        &mut k,
717        n,
718        cfg.num_heads,
719        cfg.head_dim(),
720        &b.k_norm,
721        rope,
722        pool,
723    );
724    let attn = attention(&q, &k, &v, n, cfg.num_heads, cfg.head_dim(), pool);
725    let out = linear(&b.proj, &attn, n, Some(&b.proj_b), pool);
726    for (a, &v) in x.iter_mut().zip(&out) {
727        *a += v;
728    }
729    let mut norm = x.to_vec();
730    rms_rows_inplace(&mut norm, n, d, &b.norm2, None, None, pool);
731    let gate = linear(&b.ffn_gate, &norm, n, Some(&b.ffn_gate_b), pool);
732    let mut up = linear(&b.ffn_up, &norm, n, Some(&b.ffn_up_b), pool);
733    for (a, &g) in up.iter_mut().zip(&gate) {
734        *a = situ(*a, g);
735    }
736    let out = linear(&b.ffn_down, &up, n, Some(&b.ffn_down_b), pool);
737    for (a, &v) in x.iter_mut().zip(&out) {
738        *a += v;
739    }
740}
741
742fn main_block(
743    b: &Block,
744    x: &mut [f32],
745    n: usize,
746    rope: &Rope,
747    modulate: &[f32],
748    cfg: &MossConfig,
749    pool: Option<&Pool>,
750) {
751    let d = cfg.dim;
752    assert_eq!(modulate.len(), 6 * d);
753    let (shift_a, rest) = modulate.split_at(d);
754    let (scale_a, rest) = rest.split_at(d);
755    let (gate_a, rest) = rest.split_at(d);
756    let (shift_f, rest) = rest.split_at(d);
757    let (scale_f, gate_f) = rest.split_at(d);
758    let mut norm = x.to_vec();
759    rms_rows_inplace(
760        &mut norm,
761        n,
762        d,
763        &b.norm1,
764        Some(scale_a),
765        Some(shift_a),
766        pool,
767    );
768    let mut q = linear(&b.q, &norm, n, None, pool);
769    let mut k = linear(&b.k, &norm, n, None, pool);
770    let v = linear(&b.v, &norm, n, None, pool);
771    qk_norm_rope(
772        &mut q,
773        n,
774        cfg.num_heads,
775        cfg.head_dim(),
776        &b.q_norm,
777        rope,
778        pool,
779    );
780    qk_norm_rope(
781        &mut k,
782        n,
783        cfg.num_heads,
784        cfg.head_dim(),
785        &b.k_norm,
786        rope,
787        pool,
788    );
789    let attn = attention(&q, &k, &v, n, cfg.num_heads, cfg.head_dim(), pool);
790    let out = linear(&b.o, &attn, n, None, pool);
791    for row in 0..n {
792        for j in 0..d {
793            x[row * d + j] += out[row * d + j] * gate_a[j];
794        }
795    }
796    let mut norm = x.to_vec();
797    rms_rows_inplace(
798        &mut norm,
799        n,
800        d,
801        &b.norm2,
802        Some(scale_f),
803        Some(shift_f),
804        pool,
805    );
806    let up_gate = linear(&b.ffn_up_gate, &norm, n, None, pool);
807    let inter = cfg.ffn_dim;
808    let mut ffn = vec![0f32; n * inter];
809    for row in 0..n {
810        for i in 0..inter {
811            ffn[row * inter + i] = situ(
812                up_gate[row * 2 * inter + i],
813                up_gate[row * 2 * inter + inter + i],
814            );
815        }
816    }
817    let out = linear(&b.ffn_down, &ffn, n, None, pool);
818    for row in 0..n {
819        for j in 0..d {
820            x[row * d + j] += out[row * d + j] * gate_f[j];
821        }
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828
829    #[test]
830    fn rope_layout_repeats_quarter_axis_frequencies() {
831        let cfg = MossConfig {
832            dim: 64,
833            ffn_dim: 64,
834            freq_dim: 8,
835            latent_channels: 4,
836            num_heads: 1,
837            num_layers: 1,
838            text_dim: 8,
839            rope_base: 10_000.0,
840        };
841        let r = Rope::new(&cfg, 2, 2, 3);
842        assert_eq!(r.sin.len(), 7 * 64);
843        for t in 0..7 {
844            assert_eq!(
845                &r.sin[t * 64..t * 64 + 32],
846                &r.sin[t * 64 + 32..(t + 1) * 64]
847            );
848            assert_eq!(
849                &r.cos[t * 64..t * 64 + 32],
850                &r.cos[t * 64 + 32..(t + 1) * 64]
851            );
852        }
853    }
854
855    #[test]
856    fn situ_matches_definition() {
857        let h = 2.5f32;
858        let g = -1.25f32;
859        let got = situ(h, g);
860        let want =
861            (4.0 * (g / 4.0).tanh() * (1.0 / (1.0 + (-g).exp()))) * (25.0 * (h / 25.0).tanh());
862        assert!((got - want).abs() < 1e-7);
863    }
864}