Skip to main content

oa/ml/nn/
mamba3.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_mamba3.json
3// generator_version=8; schema_sha256=65ffc92c6fd1dc29fae577e4922a37589f52ecef6a8dc76c2ed7a28a3b1451bc
4
5use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/mamba3/mamba3.cpp
10// Adaptation: Complete donor FP32 SISO/MIMO composition with checked Rust geometry, deterministic host initialization and stable exp_m1 inverse softplus, versioned parameter adjoints and explicit caller-owned four-buffer inference cache; rank selects SISO/MIMO and existing operation providers retain all shader and graph ownership
11/// Construction contract for the donor-backed Mamba-3 block.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct Mamba3Config {
14	/// Input and output channel width.
15	pub model_width: usize,
16	/// Selective recurrent state width.
17	pub state_size: usize,
18	/// Integer expansion factor applied to `model_width`.
19	pub expand: usize,
20	/// Value width per selective-state head.
21	pub head_dim: usize,
22	/// Number of B/C groups shared across heads.
23	pub num_groups: usize,
24	/// Shared-state input/output rank; one selects the SISO route.
25	pub mimo_rank: usize,
26	/// Fraction of the state width assigned to rotary pairs.
27	pub rope_fraction: f32,
28	/// Inclusive minimum transformed time step.
29	pub dt_min: f32,
30	/// Inclusive maximum transformed time step.
31	pub dt_max: f32,
32	/// Minimum initialized transformed time step.
33	pub dt_init_floor: f32,
34	/// Positive floor used by the heavy-tail A transform.
35	pub a_floor: f32,
36	/// Normalize each head and apply the z gate after the SSM scan.
37	pub output_norm: bool,
38}
39
40impl Mamba3Config {
41	/// Construct the OA defaults for one model width.
42	pub const fn new(model_width: usize) -> Self {
43		Self {
44			model_width,
45			state_size: 128,
46			expand: 2,
47			head_dim: 64,
48			num_groups: 1,
49			mimo_rank: 1,
50			rope_fraction: 0.5,
51			dt_min: 0.001,
52			dt_max: 0.1,
53			dt_init_floor: 0.0001,
54			a_floor: 0.0001,
55			output_norm: false,
56		}
57	}
58}
59
60/// Explicit recurrent cache for one [`Mamba3`] module and batch size.
61///
62/// The cache owns the selective state, cumulative rotary angle, previous key,
63/// and previous value buffers. It is deliberately separate from the module so
64/// independent decoding streams never share hidden mutable state.
65pub struct Mamba3State {
66	owner_id: u64,
67	batch_size: usize,
68	ssm: Matrix,
69	angle: Matrix,
70	key: Matrix,
71	value: Matrix,
72}
73
74impl Mamba3State {
75	/// Return the fixed batch size accepted by this cache.
76	pub const fn batch_size(&self) -> usize {
77		self.batch_size
78	}
79}
80
81/// Parameter-owning Mamba-3 selective state-space block.
82pub struct Mamba3 {
83	config: Mamba3Config,
84	inner_size: usize,
85	num_heads: usize,
86	num_rope_angles: usize,
87	in_projection: Parameter,
88	dt_bias: Parameter,
89	b_bias: Parameter,
90	c_bias: Parameter,
91	mimo_x: Option<Parameter>,
92	mimo_z: Option<Parameter>,
93	mimo_o: Option<Parameter>,
94	d_skip: Parameter,
95	out_projection: Parameter,
96	norm_weight: Option<Parameter>,
97	norm_identity: Matrix,
98	in_projection_bias: Matrix,
99	out_projection_bias: Matrix,
100	registry: ModuleRegistry,
101}
102
103impl Mamba3 {
104	#[allow(clippy::too_many_arguments)]
105	pub fn new_with_seed(config: Mamba3Config, seed: u64) -> Result<Self> {
106		Self::new_with_seed_on(&Runtime::current()?, config, seed)
107	}
108
109	/// Construct a deterministically initialized Mamba-3 block.
110	///
111	/// The module preserves the donor parameter layout and complete
112	/// projection → preprocess → SISO scan → optional gated per-head RMSNorm →
113	/// output-projection path. `seed` owns an independent deterministic
114	/// initializer stream.
115	///
116	/// # Errors
117	///
118	/// Returns an error for invalid or overflowing geometry, invalid numerical
119	/// bounds, or failed allocation/registration.
120	pub fn new_with_seed_on(runtime: &Runtime, config: Mamba3Config, seed: u64) -> Result<Self> {
121		let inner_size = config
122			.model_width
123			.checked_mul(config.expand)
124			.ok_or_else(|| Error::invalid_argument("Mamba3 inner width overflows usize"))?;
125		if config.model_width == 0
126			|| config.state_size == 0
127			|| config.state_size > 128
128			|| config.expand == 0
129			|| config.head_dim == 0
130			|| config.head_dim > 128
131			|| inner_size == 0
132			|| !inner_size.is_multiple_of(config.head_dim)
133			|| config.num_groups == 0
134			|| !(1..=8).contains(&config.mimo_rank)
135			|| (config.mimo_rank > 1 && config.head_dim.saturating_mul(config.state_size) > 4096)
136			|| !config.rope_fraction.is_finite()
137			|| !(0.0..=1.0).contains(&config.rope_fraction)
138			|| !config.dt_min.is_finite()
139			|| !config.dt_max.is_finite()
140			|| !config.dt_init_floor.is_finite()
141			|| !config.a_floor.is_finite()
142			|| config.dt_min <= 0.0
143			|| config.dt_max < config.dt_min
144			|| config.dt_init_floor <= 0.0
145			|| config.a_floor <= 0.0
146		{
147			return Err(Error::invalid_argument(
148				"Mamba3 requires positive divisible dimensions, MIMO rank in 1..=8 with P*N <= 4096, rope_fraction in [0,1], ordered positive dt bounds, and positive dt/A floors",
149			));
150		}
151		let num_heads = inner_size / config.head_dim;
152		if num_heads == 0 || !num_heads.is_multiple_of(config.num_groups) {
153			return Err(Error::invalid_argument(
154				"Mamba3 head count must be nonzero and divisible by num_groups",
155			));
156		}
157		let rope_width =
158			((config.state_size as f64 * f64::from(config.rope_fraction)).floor() as usize) & !1_usize;
159		let num_rope_angles = rope_width / 2;
160		if num_rope_angles > 64 {
161			return Err(Error::invalid_argument(
162				"Mamba3 rotary angle count exceeds the admitted SISO kernel limit of 64",
163			));
164		}
165		let grouped_state = config
166			.num_groups
167			.checked_mul(config.state_size)
168			.ok_or_else(|| Error::invalid_argument("Mamba3 grouped state width overflows"))?;
169		let grouped_rank_state = grouped_state
170			.checked_mul(config.mimo_rank)
171			.ok_or_else(|| Error::invalid_argument("Mamba3 grouped MIMO state width overflows"))?;
172		let projected_width = inner_size
173			.checked_mul(2)
174			.and_then(|value| {
175				grouped_rank_state
176					.checked_mul(2)
177					.and_then(|bc| value.checked_add(bc))
178			})
179			.and_then(|value| {
180				num_heads
181					.checked_mul(3)
182					.and_then(|heads| value.checked_add(heads))
183			})
184			.and_then(|value| value.checked_add(num_rope_angles))
185			.ok_or_else(|| Error::invalid_argument("Mamba3 projected width overflows usize"))?;
186
187		let in_count = projected_width
188			.checked_mul(config.model_width)
189			.ok_or_else(|| Error::invalid_argument("Mamba3 input projection size overflows"))?;
190		let in_limit = (6.0_f32 / (projected_width + config.model_width) as f32).sqrt();
191		let in_projection = Parameter::new(
192			"in_proj",
193			Matrix::new_from_f32_on(
194				runtime,
195				[projected_width, config.model_width],
196				&random::symmetric_uniform(in_count, in_limit, seed),
197			)?,
198		)?;
199		let dt_uniform = random::unit_uniform(num_heads, seed.wrapping_add(1));
200		let log_min = config.dt_min.ln();
201		let log_range = config.dt_max.ln() - log_min;
202		let dt_bias_values = dt_uniform
203			.into_iter()
204			.map(|sample| {
205				let dt = (log_min + sample * log_range)
206					.exp()
207					.max(config.dt_init_floor);
208				dt + (-(-dt).exp_m1()).ln()
209			})
210			.collect::<Vec<_>>();
211		let dt_bias = Parameter::new(
212			"dt_bias",
213			Matrix::new_from_f32_on(runtime, [num_heads], &dt_bias_values)?,
214		)?;
215		let bias_count = num_heads
216			.checked_mul(config.mimo_rank)
217			.and_then(|value| value.checked_mul(config.state_size))
218			.ok_or_else(|| Error::invalid_argument("Mamba3 B/C bias size overflows"))?;
219		let bias_shape = if config.mimo_rank > 1 {
220			vec![num_heads, config.mimo_rank, config.state_size]
221		} else {
222			vec![num_heads, config.state_size]
223		};
224		let b_bias = Parameter::new(
225			"B_bias",
226			Matrix::new_from_f32_on(runtime, bias_shape.clone(), &vec![1.0; bias_count])?,
227		)?;
228		let c_bias = Parameter::new(
229			"C_bias",
230			Matrix::new_from_f32_on(runtime, bias_shape, &vec![1.0; bias_count])?,
231		)?;
232		let mimo_count = num_heads
233			.checked_mul(config.mimo_rank)
234			.and_then(|value| value.checked_mul(config.head_dim))
235			.ok_or_else(|| Error::invalid_argument("Mamba3 MIMO projection size overflows"))?;
236		let mimo_shape = [num_heads, config.mimo_rank, config.head_dim];
237		let mimo_x = (config.mimo_rank > 1)
238			.then(|| {
239				Parameter::new(
240					"mimo_x",
241					Matrix::new_from_f32_on(
242						runtime,
243						mimo_shape,
244						&vec![1.0 / config.mimo_rank as f32; mimo_count],
245					)?,
246				)
247			})
248			.transpose()?;
249		let mimo_z = (config.mimo_rank > 1)
250			.then(|| {
251				Parameter::new(
252					"mimo_z",
253					Matrix::new_from_f32_on(runtime, mimo_shape, &vec![1.0; mimo_count])?,
254				)
255			})
256			.transpose()?;
257		let mimo_o = (config.mimo_rank > 1)
258			.then(|| {
259				Parameter::new(
260					"mimo_o",
261					Matrix::new_from_f32_on(
262						runtime,
263						mimo_shape,
264						&vec![1.0 / config.mimo_rank as f32; mimo_count],
265					)?,
266				)
267			})
268			.transpose()?;
269		let d_skip = Parameter::new(
270			"D",
271			Matrix::new_from_f32_on(runtime, [num_heads], &vec![0.0; num_heads])?,
272		)?;
273		let out_count = config
274			.model_width
275			.checked_mul(inner_size)
276			.ok_or_else(|| Error::invalid_argument("Mamba3 output projection size overflows"))?;
277		let out_limit = (6.0_f32 / (config.model_width + inner_size) as f32).sqrt();
278		let out_projection = Parameter::new(
279			"out_proj",
280			Matrix::new_from_f32_on(
281				runtime,
282				[config.model_width, inner_size],
283				&random::symmetric_uniform(out_count, out_limit, seed.wrapping_add(2)),
284			)?,
285		)?;
286		let norm_weight = config
287			.output_norm
288			.then(|| {
289				Parameter::new(
290					"norm_weight",
291					Matrix::new_from_f32_on(
292						runtime,
293						[num_heads, config.head_dim],
294						&vec![1.0; inner_size],
295					)?,
296				)
297			})
298			.transpose()?;
299		let norm_identity = Matrix::new_from_f32_on(
300			runtime,
301			[num_heads, config.head_dim],
302			&vec![1.0; inner_size],
303		)?;
304		let in_projection_bias =
305			Matrix::new_from_f32_on(runtime, [projected_width], &vec![0.0; projected_width])?;
306		let out_projection_bias = Matrix::new_from_f32_on(
307			runtime,
308			[config.model_width],
309			&vec![0.0; config.model_width],
310		)?;
311
312		let mut registry = ModuleRegistry::new();
313		for (name, parameter) in [
314			("in_proj", &in_projection),
315			("dt_bias", &dt_bias),
316			("B_bias", &b_bias),
317			("C_bias", &c_bias),
318		] {
319			registry.register_parameter(name, parameter.clone())?;
320		}
321		for (name, parameter) in [
322			("mimo_x", &mimo_x),
323			("mimo_z", &mimo_z),
324			("mimo_o", &mimo_o),
325		] {
326			if let Some(parameter) = parameter {
327				registry.register_parameter(name, parameter.clone())?;
328			}
329		}
330		registry.register_parameter("D", d_skip.clone())?;
331		registry.register_parameter("out_proj", out_projection.clone())?;
332		if let Some(parameter) = &norm_weight {
333			registry.register_parameter("norm_weight", parameter.clone())?;
334		}
335		Ok(Self {
336			config,
337			inner_size,
338			num_heads,
339			num_rope_angles,
340			in_projection,
341			dt_bias,
342			b_bias,
343			c_bias,
344			mimo_x,
345			mimo_z,
346			mimo_o,
347			d_skip,
348			out_projection,
349			norm_weight,
350			norm_identity,
351			in_projection_bias,
352			out_projection_bias,
353			registry,
354		})
355	}
356
357	/// Evaluate one complete Mamba-3 block without submitting or waiting.
358	///
359	/// # Errors
360	///
361	/// Returns an error unless `input` is a nonempty same-runtime F32
362	/// `[batch, sequence, model_width]` value or an owned operation cannot be
363	/// recorded.
364	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
365		let [batch, sequence_length, model_width] = input.shape() else {
366			return Err(Error::invalid_argument(
367				"Mamba3 input must have shape [batch, sequence, model_width]",
368			));
369		};
370		if *batch == 0
371			|| *sequence_length == 0
372			|| *model_width != self.config.model_width
373			|| input.dtype() != DType::F32
374		{
375			return Err(Error::invalid_argument(format!(
376				"Mamba3 requires nonempty F32 input [B, L, {}]; found {:?} {}",
377				self.config.model_width,
378				input.shape(),
379				input.dtype().token()
380			)));
381		}
382		let rows = batch
383			.checked_mul(*sequence_length)
384			.ok_or_else(|| Error::invalid_argument("Mamba3 flattened row count overflows"))?;
385		let input_2d = input.reshape([rows, self.config.model_width])?;
386		let projected =
387			self.parameter_linear(&input_2d, &self.in_projection, &self.in_projection_bias)?;
388
389		for parameter in [&self.dt_bias, &self.b_bias, &self.c_bias, &self.d_skip] {
390			autograd::record_parameter_leaf(parameter)?;
391		}
392		for parameter in [&self.mimo_x, &self.mimo_z, &self.mimo_o]
393			.into_iter()
394			.flatten()
395		{
396			autograd::record_parameter_leaf(parameter)?;
397		}
398		let dt_bias = self.dt_bias.data();
399		let preprocess = matrix::mamba3_preprocess(
400			&projected,
401			&dt_bias,
402			crate::ml::matrix::Mamba3PreprocessConfig {
403				inner_size: self.inner_size,
404				state_size: self.config.state_size,
405				num_heads: self.num_heads,
406				num_rope_angles: self.num_rope_angles,
407				num_groups: self.config.num_groups,
408				mimo_rank: self.config.mimo_rank,
409				epsilon: 1e-5,
410				dt_min: self.config.dt_min,
411				dt_max: self.config.dt_max,
412				a_floor: self.config.a_floor,
413			},
414		)?;
415		let x = preprocess.x.reshape([
416			*batch,
417			*sequence_length,
418			self.num_heads,
419			self.config.head_dim,
420		])?;
421		let z = preprocess.z.reshape(x.shape().to_vec())?;
422		let b = preprocess.bh.reshape([
423			*batch,
424			*sequence_length,
425			self.config.num_groups * self.config.mimo_rank,
426			self.config.state_size,
427		])?;
428		let c = preprocess.ch.reshape(b.shape().to_vec())?;
429		let adt = preprocess
430			.adt
431			.reshape([*batch, *sequence_length, self.num_heads])?;
432		let dt = preprocess
433			.dt
434			.reshape([*batch, *sequence_length, self.num_heads])?;
435		let trap = preprocess
436			.trap
437			.reshape([*batch, *sequence_length, self.num_heads])?;
438		let angle = preprocess
439			.angle
440			.reshape([*batch, *sequence_length, self.num_rope_angles])?;
441		let c_bias = self.c_bias.data();
442		let b_bias = self.b_bias.data();
443		let d_skip = self.d_skip.data();
444		let scan_config = crate::ml::matrix::SsmConfig {
445			batch_size: *batch,
446			sequence_length: *sequence_length,
447			num_heads: self.num_heads,
448			num_groups: self.config.num_groups,
449			head_dim: self.config.head_dim,
450			state_size: self.config.state_size,
451			num_rope_angles: self.num_rope_angles,
452			mimo_rank: self.config.mimo_rank,
453			has_z: self.config.mimo_rank > 1 || !self.config.output_norm,
454			has_d: true,
455			has_output_norm: self.config.mimo_rank > 1 && self.config.output_norm,
456		};
457		let scan = if let (Some(mimo_x), Some(mimo_z), Some(mimo_o)) =
458			(&self.mimo_x, &self.mimo_z, &self.mimo_o)
459		{
460			if let Some(norm_weight) = &self.norm_weight {
461				autograd::record_parameter_leaf(norm_weight)?;
462			}
463			let norm_weight = self
464				.norm_weight
465				.as_ref()
466				.map_or_else(|| self.norm_identity.clone(), Parameter::data);
467			matrix::mamba3_mimo(
468				&c,
469				&b,
470				&x,
471				&z,
472				&adt,
473				&dt,
474				&trap,
475				&angle,
476				&c_bias,
477				&b_bias,
478				&d_skip,
479				&mimo_x.data(),
480				&mimo_z.data(),
481				&mimo_o.data(),
482				&norm_weight,
483				scan_config,
484			)?
485		} else {
486			matrix::mamba3_siso(
487				&c,
488				&b,
489				&x,
490				&z,
491				&adt,
492				&dt,
493				&trap,
494				&angle,
495				&c_bias,
496				&b_bias,
497				&d_skip,
498				scan_config,
499			)?
500		};
501		let scan = if self.config.mimo_rank == 1 {
502			if let Some(norm_weight) = &self.norm_weight {
503				autograd::record_parameter_leaf(norm_weight)?;
504				matrix::rms_norm_gated(&scan, &norm_weight.data(), None, &z, 1e-5)?
505			} else {
506				scan
507			}
508		} else {
509			scan
510		};
511		let flattened = scan.reshape([rows, self.inner_size])?;
512		let output =
513			self.parameter_linear(&flattened, &self.out_projection, &self.out_projection_bias)?;
514		output.reshape([*batch, *sequence_length, self.config.model_width])
515	}
516
517	/// Allocate a zero-initialized recurrent cache for one positive batch size.
518	///
519	/// # Errors
520	///
521	/// Returns an error when `batch_size` is zero, state geometry overflows, or
522	/// device allocation fails.
523	pub fn new_state(&self, batch_size: usize) -> Result<Mamba3State> {
524		if batch_size == 0 {
525			return Err(Error::invalid_argument(
526				"Mamba3 recurrent state requires a positive batch size",
527			));
528		}
529		let owner = self.in_projection.data();
530		let allocate = |shape: Vec<usize>| -> Result<Matrix> {
531			let count = shape.iter().try_fold(1_usize, |count, extent| {
532				count
533					.checked_mul(*extent)
534					.ok_or_else(|| Error::invalid_argument("Mamba3 recurrent state size overflows usize"))
535			})?;
536			Matrix::allocate(owner.runtime(), shape, count, DType::F32)
537		};
538		Ok(Mamba3State {
539			owner_id: owner.value_id(),
540			batch_size,
541			ssm: allocate(vec![
542				batch_size,
543				self.num_heads,
544				self.config.head_dim,
545				self.config.state_size,
546			])?,
547			angle: allocate(vec![batch_size, self.num_heads, self.num_rope_angles])?,
548			key: if self.config.mimo_rank > 1 {
549				allocate(vec![
550					batch_size,
551					self.num_heads,
552					self.config.mimo_rank,
553					self.config.state_size,
554				])?
555			} else {
556				allocate(vec![batch_size, self.num_heads, self.config.state_size])?
557			},
558			value: if self.config.mimo_rank > 1 {
559				allocate(vec![
560					batch_size,
561					self.num_heads,
562					self.config.mimo_rank,
563					self.config.head_dim,
564				])?
565			} else {
566				allocate(vec![batch_size, self.num_heads, self.config.head_dim])?
567			},
568		})
569	}
570
571	/// Advance one autoregressive token using an explicit recurrent cache.
572	///
573	/// `input` must be F32 `[batch, 1, model_width]`. This is an inference-only
574	/// operation: recurrent-state differentiation is not admitted, and calling it
575	/// while a [`crate::ml::GradientTape`] is active returns an error.
576	///
577	/// # Errors
578	///
579	/// Returns an error for an active gradient tape, a cache owned by another
580	/// module, mismatched batch/shape/dtype/Runtime ownership, or failed recording.
581	pub fn step(&self, input: &Matrix, state: &mut Mamba3State) -> Result<Matrix> {
582		if autograd::recording_active() {
583			return Err(Error::failed_precondition(
584				"Mamba3 recurrent step is inference-only and cannot run inside a GradientTape",
585			));
586		}
587		let owner = self.in_projection.data();
588		if state.owner_id != owner.value_id() {
589			return Err(Error::invalid_argument(
590				"Mamba3 recurrent state belongs to another module instance",
591			));
592		}
593		if input.shape() != [state.batch_size, 1, self.config.model_width]
594			|| input.dtype() != DType::F32
595		{
596			return Err(Error::invalid_argument(format!(
597				"Mamba3 step requires F32 input [{}, 1, {}]; found {:?} {}",
598				state.batch_size,
599				self.config.model_width,
600				input.shape(),
601				input.dtype().token()
602			)));
603		}
604
605		let input_2d = input.reshape([state.batch_size, self.config.model_width])?;
606		let projected = matrix::linear(&input_2d, &owner, &self.in_projection_bias)?;
607		let preprocess = matrix::mamba3_preprocess(
608			&projected,
609			&self.dt_bias.data(),
610			crate::ml::matrix::Mamba3PreprocessConfig {
611				inner_size: self.inner_size,
612				state_size: self.config.state_size,
613				num_heads: self.num_heads,
614				num_rope_angles: self.num_rope_angles,
615				num_groups: self.config.num_groups,
616				mimo_rank: self.config.mimo_rank,
617				epsilon: 1e-5,
618				dt_min: self.config.dt_min,
619				dt_max: self.config.dt_max,
620				a_floor: self.config.a_floor,
621			},
622		)?;
623		let x = preprocess
624			.x
625			.reshape([state.batch_size, 1, self.num_heads, self.config.head_dim])?;
626		let z = preprocess.z.reshape(x.shape().to_vec())?;
627		let b = preprocess.bh.reshape([
628			state.batch_size,
629			1,
630			self.config.num_groups * self.config.mimo_rank,
631			self.config.state_size,
632		])?;
633		let c = preprocess.ch.reshape(b.shape().to_vec())?;
634		let adt = preprocess
635			.adt
636			.reshape([state.batch_size, 1, self.num_heads])?;
637		let dt = preprocess
638			.dt
639			.reshape([state.batch_size, 1, self.num_heads])?;
640		let trap = preprocess
641			.trap
642			.reshape([state.batch_size, 1, self.num_heads])?;
643		let angle = preprocess
644			.angle
645			.reshape([state.batch_size, 1, self.num_rope_angles])?;
646		let scan_config = crate::ml::matrix::SsmConfig {
647			batch_size: state.batch_size,
648			sequence_length: 1,
649			num_heads: self.num_heads,
650			num_groups: self.config.num_groups,
651			head_dim: self.config.head_dim,
652			state_size: self.config.state_size,
653			num_rope_angles: self.num_rope_angles,
654			mimo_rank: self.config.mimo_rank,
655			has_z: self.config.mimo_rank > 1 || !self.config.output_norm,
656			has_d: true,
657			has_output_norm: self.config.mimo_rank > 1 && self.config.output_norm,
658		};
659		let scan = if let (Some(mimo_x), Some(mimo_z), Some(mimo_o)) =
660			(&self.mimo_x, &self.mimo_z, &self.mimo_o)
661		{
662			let norm_weight = self
663				.norm_weight
664				.as_ref()
665				.map_or_else(|| self.norm_identity.clone(), Parameter::data);
666			matrix::mamba3_mimo_step(
667				&c,
668				&b,
669				&x,
670				&z,
671				&adt,
672				&dt,
673				&trap,
674				&angle,
675				&self.c_bias.data(),
676				&self.b_bias.data(),
677				&self.d_skip.data(),
678				&mimo_x.data(),
679				&mimo_z.data(),
680				&mimo_o.data(),
681				&norm_weight,
682				&mut state.ssm,
683				&mut state.angle,
684				&mut state.key,
685				&mut state.value,
686				scan_config,
687			)?
688		} else {
689			matrix::mamba3_siso_step(
690				&c,
691				&b,
692				&x,
693				&z,
694				&adt,
695				&dt,
696				&trap,
697				&angle,
698				&self.c_bias.data(),
699				&self.b_bias.data(),
700				&self.d_skip.data(),
701				&mut state.ssm,
702				&mut state.angle,
703				&mut state.key,
704				&mut state.value,
705				scan_config,
706			)?
707		};
708		let scan = if self.config.mimo_rank == 1 {
709			if let Some(weight) = &self.norm_weight {
710				matrix::rms_norm_gated_forward(&scan, &weight.data(), None, &z, 1e-5)?
711			} else {
712				scan
713			}
714		} else {
715			scan
716		};
717		let flattened = scan.reshape([state.batch_size, self.inner_size])?;
718		let output = matrix::linear(
719			&flattened,
720			&self.out_projection.data(),
721			&self.out_projection_bias,
722		)?;
723		output.reshape([state.batch_size, 1, self.config.model_width])
724	}
725
726	fn parameter_linear(&self, input: &Matrix, weight: &Parameter, bias: &Matrix) -> Result<Matrix> {
727		let (weight_value, version, requires_grad) = weight.snapshot();
728		let output = matrix::linear(input, &weight_value, bias)?;
729		if requires_grad {
730			autograd::record_linear(input, &output, weight.clone(), weight_value, version, None)?;
731		}
732		Ok(output)
733	}
734
735	/// Return the immutable construction contract.
736	pub const fn config(&self) -> Mamba3Config {
737		self.config
738	}
739
740	/// Return the expanded SSM width.
741	pub const fn inner_size(&self) -> usize {
742		self.inner_size
743	}
744
745	/// Return the selective-state head count.
746	pub const fn num_heads(&self) -> usize {
747		self.num_heads
748	}
749
750	/// Return the rotary angle count.
751	pub const fn num_rope_angles(&self) -> usize {
752		self.num_rope_angles
753	}
754
755	/// Return the exact registered parameters in donor order.
756	pub fn parameters(&self) -> Vec<Parameter> {
757		let mut parameters = vec![
758			self.in_projection.clone(),
759			self.dt_bias.clone(),
760			self.b_bias.clone(),
761			self.c_bias.clone(),
762		];
763		for parameter in [&self.mimo_x, &self.mimo_z, &self.mimo_o]
764			.into_iter()
765			.flatten()
766		{
767			parameters.push(parameter.clone());
768		}
769		parameters.push(self.d_skip.clone());
770		parameters.push(self.out_projection.clone());
771		if let Some(weight) = &self.norm_weight {
772			parameters.push(weight.clone());
773		}
774		parameters
775	}
776}
777
778impl Module for Mamba3 {
779	fn forward(&self, input: &Matrix) -> Result<Matrix> {
780		Mamba3::forward(self, input)
781	}
782
783	fn registry(&self) -> &ModuleRegistry {
784		&self.registry
785	}
786}