Skip to main content

oa/ml/matrix/
mamba3.rs

1//! Mamba-3 selective state-space Matrix operations and adjoints.
2
3pub use crate::ml::types::{Mamba3PreprocessConfig, Mamba3PreprocessResult, SsmConfig};
4use crate::{
5	DType, Error, Matrix, OpAttribute, Result,
6	runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
7};
8
9use crate::ml::{
10	autograd,
11	validation::{shader_u32, validate_f32_same_runtime},
12};
13
14impl Mamba3PreprocessConfig {
15	pub(crate) fn identity(self, operation: &'static str) -> Result<u64> {
16		let mut hash = 14_695_981_039_346_656_037_u64;
17		for value in [
18			u32::try_from(self.inner_size),
19			u32::try_from(self.state_size),
20			u32::try_from(self.num_heads),
21			u32::try_from(self.num_rope_angles),
22			u32::try_from(self.num_groups),
23			u32::try_from(self.mimo_rank),
24		]
25		.into_iter()
26		.chain([
27			Ok(self.epsilon.to_bits()),
28			Ok(self.dt_min.to_bits()),
29			Ok(self.dt_max.to_bits()),
30			Ok(self.a_floor.to_bits()),
31		]) {
32			let value = value.map_err(|_| {
33				Error::invalid_argument(format!(
34					"{operation} configuration value exceeds the stable u32 identity ABI"
35				))
36			})?;
37			for byte in value.to_le_bytes() {
38				hash = (hash ^ u64::from(byte)).wrapping_mul(1_099_511_628_211);
39			}
40		}
41		Ok(hash)
42	}
43}
44
45impl Mamba3PreprocessResult {
46	pub(crate) fn matrices(&self) -> [&Matrix; 8] {
47		[
48			&self.x,
49			&self.z,
50			&self.bh,
51			&self.ch,
52			&self.dt,
53			&self.adt,
54			&self.trap,
55			&self.angle,
56		]
57	}
58}
59
60/// Input adjoints produced by the fused Mamba-3 projection preprocess.
61pub struct Mamba3PreprocessBackward {
62	/// Gradient of the packed projected input.
63	pub projected: Matrix,
64	/// Gradient of the per-head dt bias.
65	pub dt_bias: Matrix,
66}
67
68impl SsmConfig {
69	pub(crate) fn identity(self, operation: &'static str) -> Result<u64> {
70		let mut hash = 14_695_981_039_346_656_037_u64;
71		for value in [
72			self.batch_size,
73			self.sequence_length,
74			self.num_heads,
75			self.num_groups,
76			self.head_dim,
77			self.state_size,
78			self.num_rope_angles,
79			self.mimo_rank,
80			usize::from(self.has_z),
81			usize::from(self.has_d),
82			usize::from(self.has_output_norm),
83		] {
84			let value = u32::try_from(value).map_err(|_| {
85				Error::invalid_argument(format!(
86					"{operation} configuration value exceeds the stable u32 identity ABI"
87				))
88			})?;
89			for byte in value.to_le_bytes() {
90				hash = (hash ^ u64::from(byte)).wrapping_mul(1_099_511_628_211);
91			}
92		}
93		Ok(hash)
94	}
95}
96
97// ---------------------------------------------------------------------------
98// Private lowering types and helpers
99// ---------------------------------------------------------------------------
100
101const MAMBA3_CHUNK_HISTORY_LIMIT_BYTES: usize = 256 * 1024 * 1024;
102
103pub(in crate::ml) struct Mamba3PreprocessBackwardResult {
104	pub(in crate::ml) projected: Matrix,
105	pub(in crate::ml) dt_bias: Matrix,
106}
107
108pub(in crate::ml) struct SsmBackwardResult {
109	pub(in crate::ml) c: Matrix,
110	pub(in crate::ml) b: Matrix,
111	pub(in crate::ml) x: Matrix,
112	pub(in crate::ml) z: Matrix,
113	pub(in crate::ml) adt: Matrix,
114	pub(in crate::ml) dt: Matrix,
115	pub(in crate::ml) trap: Matrix,
116	pub(in crate::ml) angle: Matrix,
117	pub(in crate::ml) c_bias: Matrix,
118	pub(in crate::ml) b_bias: Matrix,
119	pub(in crate::ml) d: Matrix,
120}
121
122pub(in crate::ml) struct Mamba3MimoBackwardResult {
123	pub(in crate::ml) c: Matrix,
124	pub(in crate::ml) b: Matrix,
125	pub(in crate::ml) x: Matrix,
126	pub(in crate::ml) z: Matrix,
127	pub(in crate::ml) adt: Matrix,
128	pub(in crate::ml) dt: Matrix,
129	pub(in crate::ml) trap: Matrix,
130	pub(in crate::ml) angle: Matrix,
131	pub(in crate::ml) c_bias: Matrix,
132	pub(in crate::ml) b_bias: Matrix,
133	pub(in crate::ml) d: Matrix,
134	pub(in crate::ml) mimo_x: Matrix,
135	pub(in crate::ml) mimo_z: Matrix,
136	pub(in crate::ml) mimo_o: Matrix,
137	pub(in crate::ml) norm_weight: Matrix,
138}
139
140struct Geometry {
141	batch: u32,
142	length: u32,
143	heads: u32,
144	groups: u32,
145	head_dim: u32,
146	state_size: u32,
147	angles: u32,
148	batch_heads: u32,
149}
150
151impl Geometry {
152	fn resolve(inputs: &[&Matrix; 11], config: SsmConfig, operation: &'static str) -> Result<Self> {
153		let groups = if config.num_groups == 0 {
154			config.num_heads
155		} else {
156			config.num_groups
157		};
158		if config.batch_size == 0
159			|| config.sequence_length == 0
160			|| config.num_heads == 0
161			|| groups == 0
162			|| !config.num_heads.is_multiple_of(groups)
163			|| config.head_dim == 0
164			|| config.head_dim > 128
165			|| config.state_size == 0
166			|| config.state_size > 128
167			|| config.num_rope_angles > 64
168			|| config.num_rope_angles.saturating_mul(2) > config.state_size
169			|| config.mimo_rank != 1
170			|| config.has_output_norm
171		{
172			return Err(Error::invalid_argument(format!(
173				"{operation} requires B/L/H/G/P/N > 0, H divisible by G, P/N <= 128, A <= 64, 2A <= N, MIMO rank one, and no MIMO output normalization"
174			)));
175		}
176		let expected = [
177			vec![
178				config.batch_size,
179				config.sequence_length,
180				groups,
181				config.state_size,
182			],
183			vec![
184				config.batch_size,
185				config.sequence_length,
186				groups,
187				config.state_size,
188			],
189			vec![
190				config.batch_size,
191				config.sequence_length,
192				config.num_heads,
193				config.head_dim,
194			],
195			vec![
196				config.batch_size,
197				config.sequence_length,
198				config.num_heads,
199				config.head_dim,
200			],
201			vec![config.batch_size, config.sequence_length, config.num_heads],
202			vec![config.batch_size, config.sequence_length, config.num_heads],
203			vec![config.batch_size, config.sequence_length, config.num_heads],
204			vec![
205				config.batch_size,
206				config.sequence_length,
207				config.num_rope_angles,
208			],
209			vec![config.num_heads, config.state_size],
210			vec![config.num_heads, config.state_size],
211			vec![config.num_heads],
212		];
213		if inputs
214			.iter()
215			.zip(expected.iter())
216			.any(|(matrix, shape)| matrix.shape() != shape)
217		{
218			return Err(Error::invalid_argument(format!(
219				"{operation} operands do not match the explicit SSM configuration"
220			)));
221		}
222		validate_f32_same_runtime(operation, inputs)?;
223		for shape in &expected {
224			let count = checked_count(shape, operation)?;
225			shader_u32(count, "tensor element count", operation)?;
226		}
227		let batch = shader_u32(config.batch_size, "batch size", operation)?;
228		let length = shader_u32(config.sequence_length, "sequence length", operation)?;
229		let heads = shader_u32(config.num_heads, "head count", operation)?;
230		let groups = shader_u32(groups, "group count", operation)?;
231		let head_dim = shader_u32(config.head_dim, "head dimension", operation)?;
232		let state_size = shader_u32(config.state_size, "state size", operation)?;
233		let angles = shader_u32(config.num_rope_angles, "rope angle count", operation)?;
234		let batch_heads = batch.checked_mul(heads).ok_or_else(|| {
235			Error::invalid_argument(format!("{operation} batch-head count exceeds u32"))
236		})?;
237		Ok(Self {
238			batch,
239			length,
240			heads,
241			groups,
242			head_dim,
243			state_size,
244			angles,
245			batch_heads,
246		})
247	}
248
249	fn output_shape(&self) -> Vec<usize> {
250		vec![
251			self.batch as usize,
252			self.length as usize,
253			self.heads as usize,
254			self.head_dim as usize,
255		]
256	}
257}
258
259struct MimoGeometry {
260	batch: u32,
261	length: u32,
262	heads: u32,
263	groups: u32,
264	head_dim: u32,
265	state_size: u32,
266	angles: u32,
267	rank: u32,
268	batch_heads: u32,
269}
270
271impl MimoGeometry {
272	fn resolve(inputs: &[&Matrix; 15], config: SsmConfig, operation: &'static str) -> Result<Self> {
273		let groups = if config.num_groups == 0 {
274			config.num_heads
275		} else {
276			config.num_groups
277		};
278		if config.batch_size == 0
279			|| config.sequence_length == 0
280			|| config.num_heads == 0
281			|| groups == 0
282			|| !config.num_heads.is_multiple_of(groups)
283			|| config.head_dim == 0
284			|| config.head_dim > 128
285			|| config.state_size == 0
286			|| config.state_size > 128
287			|| config.head_dim.saturating_mul(config.state_size) > 4096
288			|| config.num_rope_angles > 64
289			|| config.num_rope_angles.saturating_mul(2) > config.state_size
290			|| !(1..=8).contains(&config.mimo_rank)
291		{
292			return Err(Error::invalid_argument(format!(
293				"{operation} requires B/L/H/G/P/N > 0, H divisible by G, P/N <= 128, P*N <= 4096, A <= 64, 2A <= N, and MIMO rank in 1..=8"
294			)));
295		}
296		let rg = config.mimo_rank.checked_mul(groups).ok_or_else(|| {
297			Error::invalid_argument(format!("{operation} rank-group extent overflows usize"))
298		})?;
299		let expected = [
300			vec![
301				config.batch_size,
302				config.sequence_length,
303				rg,
304				config.state_size,
305			],
306			vec![
307				config.batch_size,
308				config.sequence_length,
309				rg,
310				config.state_size,
311			],
312			vec![
313				config.batch_size,
314				config.sequence_length,
315				config.num_heads,
316				config.head_dim,
317			],
318			vec![
319				config.batch_size,
320				config.sequence_length,
321				config.num_heads,
322				config.head_dim,
323			],
324			vec![config.batch_size, config.sequence_length, config.num_heads],
325			vec![config.batch_size, config.sequence_length, config.num_heads],
326			vec![config.batch_size, config.sequence_length, config.num_heads],
327			vec![
328				config.batch_size,
329				config.sequence_length,
330				config.num_rope_angles,
331			],
332			vec![config.num_heads, config.mimo_rank, config.state_size],
333			vec![config.num_heads, config.mimo_rank, config.state_size],
334			vec![config.num_heads],
335			vec![config.num_heads, config.mimo_rank, config.head_dim],
336			vec![config.num_heads, config.mimo_rank, config.head_dim],
337			vec![config.num_heads, config.mimo_rank, config.head_dim],
338			vec![config.num_heads, config.head_dim],
339		];
340		if inputs
341			.iter()
342			.zip(expected.iter())
343			.any(|(matrix, shape)| matrix.shape() != shape)
344		{
345			return Err(Error::invalid_argument(format!(
346				"{operation} operands do not match the explicit MIMO configuration"
347			)));
348		}
349		validate_f32_same_runtime(operation, inputs)?;
350		for shape in &expected {
351			shader_u32(
352				checked_count(shape, operation)?,
353				"tensor element count",
354				operation,
355			)?;
356		}
357		let batch = shader_u32(config.batch_size, "batch size", operation)?;
358		let length = shader_u32(config.sequence_length, "sequence length", operation)?;
359		let heads = shader_u32(config.num_heads, "head count", operation)?;
360		let groups = shader_u32(groups, "group count", operation)?;
361		let head_dim = shader_u32(config.head_dim, "head dimension", operation)?;
362		let state_size = shader_u32(config.state_size, "state size", operation)?;
363		let angles = shader_u32(config.num_rope_angles, "rope angle count", operation)?;
364		let rank = shader_u32(config.mimo_rank, "MIMO rank", operation)?;
365		let batch_heads = batch.checked_mul(heads).ok_or_else(|| {
366			Error::invalid_argument(format!("{operation} batch-head count exceeds u32"))
367		})?;
368		Ok(Self {
369			batch,
370			length,
371			heads,
372			groups,
373			head_dim,
374			state_size,
375			angles,
376			rank,
377			batch_heads,
378		})
379	}
380
381	fn output_shape(&self) -> Vec<usize> {
382		vec![
383			self.batch as usize,
384			self.length as usize,
385			self.heads as usize,
386			self.head_dim as usize,
387		]
388	}
389
390	fn push_constants(&self, config: SsmConfig) -> [PushConstant; 12] {
391		[
392			PushConstant::U32(self.batch),
393			PushConstant::U32(self.length),
394			PushConstant::U32(self.heads),
395			PushConstant::U32(self.groups),
396			PushConstant::U32(self.head_dim),
397			PushConstant::U32(self.state_size),
398			PushConstant::U32(self.angles),
399			PushConstant::U32(self.rank),
400			PushConstant::U32(u32::from(config.has_z)),
401			PushConstant::U32(u32::from(config.has_d)),
402			PushConstant::U32(u32::from(config.has_output_norm)),
403			PushConstant::F32(1.0e-5),
404		]
405	}
406}
407
408fn checked_count(shape: &[usize], operation: &'static str) -> Result<usize> {
409	shape.iter().try_fold(1_usize, |count, extent| {
410		count
411			.checked_mul(*extent)
412			.ok_or_else(|| Error::invalid_argument(format!("{operation} tensor size overflows usize")))
413	})
414}
415
416struct PreprocessGeometry {
417	rows: usize,
418	rows_u32: u32,
419	inner_size: usize,
420	inner_size_u32: u32,
421	state_size_u32: u32,
422	heads: usize,
423	heads_u32: u32,
424	rope_angles: usize,
425	rope_angles_u32: u32,
426	bc_rows_u32: u32,
427	bc_width: usize,
428}
429
430impl PreprocessGeometry {
431	fn resolve(
432		projected: &Matrix,
433		dt_bias: &Matrix,
434		config: Mamba3PreprocessConfig,
435		operation: &'static str,
436	) -> Result<Self> {
437		let [rows, projected_width] = projected.shape() else {
438			return Err(Error::invalid_argument(format!(
439				"{operation} projected input must have shape [rows, width]"
440			)));
441		};
442		if *rows == 0
443			|| config.inner_size == 0
444			|| config.state_size == 0
445			|| config.num_heads == 0
446			|| config.num_groups == 0
447			|| config.mimo_rank == 0
448			|| config.num_rope_angles.saturating_mul(2) > config.state_size
449			|| !config.epsilon.is_finite()
450			|| config.epsilon <= 0.0
451			|| !config.dt_min.is_finite()
452			|| !config.dt_max.is_finite()
453			|| config.dt_min <= 0.0
454			|| config.dt_min > config.dt_max
455			|| !config.a_floor.is_finite()
456			|| config.a_floor <= 0.0
457		{
458			return Err(Error::invalid_argument(format!(
459				"{operation} requires positive geometry, 2*rope_angles <= state_size, finite epsilon/dt/A bounds, epsilon/dt_min/A floor > 0, and dt_min <= dt_max"
460			)));
461		}
462		let bc_rows = config
463			.num_groups
464			.checked_mul(config.mimo_rank)
465			.ok_or_else(|| Error::invalid_argument(format!("{operation} B/C row count overflows")))?;
466		let bc_width = bc_rows
467			.checked_mul(config.state_size)
468			.ok_or_else(|| Error::invalid_argument(format!("{operation} B/C width overflows")))?;
469		let expected_width = config
470			.inner_size
471			.checked_mul(2)
472			.and_then(|value| bc_width.checked_mul(2).and_then(|bc| value.checked_add(bc)))
473			.and_then(|value| {
474				config
475					.num_heads
476					.checked_mul(3)
477					.and_then(|heads| value.checked_add(heads))
478			})
479			.and_then(|value| value.checked_add(config.num_rope_angles))
480			.ok_or_else(|| {
481				Error::invalid_argument(format!("{operation} projected width overflows usize"))
482			})?;
483		if *projected_width != expected_width || dt_bias.shape() != [config.num_heads] {
484			return Err(Error::invalid_argument(format!(
485				"{operation} projected width or dt-bias shape does not match the configuration"
486			)));
487		}
488		validate_f32_same_runtime(operation, &[projected, dt_bias])?;
489		shader_u32(expected_width, "projected row width", operation)?;
490		shader_u32(bc_width, "B/C width", operation)?;
491		for (label, shape) in [
492			("projected element count", projected.shape()),
493			("vector output element count", &[*rows, config.inner_size]),
494			("B/C output element count", &[*rows, bc_width]),
495			("scalar output element count", &[*rows, config.num_heads]),
496			(
497				"angle output element count",
498				&[*rows, config.num_rope_angles],
499			),
500		] {
501			shader_u32(checked_count(shape, operation)?, label, operation)?;
502		}
503		Ok(Self {
504			rows: *rows,
505			rows_u32: shader_u32(*rows, "row count", operation)?,
506			inner_size: config.inner_size,
507			inner_size_u32: shader_u32(config.inner_size, "inner size", operation)?,
508			state_size_u32: shader_u32(config.state_size, "state size", operation)?,
509			heads: config.num_heads,
510			heads_u32: shader_u32(config.num_heads, "head count", operation)?,
511			rope_angles: config.num_rope_angles,
512			rope_angles_u32: shader_u32(config.num_rope_angles, "rope angle count", operation)?,
513			bc_rows_u32: shader_u32(bc_rows, "B/C row count", operation)?,
514			bc_width,
515		})
516	}
517
518	fn output_shapes(&self) -> [Vec<usize>; 4] {
519		[
520			vec![self.rows, self.inner_size],
521			vec![self.rows, self.bc_width],
522			vec![self.rows, self.heads],
523			vec![self.rows, self.rope_angles],
524		]
525	}
526
527	fn scalar_push_constants(&self, config: Mamba3PreprocessConfig) -> [PushConstant; 10] {
528		[
529			PushConstant::U32(self.rows_u32),
530			PushConstant::U32(self.inner_size_u32),
531			PushConstant::U32(self.state_size_u32),
532			PushConstant::U32(self.heads_u32),
533			PushConstant::U32(self.rope_angles_u32),
534			PushConstant::U32(self.bc_rows_u32),
535			PushConstant::F32(config.epsilon),
536			PushConstant::F32(config.dt_min),
537			PushConstant::F32(config.dt_max),
538			PushConstant::F32(config.a_floor),
539		]
540	}
541}
542
543// ---------------------------------------------------------------------------
544// Private Mamba-3 GPU dispatch providers
545// ---------------------------------------------------------------------------
546
547fn dispatch_mamba3_preprocess(
548	projected: &Matrix,
549	dt_bias: &Matrix,
550	config: Mamba3PreprocessConfig,
551) -> Result<Mamba3PreprocessResult> {
552	let contract = crate::core::operation::ml::MAMBA3_PREPROCESS;
553	let operation = contract.name();
554	let geometry = PreprocessGeometry::resolve(projected, dt_bias, config, operation)?;
555	let [vector_shape, bc_shape, scalar_shape, angle_shape] = geometry.output_shapes();
556	let runtime = projected.runtime();
557	let allocate = |shape: Vec<usize>| {
558		let count = checked_count(&shape, operation)?;
559		shader_u32(count, "output element count", operation)?;
560		Matrix::allocate(runtime, shape, count, DType::F32)
561	};
562	let result = Mamba3PreprocessResult {
563		x: allocate(vector_shape.clone())?,
564		z: allocate(vector_shape)?,
565		bh: allocate(bc_shape.clone())?,
566		ch: allocate(bc_shape)?,
567		dt: allocate(scalar_shape.clone())?,
568		adt: allocate(scalar_shape.clone())?,
569		trap: allocate(scalar_shape)?,
570		angle: allocate(angle_shape)?,
571	};
572	let buffers = [
573		BufferBinding::read(projected.storage()),
574		BufferBinding::read(dt_bias.storage()),
575		BufferBinding::write(result.z.storage()),
576		BufferBinding::write(result.x.storage()),
577		BufferBinding::write(result.bh.storage()),
578		BufferBinding::write(result.ch.storage()),
579		BufferBinding::write(result.dt.storage()),
580		BufferBinding::write(result.adt.storage()),
581		BufferBinding::write(result.trap.storage()),
582		BufferBinding::write(result.angle.storage()),
583	];
584	let push_constants = geometry.scalar_push_constants(config);
585	let attributes = [OpAttribute::UnsignedInteger {
586		name: "configIdentity".into(),
587		value: config.identity(operation)?,
588	}];
589	let inputs = [projected, dt_bias];
590	let outputs = result.matrices();
591	runtime.record_semantic(
592		ComputeDispatch {
593			kernel: KernelId::MlMamba3PreprocessF32,
594			buffers: &buffers,
595			push_constants: &push_constants,
596			workgroups: [geometry.rows_u32, 1, 1],
597			indirect: None,
598		},
599		SemanticDispatch {
600			contract,
601			inputs: &inputs,
602			outputs: &outputs,
603			attributes: &attributes,
604		},
605	)?;
606	Ok(result)
607}
608
609fn dispatch_mamba3_preprocess_backward(
610	projected: &Matrix,
611	dt_bias: &Matrix,
612	output_gradients: &Mamba3PreprocessResult,
613	config: Mamba3PreprocessConfig,
614) -> Result<Mamba3PreprocessBackwardResult> {
615	let contract = crate::core::operation::ml::MAMBA3_PREPROCESS_BACKWARD;
616	let operation = contract.name();
617	let geometry = PreprocessGeometry::resolve(projected, dt_bias, config, operation)?;
618	let [vector_shape, bc_shape, scalar_shape, angle_shape] = geometry.output_shapes();
619	let expected = [
620		vector_shape.as_slice(),
621		vector_shape.as_slice(),
622		bc_shape.as_slice(),
623		bc_shape.as_slice(),
624		scalar_shape.as_slice(),
625		scalar_shape.as_slice(),
626		scalar_shape.as_slice(),
627		angle_shape.as_slice(),
628	];
629	let gradient_matrices = output_gradients.matrices();
630	if gradient_matrices
631		.iter()
632		.zip(expected)
633		.any(|(matrix, shape)| matrix.shape() != shape)
634	{
635		return Err(Error::invalid_argument(format!(
636			"{operation} output gradients do not match the configured outputs"
637		)));
638	}
639	let mut all_inputs = Vec::with_capacity(10);
640	all_inputs.extend([projected, dt_bias]);
641	all_inputs.extend(gradient_matrices);
642	validate_f32_same_runtime(operation, &all_inputs)?;
643
644	let projected_gradient = Matrix::allocate(
645		projected.runtime(),
646		projected.shape().to_vec(),
647		projected.element_count(),
648		DType::F32,
649	)?;
650	let partial_count = geometry
651		.rows
652		.checked_mul(geometry.heads)
653		.ok_or_else(|| Error::invalid_argument(format!("{operation} partial size overflows")))?;
654	let dt_bias_partial = Matrix::allocate(
655		projected.runtime(),
656		vec![geometry.rows, geometry.heads],
657		partial_count,
658		DType::F32,
659	)?;
660	let dt_bias_gradient = Matrix::allocate(
661		projected.runtime(),
662		vec![geometry.heads],
663		geometry.heads,
664		DType::F32,
665	)?;
666	let buffers = [
667		BufferBinding::read(projected.storage()),
668		BufferBinding::read(dt_bias.storage()),
669		BufferBinding::read(output_gradients.z.storage()),
670		BufferBinding::read(output_gradients.x.storage()),
671		BufferBinding::read(output_gradients.bh.storage()),
672		BufferBinding::read(output_gradients.ch.storage()),
673		BufferBinding::read(output_gradients.dt.storage()),
674		BufferBinding::read(output_gradients.adt.storage()),
675		BufferBinding::read(output_gradients.trap.storage()),
676		BufferBinding::read(output_gradients.angle.storage()),
677		BufferBinding::write(projected_gradient.storage()),
678		BufferBinding::write(dt_bias_partial.storage()),
679	];
680	let push_constants = geometry.scalar_push_constants(config);
681	let reduce_buffers = [
682		BufferBinding::read(dt_bias_partial.storage()),
683		BufferBinding::write(dt_bias_gradient.storage()),
684	];
685	let reduce_push_constants = [
686		PushConstant::U32(geometry.rows_u32),
687		PushConstant::U32(geometry.heads_u32),
688	];
689	let dispatches = [
690		ComputeDispatch {
691			kernel: KernelId::MlMamba3PreprocessBackwardF32,
692			buffers: &buffers,
693			push_constants: &push_constants,
694			workgroups: [geometry.rows_u32, 1, 1],
695			indirect: None,
696		},
697		ComputeDispatch {
698			kernel: KernelId::MlMamba3PreprocessBackwardReduceF32,
699			buffers: &reduce_buffers,
700			push_constants: &reduce_push_constants,
701			workgroups: [geometry.heads_u32.div_ceil(256), 1, 1],
702			indirect: None,
703		},
704	];
705	let attributes = [OpAttribute::UnsignedInteger {
706		name: "config_identity".into(),
707		value: config.identity(operation)?,
708	}];
709	let outputs = [&projected_gradient, &dt_bias_gradient];
710	projected.runtime().record_split_semantic(
711		&dispatches,
712		SemanticDispatch {
713			contract,
714			inputs: &all_inputs,
715			outputs: &outputs,
716			attributes: &attributes,
717		},
718	)?;
719	Ok(Mamba3PreprocessBackwardResult {
720		projected: projected_gradient,
721		dt_bias: dt_bias_gradient,
722	})
723}
724
725#[allow(
726	clippy::too_many_arguments,
727	reason = "preserves the donor eleven-operand selective-scan boundary"
728)]
729fn dispatch_mamba3_siso(
730	c: &Matrix,
731	b: &Matrix,
732	x: &Matrix,
733	z: &Matrix,
734	adt: &Matrix,
735	dt: &Matrix,
736	trap: &Matrix,
737	angle: &Matrix,
738	c_bias: &Matrix,
739	b_bias: &Matrix,
740	d: &Matrix,
741	config: SsmConfig,
742) -> Result<Matrix> {
743	let contract = crate::core::operation::ml::MAMBA3_SISO;
744	let operation = contract.name();
745	let inputs = [c, b, x, z, adt, dt, trap, angle, c_bias, b_bias, d];
746	let geometry = Geometry::resolve(&inputs, config, operation)?;
747	let output_shape = geometry.output_shape();
748	let output = Matrix::allocate(
749		x.runtime(),
750		output_shape.clone(),
751		checked_count(&output_shape, operation)?,
752		DType::F32,
753	)?;
754	let buffers = [
755		BufferBinding::read(c.storage()),
756		BufferBinding::read(b.storage()),
757		BufferBinding::read(x.storage()),
758		BufferBinding::read(z.storage()),
759		BufferBinding::read(adt.storage()),
760		BufferBinding::read(dt.storage()),
761		BufferBinding::read(trap.storage()),
762		BufferBinding::read(angle.storage()),
763		BufferBinding::read(c_bias.storage()),
764		BufferBinding::read(b_bias.storage()),
765		BufferBinding::read(d.storage()),
766		BufferBinding::write(output.storage()),
767	];
768	let push_constants = [
769		PushConstant::U32(geometry.batch),
770		PushConstant::U32(geometry.length),
771		PushConstant::U32(geometry.heads),
772		PushConstant::U32(geometry.groups),
773		PushConstant::U32(geometry.head_dim),
774		PushConstant::U32(geometry.state_size),
775		PushConstant::U32(geometry.angles),
776		PushConstant::U32(u32::from(config.has_z)),
777		PushConstant::U32(u32::from(config.has_d)),
778	];
779	let attributes = [OpAttribute::UnsignedInteger {
780		name: "configIdentity".into(),
781		value: config.identity(operation)?,
782	}];
783	let outputs = [&output];
784	x.runtime().record_semantic(
785		ComputeDispatch {
786			kernel: KernelId::MlMamba3SisoF32,
787			buffers: &buffers,
788			push_constants: &push_constants,
789			workgroups: [geometry.batch_heads, 1, 1],
790			indirect: None,
791		},
792		SemanticDispatch {
793			contract,
794			inputs: &inputs,
795			outputs: &outputs,
796			attributes: &attributes,
797		},
798	)?;
799	Ok(output)
800}
801
802#[allow(
803	clippy::too_many_arguments,
804	reason = "preserves the donor eleven operands plus four explicit recurrent-state buffers"
805)]
806fn dispatch_mamba3_siso_step(
807	c: &Matrix,
808	b: &Matrix,
809	x: &Matrix,
810	z: &Matrix,
811	adt: &Matrix,
812	dt: &Matrix,
813	trap: &Matrix,
814	angle: &Matrix,
815	c_bias: &Matrix,
816	b_bias: &Matrix,
817	d: &Matrix,
818	ssm_state: &Matrix,
819	angle_state: &Matrix,
820	k_state: &Matrix,
821	v_state: &Matrix,
822	config: SsmConfig,
823) -> Result<Matrix> {
824	let contract = crate::core::operation::ml::MAMBA3_SISO_STEP;
825	let operation = contract.name();
826	let operands = [c, b, x, z, adt, dt, trap, angle, c_bias, b_bias, d];
827	let geometry = Geometry::resolve(&operands, config, operation)?;
828	if geometry.length != 1 {
829		return Err(Error::invalid_argument(format!(
830			"{operation} requires sequence_length == 1"
831		)));
832	}
833	let expected_states = [
834		vec![
835			geometry.batch as usize,
836			geometry.heads as usize,
837			geometry.head_dim as usize,
838			geometry.state_size as usize,
839		],
840		vec![
841			geometry.batch as usize,
842			geometry.heads as usize,
843			geometry.angles as usize,
844		],
845		vec![
846			geometry.batch as usize,
847			geometry.heads as usize,
848			geometry.state_size as usize,
849		],
850		vec![
851			geometry.batch as usize,
852			geometry.heads as usize,
853			geometry.head_dim as usize,
854		],
855	];
856	let states = [ssm_state, angle_state, k_state, v_state];
857	if states
858		.iter()
859		.zip(expected_states.iter())
860		.any(|(state, shape)| state.shape() != shape)
861	{
862		return Err(Error::invalid_argument(format!(
863			"{operation} recurrent-state shapes do not match the explicit configuration"
864		)));
865	}
866	validate_f32_same_runtime(operation, &[x, ssm_state, angle_state, k_state, v_state])?;
867	for shape in &expected_states {
868		shader_u32(
869			checked_count(shape, operation)?,
870			"state element count",
871			operation,
872		)?;
873	}
874
875	let output_shape = geometry.output_shape();
876	let output = Matrix::allocate(
877		x.runtime(),
878		output_shape.clone(),
879		checked_count(&output_shape, operation)?,
880		DType::F32,
881	)?;
882	let buffers = [
883		BufferBinding::read(c.storage()),
884		BufferBinding::read(b.storage()),
885		BufferBinding::read(x.storage()),
886		BufferBinding::read(z.storage()),
887		BufferBinding::read(adt.storage()),
888		BufferBinding::read(dt.storage()),
889		BufferBinding::read(trap.storage()),
890		BufferBinding::read(angle.storage()),
891		BufferBinding::read(c_bias.storage()),
892		BufferBinding::read(b_bias.storage()),
893		BufferBinding::read(d.storage()),
894		BufferBinding::write(output.storage()),
895		BufferBinding::read_write(ssm_state.storage()),
896		BufferBinding::read_write(angle_state.storage()),
897		BufferBinding::read_write(k_state.storage()),
898		BufferBinding::read_write(v_state.storage()),
899	];
900	let push_constants = [
901		PushConstant::U32(geometry.batch),
902		PushConstant::U32(geometry.heads),
903		PushConstant::U32(geometry.groups),
904		PushConstant::U32(geometry.head_dim),
905		PushConstant::U32(geometry.state_size),
906		PushConstant::U32(geometry.angles),
907		PushConstant::U32(u32::from(config.has_z)),
908		PushConstant::U32(u32::from(config.has_d)),
909	];
910	let attributes = [OpAttribute::UnsignedInteger {
911		name: "config_identity".into(),
912		value: config.identity(operation)?,
913	}];
914	let semantic_inputs = [
915		ssm_state,
916		angle_state,
917		k_state,
918		v_state,
919		c,
920		b,
921		x,
922		z,
923		adt,
924		dt,
925		trap,
926		angle,
927		c_bias,
928		b_bias,
929		d,
930	];
931	let semantic_outputs = [&output, ssm_state, angle_state, k_state, v_state];
932	x.runtime().record_semantic(
933		ComputeDispatch {
934			kernel: KernelId::MlMamba3SisoStepF32,
935			buffers: &buffers,
936			push_constants: &push_constants,
937			workgroups: [geometry.batch_heads, 1, 1],
938			indirect: None,
939		},
940		SemanticDispatch {
941			contract,
942			inputs: &semantic_inputs,
943			outputs: &semantic_outputs,
944			attributes: &attributes,
945		},
946	)?;
947	Ok(output)
948}
949
950#[allow(
951	clippy::too_many_arguments,
952	reason = "preserves the donor fifteen-operand MIMO selective-scan boundary"
953)]
954fn dispatch_mamba3_mimo(
955	c: &Matrix,
956	b: &Matrix,
957	x: &Matrix,
958	z: &Matrix,
959	adt: &Matrix,
960	dt: &Matrix,
961	trap: &Matrix,
962	angle: &Matrix,
963	c_bias: &Matrix,
964	b_bias: &Matrix,
965	d: &Matrix,
966	mimo_x: &Matrix,
967	mimo_z: &Matrix,
968	mimo_o: &Matrix,
969	norm_weight: &Matrix,
970	config: SsmConfig,
971) -> Result<Matrix> {
972	let contract = crate::core::operation::ml::MAMBA3_MIMO;
973	let operation = contract.name();
974	let inputs = [
975		c,
976		b,
977		x,
978		z,
979		adt,
980		dt,
981		trap,
982		angle,
983		c_bias,
984		b_bias,
985		d,
986		mimo_x,
987		mimo_z,
988		mimo_o,
989		norm_weight,
990	];
991	let geometry = MimoGeometry::resolve(&inputs, config, operation)?;
992	let output_shape = geometry.output_shape();
993	let output = Matrix::allocate(
994		x.runtime(),
995		output_shape.clone(),
996		checked_count(&output_shape, operation)?,
997		DType::F32,
998	)?;
999	let buffers = [
1000		BufferBinding::read(c.storage()),
1001		BufferBinding::read(b.storage()),
1002		BufferBinding::read(x.storage()),
1003		BufferBinding::read(z.storage()),
1004		BufferBinding::read(adt.storage()),
1005		BufferBinding::read(dt.storage()),
1006		BufferBinding::read(trap.storage()),
1007		BufferBinding::read(angle.storage()),
1008		BufferBinding::read(c_bias.storage()),
1009		BufferBinding::read(b_bias.storage()),
1010		BufferBinding::read(d.storage()),
1011		BufferBinding::read(mimo_x.storage()),
1012		BufferBinding::read(mimo_z.storage()),
1013		BufferBinding::read(mimo_o.storage()),
1014		BufferBinding::read(norm_weight.storage()),
1015		BufferBinding::write(output.storage()),
1016	];
1017	let push_constants = geometry.push_constants(config);
1018	let attributes = [OpAttribute::UnsignedInteger {
1019		name: "configIdentity".into(),
1020		value: config.identity(operation)?,
1021	}];
1022	let outputs = [&output];
1023	x.runtime().record_semantic(
1024		ComputeDispatch {
1025			kernel: KernelId::MlMamba3MimoF32,
1026			buffers: &buffers,
1027			push_constants: &push_constants,
1028			workgroups: [geometry.batch_heads, 1, 1],
1029			indirect: None,
1030		},
1031		SemanticDispatch {
1032			contract,
1033			inputs: &inputs,
1034			outputs: &outputs,
1035			attributes: &attributes,
1036		},
1037	)?;
1038	Ok(output)
1039}
1040
1041#[allow(
1042	clippy::too_many_arguments,
1043	reason = "preserves the donor fifteen operands plus four explicit recurrent-state buffers"
1044)]
1045fn dispatch_mamba3_mimo_step(
1046	c: &Matrix,
1047	b: &Matrix,
1048	x: &Matrix,
1049	z: &Matrix,
1050	adt: &Matrix,
1051	dt: &Matrix,
1052	trap: &Matrix,
1053	angle: &Matrix,
1054	c_bias: &Matrix,
1055	b_bias: &Matrix,
1056	d: &Matrix,
1057	mimo_x: &Matrix,
1058	mimo_z: &Matrix,
1059	mimo_o: &Matrix,
1060	norm_weight: &Matrix,
1061	ssm_state: &Matrix,
1062	angle_state: &Matrix,
1063	k_state: &Matrix,
1064	v_state: &Matrix,
1065	config: SsmConfig,
1066) -> Result<Matrix> {
1067	let contract = crate::core::operation::ml::MAMBA3_MIMO_STEP;
1068	let operation = contract.name();
1069	let operands = [
1070		c,
1071		b,
1072		x,
1073		z,
1074		adt,
1075		dt,
1076		trap,
1077		angle,
1078		c_bias,
1079		b_bias,
1080		d,
1081		mimo_x,
1082		mimo_z,
1083		mimo_o,
1084		norm_weight,
1085	];
1086	let geometry = MimoGeometry::resolve(&operands, config, operation)?;
1087	if geometry.length != 1 {
1088		return Err(Error::invalid_argument(format!(
1089			"{operation} requires sequence_length == 1"
1090		)));
1091	}
1092	let expected_states = [
1093		vec![
1094			geometry.batch as usize,
1095			geometry.heads as usize,
1096			geometry.head_dim as usize,
1097			geometry.state_size as usize,
1098		],
1099		vec![
1100			geometry.batch as usize,
1101			geometry.heads as usize,
1102			geometry.angles as usize,
1103		],
1104		vec![
1105			geometry.batch as usize,
1106			geometry.heads as usize,
1107			geometry.rank as usize,
1108			geometry.state_size as usize,
1109		],
1110		vec![
1111			geometry.batch as usize,
1112			geometry.heads as usize,
1113			geometry.rank as usize,
1114			geometry.head_dim as usize,
1115		],
1116	];
1117	let states = [ssm_state, angle_state, k_state, v_state];
1118	if states
1119		.iter()
1120		.zip(expected_states.iter())
1121		.any(|(state, shape)| state.shape() != shape)
1122	{
1123		return Err(Error::invalid_argument(format!(
1124			"{operation} recurrent-state shapes do not match the explicit MIMO configuration"
1125		)));
1126	}
1127	validate_f32_same_runtime(operation, &[x, ssm_state, angle_state, k_state, v_state])?;
1128	for shape in &expected_states {
1129		shader_u32(
1130			checked_count(shape, operation)?,
1131			"state element count",
1132			operation,
1133		)?;
1134	}
1135	let output_shape = geometry.output_shape();
1136	let output = Matrix::allocate(
1137		x.runtime(),
1138		output_shape.clone(),
1139		checked_count(&output_shape, operation)?,
1140		DType::F32,
1141	)?;
1142	let buffers = [
1143		BufferBinding::read(c.storage()),
1144		BufferBinding::read(b.storage()),
1145		BufferBinding::read(x.storage()),
1146		BufferBinding::read(z.storage()),
1147		BufferBinding::read(adt.storage()),
1148		BufferBinding::read(dt.storage()),
1149		BufferBinding::read(trap.storage()),
1150		BufferBinding::read(angle.storage()),
1151		BufferBinding::read(c_bias.storage()),
1152		BufferBinding::read(b_bias.storage()),
1153		BufferBinding::read(d.storage()),
1154		BufferBinding::read(mimo_x.storage()),
1155		BufferBinding::read(mimo_z.storage()),
1156		BufferBinding::read(mimo_o.storage()),
1157		BufferBinding::read(norm_weight.storage()),
1158		BufferBinding::write(output.storage()),
1159		BufferBinding::read_write(ssm_state.storage()),
1160		BufferBinding::read_write(angle_state.storage()),
1161		BufferBinding::read_write(k_state.storage()),
1162		BufferBinding::read_write(v_state.storage()),
1163	];
1164	let push_constants = [
1165		PushConstant::U32(geometry.batch),
1166		PushConstant::U32(geometry.heads),
1167		PushConstant::U32(geometry.groups),
1168		PushConstant::U32(geometry.head_dim),
1169		PushConstant::U32(geometry.state_size),
1170		PushConstant::U32(geometry.angles),
1171		PushConstant::U32(geometry.rank),
1172		PushConstant::U32(u32::from(config.has_z)),
1173		PushConstant::U32(u32::from(config.has_d)),
1174		PushConstant::U32(u32::from(config.has_output_norm)),
1175		PushConstant::F32(1.0e-5),
1176	];
1177	let attributes = [OpAttribute::UnsignedInteger {
1178		name: "config_identity".into(),
1179		value: config.identity(operation)?,
1180	}];
1181	let semantic_inputs = [
1182		ssm_state,
1183		angle_state,
1184		k_state,
1185		v_state,
1186		c,
1187		b,
1188		x,
1189		z,
1190		adt,
1191		dt,
1192		trap,
1193		angle,
1194		c_bias,
1195		b_bias,
1196		d,
1197		mimo_x,
1198		mimo_z,
1199		mimo_o,
1200		norm_weight,
1201	];
1202	let semantic_outputs = [&output, ssm_state, angle_state, k_state, v_state];
1203	x.runtime().record_semantic(
1204		ComputeDispatch {
1205			kernel: KernelId::MlMamba3MimoStepF32,
1206			buffers: &buffers,
1207			push_constants: &push_constants,
1208			workgroups: [geometry.batch_heads, 1, 1],
1209			indirect: None,
1210		},
1211		SemanticDispatch {
1212			contract,
1213			inputs: &semantic_inputs,
1214			outputs: &semantic_outputs,
1215			attributes: &attributes,
1216		},
1217	)?;
1218	Ok(output)
1219}
1220
1221// ---------------------------------------------------------------------------
1222
1223#[allow(
1224	clippy::too_many_arguments,
1225	reason = "preserves the donor upstream plus fifteen-operand MIMO adjoint boundary"
1226)]
1227fn dispatch_mamba3_mimo_backward(
1228	output_gradient: &Matrix,
1229	c: &Matrix,
1230	b: &Matrix,
1231	x: &Matrix,
1232	z: &Matrix,
1233	adt: &Matrix,
1234	dt: &Matrix,
1235	trap: &Matrix,
1236	angle: &Matrix,
1237	c_bias: &Matrix,
1238	b_bias: &Matrix,
1239	d: &Matrix,
1240	mimo_x: &Matrix,
1241	mimo_z: &Matrix,
1242	mimo_o: &Matrix,
1243	norm_weight: &Matrix,
1244	config: SsmConfig,
1245) -> Result<Mamba3MimoBackwardResult> {
1246	let contract = crate::core::operation::ml::MAMBA3_MIMO_BACKWARD;
1247	let operation = contract.name();
1248	let operands = [
1249		c,
1250		b,
1251		x,
1252		z,
1253		adt,
1254		dt,
1255		trap,
1256		angle,
1257		c_bias,
1258		b_bias,
1259		d,
1260		mimo_x,
1261		mimo_z,
1262		mimo_o,
1263		norm_weight,
1264	];
1265	let geometry = MimoGeometry::resolve(&operands, config, operation)?;
1266	if output_gradient.shape() != geometry.output_shape() {
1267		return Err(Error::invalid_argument(format!(
1268			"{operation} output gradient does not match the configured output"
1269		)));
1270	}
1271	validate_f32_same_runtime(operation, &[output_gradient, x])?;
1272
1273	let runtime = x.runtime();
1274	let alloc = |shape: Vec<usize>| -> Result<Matrix> {
1275		let count = checked_count(&shape, operation)?;
1276		shader_u32(count, "temporary element count", operation)?;
1277		Matrix::allocate(runtime, shape, count, DType::F32)
1278	};
1279	let batch = geometry.batch as usize;
1280	let length = geometry.length as usize;
1281	let heads = geometry.heads as usize;
1282	let groups = geometry.groups as usize;
1283	let head_dim = geometry.head_dim as usize;
1284	let state_size = geometry.state_size as usize;
1285	let angles = geometry.angles as usize;
1286	let rank = geometry.rank as usize;
1287	let scalar_shape = vec![batch, length, heads];
1288	let vector_shape = vec![batch, length, heads, head_dim];
1289	let qk_shape = vec![batch, length, heads, rank, state_size];
1290
1291	let q = alloc(qk_shape.clone())?;
1292	let k = alloc(qk_shape.clone())?;
1293	let theta = alloc(vec![batch, heads, length, angles])?;
1294	let h_previous = alloc(vec![batch * heads, length, head_dim, state_size])?;
1295	let decay = alloc(scalar_shape.clone())?;
1296	let gamma = alloc(scalar_shape.clone())?;
1297	let scale = alloc(scalar_shape.clone())?;
1298
1299	let d_pre = alloc(vec![batch, length, heads, rank, head_dim])?;
1300	let d_z = alloc(vector_shape.clone())?;
1301	let d_mimo_z_batch = alloc(vec![batch, heads, rank, head_dim])?;
1302	let d_mimo_o_batch = alloc(vec![batch, heads, rank, head_dim])?;
1303	let d_norm_batch = alloc(vec![batch, heads, head_dim])?;
1304
1305	let d_q = alloc(qk_shape.clone())?;
1306	let d_k = alloc(qk_shape.clone())?;
1307	let d_x = alloc(vector_shape)?;
1308	let d_adt = alloc(scalar_shape.clone())?;
1309	let d_dt = alloc(scalar_shape.clone())?;
1310	let d_trap = alloc(scalar_shape.clone())?;
1311	let d_d_batch = alloc(vec![batch, heads])?;
1312	let d_mimo_x_batch = alloc(vec![batch, heads, rank, head_dim])?;
1313	let d_scale_tmp = alloc(scalar_shape)?;
1314
1315	let d_c_head = alloc(qk_shape.clone())?;
1316	let d_b_head = alloc(qk_shape)?;
1317	let d_angle_head = alloc(vec![batch, heads, length, angles])?;
1318	let d_c_bias_batch = alloc(vec![batch, heads, rank, state_size])?;
1319	let d_b_bias_batch = alloc(vec![batch, heads, rank, state_size])?;
1320
1321	let d_c = alloc(vec![batch, length, rank * groups, state_size])?;
1322	let d_b = alloc(vec![batch, length, rank * groups, state_size])?;
1323	let d_angle = alloc(vec![batch, length, angles])?;
1324	let d_c_bias = alloc(vec![heads, rank, state_size])?;
1325	let d_b_bias = alloc(vec![heads, rank, state_size])?;
1326	let d_d = alloc(vec![heads])?;
1327	let d_mimo_x = alloc(vec![heads, rank, head_dim])?;
1328	let d_mimo_z = alloc(vec![heads, rank, head_dim])?;
1329	let d_mimo_o = alloc(vec![heads, rank, head_dim])?;
1330	let d_norm_weight = alloc(vec![heads, head_dim])?;
1331
1332	let prepare_buffers = [
1333		BufferBinding::read(c.storage()),
1334		BufferBinding::read(b.storage()),
1335		BufferBinding::read(x.storage()),
1336		BufferBinding::read(adt.storage()),
1337		BufferBinding::read(dt.storage()),
1338		BufferBinding::read(trap.storage()),
1339		BufferBinding::read(angle.storage()),
1340		BufferBinding::read(c_bias.storage()),
1341		BufferBinding::read(b_bias.storage()),
1342		BufferBinding::read(mimo_x.storage()),
1343		BufferBinding::write(q.storage()),
1344		BufferBinding::write(k.storage()),
1345		BufferBinding::write(theta.storage()),
1346		BufferBinding::write(h_previous.storage()),
1347		BufferBinding::write(decay.storage()),
1348		BufferBinding::write(gamma.storage()),
1349		BufferBinding::write(scale.storage()),
1350	];
1351	let prepare_constants = [
1352		PushConstant::U32(geometry.batch),
1353		PushConstant::U32(geometry.length),
1354		PushConstant::U32(geometry.heads),
1355		PushConstant::U32(geometry.groups),
1356		PushConstant::U32(geometry.head_dim),
1357		PushConstant::U32(geometry.state_size),
1358		PushConstant::U32(geometry.angles),
1359		PushConstant::U32(geometry.rank),
1360	];
1361
1362	let post_buffers = [
1363		BufferBinding::read(output_gradient.storage()),
1364		BufferBinding::read(x.storage()),
1365		BufferBinding::read(z.storage()),
1366		BufferBinding::read(d.storage()),
1367		BufferBinding::read(mimo_x.storage()),
1368		BufferBinding::read(mimo_z.storage()),
1369		BufferBinding::read(mimo_o.storage()),
1370		BufferBinding::read(norm_weight.storage()),
1371		BufferBinding::read(q.storage()),
1372		BufferBinding::read(k.storage()),
1373		BufferBinding::read(h_previous.storage()),
1374		BufferBinding::read(decay.storage()),
1375		BufferBinding::read(gamma.storage()),
1376		BufferBinding::write(d_pre.storage()),
1377		BufferBinding::write(d_z.storage()),
1378		BufferBinding::write(d_mimo_z_batch.storage()),
1379		BufferBinding::write(d_mimo_o_batch.storage()),
1380		BufferBinding::write(d_norm_batch.storage()),
1381	];
1382	let post_constants = [
1383		PushConstant::U32(geometry.batch),
1384		PushConstant::U32(geometry.length),
1385		PushConstant::U32(geometry.heads),
1386		PushConstant::U32(geometry.head_dim),
1387		PushConstant::U32(geometry.state_size),
1388		PushConstant::U32(geometry.rank),
1389		PushConstant::U32(u32::from(config.has_z)),
1390		PushConstant::U32(u32::from(config.has_d)),
1391		PushConstant::U32(u32::from(config.has_output_norm)),
1392		PushConstant::F32(1.0e-5),
1393	];
1394
1395	let core_buffers = [
1396		BufferBinding::read(d_pre.storage()),
1397		BufferBinding::read(x.storage()),
1398		BufferBinding::read(d.storage()),
1399		BufferBinding::read(mimo_x.storage()),
1400		BufferBinding::read(q.storage()),
1401		BufferBinding::read(k.storage()),
1402		BufferBinding::read(h_previous.storage()),
1403		BufferBinding::read(decay.storage()),
1404		BufferBinding::read(gamma.storage()),
1405		BufferBinding::read(scale.storage()),
1406		BufferBinding::read(dt.storage()),
1407		BufferBinding::read(trap.storage()),
1408		BufferBinding::write(d_q.storage()),
1409		BufferBinding::write(d_k.storage()),
1410		BufferBinding::write(d_x.storage()),
1411		BufferBinding::write(d_adt.storage()),
1412		BufferBinding::write(d_dt.storage()),
1413		BufferBinding::write(d_trap.storage()),
1414		BufferBinding::write(d_d_batch.storage()),
1415		BufferBinding::write(d_mimo_x_batch.storage()),
1416		BufferBinding::write(d_scale_tmp.storage()),
1417	];
1418	let core_constants = [
1419		PushConstant::U32(geometry.batch),
1420		PushConstant::U32(geometry.length),
1421		PushConstant::U32(geometry.heads),
1422		PushConstant::U32(geometry.head_dim),
1423		PushConstant::U32(geometry.state_size),
1424		PushConstant::U32(geometry.rank),
1425		PushConstant::U32(u32::from(config.has_d)),
1426	];
1427
1428	let rotate_buffers = [
1429		BufferBinding::read(d_q.storage()),
1430		BufferBinding::read(d_k.storage()),
1431		BufferBinding::read(c.storage()),
1432		BufferBinding::read(b.storage()),
1433		BufferBinding::read(dt.storage()),
1434		BufferBinding::read(angle.storage()),
1435		BufferBinding::read(c_bias.storage()),
1436		BufferBinding::read(b_bias.storage()),
1437		BufferBinding::read(theta.storage()),
1438		BufferBinding::write(d_c_head.storage()),
1439		BufferBinding::write(d_b_head.storage()),
1440		BufferBinding::write(d_angle_head.storage()),
1441		BufferBinding::write(d_c_bias_batch.storage()),
1442		BufferBinding::write(d_b_bias_batch.storage()),
1443		BufferBinding::read_write(d_dt.storage()),
1444	];
1445	let rotate_constants = [
1446		PushConstant::U32(geometry.batch),
1447		PushConstant::U32(geometry.length),
1448		PushConstant::U32(geometry.heads),
1449		PushConstant::U32(geometry.groups),
1450		PushConstant::U32(geometry.state_size),
1451		PushConstant::U32(geometry.angles),
1452		PushConstant::U32(geometry.rank),
1453	];
1454
1455	let group_count = geometry
1456		.batch
1457		.checked_mul(geometry.length)
1458		.and_then(|value| value.checked_mul(geometry.rank))
1459		.and_then(|value| value.checked_mul(geometry.groups))
1460		.and_then(|value| value.checked_mul(geometry.state_size))
1461		.ok_or_else(|| Error::invalid_argument(format!("{operation} group reduction exceeds u32")))?;
1462	let angle_count = geometry
1463		.batch
1464		.checked_mul(geometry.length)
1465		.and_then(|value| value.checked_mul(geometry.angles))
1466		.ok_or_else(|| Error::invalid_argument(format!("{operation} angle reduction exceeds u32")))?;
1467	let bias_count = geometry
1468		.heads
1469		.checked_mul(geometry.rank)
1470		.and_then(|value| value.checked_mul(geometry.state_size))
1471		.ok_or_else(|| Error::invalid_argument(format!("{operation} bias reduction exceeds u32")))?;
1472	let mimo_count = geometry
1473		.heads
1474		.checked_mul(geometry.rank)
1475		.and_then(|value| value.checked_mul(geometry.head_dim))
1476		.ok_or_else(|| Error::invalid_argument(format!("{operation} MIMO reduction exceeds u32")))?;
1477	let norm_count = geometry
1478		.heads
1479		.checked_mul(geometry.head_dim)
1480		.ok_or_else(|| Error::invalid_argument(format!("{operation} norm reduction exceeds u32")))?;
1481	let reduce_count = group_count
1482		.checked_add(angle_count)
1483		.and_then(|value| value.checked_add(bias_count))
1484		.and_then(|value| value.checked_add(geometry.heads))
1485		.and_then(|value| value.checked_add(mimo_count))
1486		.and_then(|value| value.checked_add(norm_count))
1487		.ok_or_else(|| Error::invalid_argument(format!("{operation} reduction size exceeds u32")))?;
1488	let reduce_buffers = [
1489		BufferBinding::read(d_c_head.storage()),
1490		BufferBinding::read(d_b_head.storage()),
1491		BufferBinding::read(d_angle_head.storage()),
1492		BufferBinding::read(d_c_bias_batch.storage()),
1493		BufferBinding::read(d_b_bias_batch.storage()),
1494		BufferBinding::read(d_d_batch.storage()),
1495		BufferBinding::read(d_mimo_x_batch.storage()),
1496		BufferBinding::read(d_mimo_z_batch.storage()),
1497		BufferBinding::read(d_mimo_o_batch.storage()),
1498		BufferBinding::read(d_norm_batch.storage()),
1499		BufferBinding::write(d_c.storage()),
1500		BufferBinding::write(d_b.storage()),
1501		BufferBinding::write(d_angle.storage()),
1502		BufferBinding::write(d_c_bias.storage()),
1503		BufferBinding::write(d_b_bias.storage()),
1504		BufferBinding::write(d_d.storage()),
1505		BufferBinding::write(d_mimo_x.storage()),
1506		BufferBinding::write(d_mimo_z.storage()),
1507		BufferBinding::write(d_mimo_o.storage()),
1508		BufferBinding::write(d_norm_weight.storage()),
1509	];
1510	let reduce_constants = [
1511		PushConstant::U32(geometry.batch),
1512		PushConstant::U32(geometry.length),
1513		PushConstant::U32(geometry.heads),
1514		PushConstant::U32(geometry.groups),
1515		PushConstant::U32(geometry.head_dim),
1516		PushConstant::U32(geometry.state_size),
1517		PushConstant::U32(geometry.angles),
1518		PushConstant::U32(geometry.rank),
1519		PushConstant::U32(reduce_count),
1520	];
1521
1522	let bh = geometry.batch_heads;
1523	let dispatches = [
1524		ComputeDispatch {
1525			kernel: KernelId::MlMamba3MimoBackwardPrepareF32,
1526			buffers: &prepare_buffers,
1527			push_constants: &prepare_constants,
1528			workgroups: [bh, 1, 1],
1529			indirect: None,
1530		},
1531		ComputeDispatch {
1532			kernel: KernelId::MlMamba3MimoBackwardPostF32,
1533			buffers: &post_buffers,
1534			push_constants: &post_constants,
1535			workgroups: [bh, 1, 1],
1536			indirect: None,
1537		},
1538		ComputeDispatch {
1539			kernel: KernelId::MlMamba3MimoBackwardCoreF32,
1540			buffers: &core_buffers,
1541			push_constants: &core_constants,
1542			workgroups: [bh, 1, 1],
1543			indirect: None,
1544		},
1545		ComputeDispatch {
1546			kernel: KernelId::MlMamba3MimoBackwardRotateF32,
1547			buffers: &rotate_buffers,
1548			push_constants: &rotate_constants,
1549			workgroups: [bh, 1, 1],
1550			indirect: None,
1551		},
1552		ComputeDispatch {
1553			kernel: KernelId::MlMamba3MimoBackwardReduceF32,
1554			buffers: &reduce_buffers,
1555			push_constants: &reduce_constants,
1556			workgroups: [reduce_count.div_ceil(256), 1, 1],
1557			indirect: None,
1558		},
1559	];
1560	let semantic_inputs = [
1561		output_gradient,
1562		c,
1563		b,
1564		x,
1565		z,
1566		adt,
1567		dt,
1568		trap,
1569		angle,
1570		c_bias,
1571		b_bias,
1572		d,
1573		mimo_x,
1574		mimo_z,
1575		mimo_o,
1576		norm_weight,
1577	];
1578	let semantic_outputs = [
1579		&d_c,
1580		&d_b,
1581		&d_x,
1582		&d_z,
1583		&d_adt,
1584		&d_dt,
1585		&d_trap,
1586		&d_angle,
1587		&d_c_bias,
1588		&d_b_bias,
1589		&d_d,
1590		&d_mimo_x,
1591		&d_mimo_z,
1592		&d_mimo_o,
1593		&d_norm_weight,
1594	];
1595	let attributes = [OpAttribute::UnsignedInteger {
1596		name: "config_identity".into(),
1597		value: config.identity(operation)?,
1598	}];
1599	runtime.record_split_semantic(
1600		&dispatches,
1601		SemanticDispatch {
1602			contract,
1603			inputs: &semantic_inputs,
1604			outputs: &semantic_outputs,
1605			attributes: &attributes,
1606		},
1607	)?;
1608	Ok(Mamba3MimoBackwardResult {
1609		c: d_c,
1610		b: d_b,
1611		x: d_x,
1612		z: d_z,
1613		adt: d_adt,
1614		dt: d_dt,
1615		trap: d_trap,
1616		angle: d_angle,
1617		c_bias: d_c_bias,
1618		b_bias: d_b_bias,
1619		d: d_d,
1620		mimo_x: d_mimo_x,
1621		mimo_z: d_mimo_z,
1622		mimo_o: d_mimo_o,
1623		norm_weight: d_norm_weight,
1624	})
1625}
1626
1627#[allow(
1628	clippy::too_many_arguments,
1629	reason = "preserves the donor upstream plus eleven-operand adjoint boundary"
1630)]
1631fn dispatch_mamba3_siso_backward(
1632	output_gradient: &Matrix,
1633	c: &Matrix,
1634	b: &Matrix,
1635	x: &Matrix,
1636	z: &Matrix,
1637	adt: &Matrix,
1638	dt: &Matrix,
1639	trap: &Matrix,
1640	angle: &Matrix,
1641	c_bias: &Matrix,
1642	b_bias: &Matrix,
1643	d: &Matrix,
1644	config: SsmConfig,
1645) -> Result<SsmBackwardResult> {
1646	let contract = crate::core::operation::ml::MAMBA3_SISO_BACKWARD;
1647	let operation = contract.name();
1648	let operands = [c, b, x, z, adt, dt, trap, angle, c_bias, b_bias, d];
1649	let geometry = Geometry::resolve(&operands, config, operation)?;
1650	if output_gradient.shape() != geometry.output_shape() {
1651		return Err(Error::invalid_argument(format!(
1652			"{operation} output gradient does not match the configured output"
1653		)));
1654	}
1655	validate_f32_same_runtime(operation, &[output_gradient, x])?;
1656	let runtime = x.runtime();
1657	let short_route = geometry.length <= 16
1658		&& geometry.head_dim <= 16
1659		&& geometry.state_size <= 32
1660		&& geometry.angles <= 8;
1661	if !short_route {
1662		let history_bytes = checked_count(
1663			&[
1664				geometry.batch as usize,
1665				geometry.heads as usize,
1666				geometry.length as usize,
1667				geometry.head_dim as usize,
1668				geometry.state_size as usize,
1669			],
1670			operation,
1671		)?
1672		.checked_mul(std::mem::size_of::<f32>())
1673		.ok_or_else(|| {
1674			Error::invalid_argument(format!("{operation} history byte size overflows usize"))
1675		})?;
1676		if geometry.length >= 64
1677			&& geometry.head_dim <= 32
1678			&& geometry.state_size <= 32
1679			&& geometry.angles <= 8
1680			&& history_bytes <= MAMBA3_CHUNK_HISTORY_LIMIT_BYTES
1681		{
1682			return mamba3_siso_backward_chunked(
1683				output_gradient,
1684				c,
1685				b,
1686				x,
1687				z,
1688				adt,
1689				dt,
1690				trap,
1691				angle,
1692				c_bias,
1693				b_bias,
1694				d,
1695				config,
1696				&geometry,
1697			);
1698		}
1699		return mamba3_siso_backward_generic(
1700			output_gradient,
1701			c,
1702			b,
1703			x,
1704			z,
1705			adt,
1706			dt,
1707			trap,
1708			angle,
1709			c_bias,
1710			b_bias,
1711			d,
1712			config,
1713			&geometry,
1714		);
1715	}
1716
1717	let alloc = |shape: Vec<usize>| -> Result<Matrix> {
1718		let count = checked_count(&shape, operation)?;
1719		shader_u32(count, "temporary element count", operation)?;
1720		Matrix::allocate(runtime, shape, count, DType::F32)
1721	};
1722	let bsz = geometry.batch as usize;
1723	let len = geometry.length as usize;
1724	let heads = geometry.heads as usize;
1725	let groups = geometry.groups as usize;
1726	let head_dim = geometry.head_dim as usize;
1727	let state = geometry.state_size as usize;
1728	let angles = geometry.angles as usize;
1729	let scalar_shape = vec![bsz, len, heads];
1730	let vector_shape = vec![bsz, len, heads, head_dim];
1731	let head_state_shape = vec![bsz, len, heads, state];
1732
1733	let c_rot = alloc(head_state_shape.clone())?;
1734	let b_rot = alloc(head_state_shape.clone())?;
1735	let theta = alloc(vec![bsz * heads, len, angles])?;
1736	let qk = alloc(scalar_shape.clone())?;
1737	let decay = alloc(scalar_shape.clone())?;
1738	let gamma = alloc(scalar_shape.clone())?;
1739	let scale = alloc(scalar_shape.clone())?;
1740	let h_previous = alloc(vec![bsz * heads, len, head_dim, state])?;
1741	let d_pre = alloc(vector_shape.clone())?;
1742	let d_z = alloc(vector_shape.clone())?;
1743	let d_c_head = alloc(head_state_shape.clone())?;
1744	let d_b_head = alloc(head_state_shape)?;
1745	let d_x = alloc(vector_shape)?;
1746	let d_adt = alloc(scalar_shape.clone())?;
1747	let d_gamma = alloc(scalar_shape.clone())?;
1748	let d_scale = alloc(scalar_shape.clone())?;
1749	let d_theta = alloc(vec![bsz * heads, len, angles])?;
1750	let d_c_bias_batch = alloc(vec![bsz, heads, state])?;
1751	let d_b_bias_batch = alloc(vec![bsz, heads, state])?;
1752	let d_d_batch = alloc(vec![bsz, heads])?;
1753	let d_dt = alloc(scalar_shape.clone())?;
1754	let d_trap = alloc(scalar_shape)?;
1755	let d_angle_head = alloc(vec![bsz, heads, len, angles])?;
1756	let d_angle = alloc(vec![bsz, len, angles])?;
1757	let d_c_bias = alloc(vec![heads, state])?;
1758	let d_b_bias = alloc(vec![heads, state])?;
1759	let d_d = alloc(vec![heads])?;
1760	let d_c = alloc(vec![bsz, len, groups, state])?;
1761	let d_b = alloc(vec![bsz, len, groups, state])?;
1762
1763	let prepare_buffers = [
1764		BufferBinding::read(c.storage()),
1765		BufferBinding::read(b.storage()),
1766		BufferBinding::read(dt.storage()),
1767		BufferBinding::read(trap.storage()),
1768		BufferBinding::read(adt.storage()),
1769		BufferBinding::read(angle.storage()),
1770		BufferBinding::read(c_bias.storage()),
1771		BufferBinding::read(b_bias.storage()),
1772		BufferBinding::write(c_rot.storage()),
1773		BufferBinding::write(b_rot.storage()),
1774		BufferBinding::write(theta.storage()),
1775		BufferBinding::write(qk.storage()),
1776		BufferBinding::write(decay.storage()),
1777		BufferBinding::write(gamma.storage()),
1778		BufferBinding::write(scale.storage()),
1779	];
1780	let prepare_constants = [
1781		PushConstant::U32(geometry.batch),
1782		PushConstant::U32(geometry.length),
1783		PushConstant::U32(geometry.heads),
1784		PushConstant::U32(geometry.groups),
1785		PushConstant::U32(geometry.state_size),
1786		PushConstant::U32(geometry.angles),
1787	];
1788	let state_buffers = [
1789		BufferBinding::read(b_rot.storage()),
1790		BufferBinding::read(x.storage()),
1791		BufferBinding::read(decay.storage()),
1792		BufferBinding::read(scale.storage()),
1793		BufferBinding::read(c_rot.storage()),
1794		BufferBinding::read(z.storage()),
1795		BufferBinding::read(gamma.storage()),
1796		BufferBinding::read(d.storage()),
1797		BufferBinding::read(qk.storage()),
1798		BufferBinding::read(output_gradient.storage()),
1799		BufferBinding::write(h_previous.storage()),
1800		BufferBinding::write(d_pre.storage()),
1801		BufferBinding::write(d_z.storage()),
1802	];
1803	let state_constants = [
1804		PushConstant::U32(geometry.batch),
1805		PushConstant::U32(geometry.length),
1806		PushConstant::U32(geometry.heads),
1807		PushConstant::U32(geometry.head_dim),
1808		PushConstant::U32(geometry.state_size),
1809		PushConstant::U32(u32::from(config.has_z)),
1810		PushConstant::U32(u32::from(config.has_d)),
1811	];
1812	let reverse_buffers = [
1813		BufferBinding::read(d_pre.storage()),
1814		BufferBinding::read(c_rot.storage()),
1815		BufferBinding::read(b_rot.storage()),
1816		BufferBinding::read(theta.storage()),
1817		BufferBinding::read(gamma.storage()),
1818		BufferBinding::read(scale.storage()),
1819		BufferBinding::read(decay.storage()),
1820		BufferBinding::read(h_previous.storage()),
1821		BufferBinding::read(x.storage()),
1822		BufferBinding::read(d.storage()),
1823		BufferBinding::read(qk.storage()),
1824		BufferBinding::write(d_c_head.storage()),
1825		BufferBinding::write(d_b_head.storage()),
1826		BufferBinding::write(d_x.storage()),
1827		BufferBinding::write(d_adt.storage()),
1828		BufferBinding::write(d_gamma.storage()),
1829		BufferBinding::write(d_scale.storage()),
1830		BufferBinding::write(d_theta.storage()),
1831		BufferBinding::write(d_c_bias_batch.storage()),
1832		BufferBinding::write(d_b_bias_batch.storage()),
1833		BufferBinding::write(d_d_batch.storage()),
1834	];
1835	let reverse_constants = [
1836		PushConstant::U32(geometry.batch),
1837		PushConstant::U32(geometry.length),
1838		PushConstant::U32(geometry.heads),
1839		PushConstant::U32(geometry.head_dim),
1840		PushConstant::U32(geometry.state_size),
1841		PushConstant::U32(geometry.angles),
1842		PushConstant::U32(u32::from(config.has_d)),
1843	];
1844	let finalize_buffers = [
1845		BufferBinding::read(dt.storage()),
1846		BufferBinding::read(trap.storage()),
1847		BufferBinding::read(angle.storage()),
1848		BufferBinding::read(d_gamma.storage()),
1849		BufferBinding::read(d_scale.storage()),
1850		BufferBinding::read(d_theta.storage()),
1851		BufferBinding::write(d_dt.storage()),
1852		BufferBinding::write(d_trap.storage()),
1853		BufferBinding::write(d_angle_head.storage()),
1854	];
1855	let finalize_constants = [
1856		PushConstant::U32(geometry.batch),
1857		PushConstant::U32(geometry.length),
1858		PushConstant::U32(geometry.heads),
1859		PushConstant::U32(geometry.angles),
1860	];
1861	let reduce_count = geometry
1862		.batch
1863		.checked_mul(geometry.length)
1864		.and_then(|value| value.checked_mul(geometry.angles))
1865		.and_then(|value| {
1866			geometry
1867				.heads
1868				.checked_mul(geometry.state_size)
1869				.and_then(|hn| hn.checked_mul(2))
1870				.and_then(|twice_hn| value.checked_add(twice_hn))
1871		})
1872		.and_then(|value| value.checked_add(geometry.heads))
1873		.ok_or_else(|| Error::invalid_argument(format!("{operation} reduction size exceeds u32")))?;
1874	let reduce_buffers = [
1875		BufferBinding::read(d_angle_head.storage()),
1876		BufferBinding::read(d_c_bias_batch.storage()),
1877		BufferBinding::read(d_b_bias_batch.storage()),
1878		BufferBinding::read(d_d_batch.storage()),
1879		BufferBinding::write(d_angle.storage()),
1880		BufferBinding::write(d_c_bias.storage()),
1881		BufferBinding::write(d_b_bias.storage()),
1882		BufferBinding::write(d_d.storage()),
1883	];
1884	let reduce_constants = [
1885		PushConstant::U32(geometry.batch),
1886		PushConstant::U32(geometry.length),
1887		PushConstant::U32(geometry.heads),
1888		PushConstant::U32(geometry.state_size),
1889		PushConstant::U32(geometry.angles),
1890		PushConstant::U32(reduce_count),
1891	];
1892	let group_count = geometry
1893		.batch
1894		.checked_mul(geometry.length)
1895		.and_then(|value| value.checked_mul(geometry.groups))
1896		.and_then(|value| value.checked_mul(geometry.state_size))
1897		.ok_or_else(|| Error::invalid_argument(format!("{operation} group reduction exceeds u32")))?;
1898	let group_buffers = [
1899		BufferBinding::read(d_c_head.storage()),
1900		BufferBinding::read(d_b_head.storage()),
1901		BufferBinding::write(d_c.storage()),
1902		BufferBinding::write(d_b.storage()),
1903	];
1904	let group_constants = [
1905		PushConstant::U32(geometry.batch),
1906		PushConstant::U32(geometry.length),
1907		PushConstant::U32(geometry.heads),
1908		PushConstant::U32(geometry.groups),
1909		PushConstant::U32(geometry.state_size),
1910		PushConstant::U32(group_count),
1911	];
1912	let bh = geometry.batch_heads;
1913	let dispatches = [
1914		ComputeDispatch {
1915			kernel: KernelId::MlMamba3SisoBackwardPrepareF32,
1916			buffers: &prepare_buffers,
1917			push_constants: &prepare_constants,
1918			workgroups: [bh.div_ceil(64), 1, 1],
1919			indirect: None,
1920		},
1921		ComputeDispatch {
1922			kernel: KernelId::MlMamba3SisoBackwardStateF32,
1923			buffers: &state_buffers,
1924			push_constants: &state_constants,
1925			workgroups: [bh, 1, 1],
1926			indirect: None,
1927		},
1928		ComputeDispatch {
1929			kernel: KernelId::MlMamba3SisoBackwardReverseP16F32,
1930			buffers: &reverse_buffers,
1931			push_constants: &reverse_constants,
1932			workgroups: [bh, 1, 1],
1933			indirect: None,
1934		},
1935		ComputeDispatch {
1936			kernel: KernelId::MlMamba3SisoBackwardFinalizeF32,
1937			buffers: &finalize_buffers,
1938			push_constants: &finalize_constants,
1939			workgroups: [bh.div_ceil(64), 1, 1],
1940			indirect: None,
1941		},
1942		ComputeDispatch {
1943			kernel: KernelId::MlMamba3SisoBackwardReduceF32,
1944			buffers: &reduce_buffers,
1945			push_constants: &reduce_constants,
1946			workgroups: [reduce_count.div_ceil(256), 1, 1],
1947			indirect: None,
1948		},
1949		ComputeDispatch {
1950			kernel: KernelId::MlMamba3SisoBackwardGroupReduceF32,
1951			buffers: &group_buffers,
1952			push_constants: &group_constants,
1953			workgroups: [group_count.div_ceil(256), 1, 1],
1954			indirect: None,
1955		},
1956	];
1957	let semantic_inputs = [
1958		output_gradient,
1959		c,
1960		b,
1961		x,
1962		z,
1963		adt,
1964		dt,
1965		trap,
1966		angle,
1967		c_bias,
1968		b_bias,
1969		d,
1970	];
1971	let semantic_outputs = [
1972		&d_c, &d_b, &d_x, &d_z, &d_adt, &d_dt, &d_trap, &d_angle, &d_c_bias, &d_b_bias, &d_d,
1973	];
1974	let attributes = [OpAttribute::UnsignedInteger {
1975		name: "config_identity".into(),
1976		value: config.identity(operation)?,
1977	}];
1978	runtime.record_split_semantic(
1979		&dispatches,
1980		SemanticDispatch {
1981			contract,
1982			inputs: &semantic_inputs,
1983			outputs: &semantic_outputs,
1984			attributes: &attributes,
1985		},
1986	)?;
1987	Ok(SsmBackwardResult {
1988		c: d_c,
1989		b: d_b,
1990		x: d_x,
1991		z: d_z,
1992		adt: d_adt,
1993		dt: d_dt,
1994		trap: d_trap,
1995		angle: d_angle,
1996		c_bias: d_c_bias,
1997		b_bias: d_b_bias,
1998		d: d_d,
1999	})
2000}
2001
2002#[allow(
2003	clippy::too_many_arguments,
2004	reason = "preserves the donor upstream plus eleven-operand adjoint boundary"
2005)]
2006fn mamba3_siso_backward_chunked(
2007	output_gradient: &Matrix,
2008	c: &Matrix,
2009	b: &Matrix,
2010	x: &Matrix,
2011	z: &Matrix,
2012	adt: &Matrix,
2013	dt: &Matrix,
2014	trap: &Matrix,
2015	angle: &Matrix,
2016	c_bias: &Matrix,
2017	b_bias: &Matrix,
2018	d: &Matrix,
2019	config: SsmConfig,
2020	geometry: &Geometry,
2021) -> Result<SsmBackwardResult> {
2022	let contract = crate::core::operation::ml::MAMBA3_SISO_BACKWARD;
2023	let operation = contract.name();
2024	let runtime = x.runtime();
2025	let allocate = |shape: Vec<usize>| -> Result<Matrix> {
2026		let count = checked_count(&shape, operation)?;
2027		shader_u32(count, "chunked SISO tensor element count", operation)?;
2028		Matrix::allocate(runtime, shape, count, DType::F32)
2029	};
2030	let batch = geometry.batch as usize;
2031	let length = geometry.length as usize;
2032	let heads = geometry.heads as usize;
2033	let groups = geometry.groups as usize;
2034	let head_dim = geometry.head_dim as usize;
2035	let state_size = geometry.state_size as usize;
2036	let angles = geometry.angles as usize;
2037	let batch_heads = geometry.batch_heads as usize;
2038	let chunks = length.div_ceil(16);
2039	let chunks_u32 = shader_u32(chunks, "chunk count", operation)?;
2040	let chunk_workgroups = geometry
2041		.batch_heads
2042		.checked_mul(chunks_u32)
2043		.ok_or_else(|| Error::invalid_argument(format!("{operation} chunk count exceeds u32")))?;
2044
2045	let scalar_shape = vec![batch, length, heads];
2046	let vector_shape = vec![batch, length, heads, head_dim];
2047	let head_state_shape = vec![batch, length, heads, state_size];
2048	let chunk_state_shape = vec![batch_heads, chunks, head_dim, state_size];
2049	let c_rot = allocate(head_state_shape.clone())?;
2050	let b_rot = allocate(head_state_shape.clone())?;
2051	let theta = allocate(vec![batch_heads, length, angles])?;
2052	let qk = allocate(scalar_shape.clone())?;
2053	let decay = allocate(scalar_shape.clone())?;
2054	let gamma = allocate(scalar_shape.clone())?;
2055	let scale = allocate(scalar_shape.clone())?;
2056	let summary = allocate(chunk_state_shape.clone())?;
2057	let product = allocate(vec![batch_heads, chunks])?;
2058	let entry = allocate(chunk_state_shape.clone())?;
2059	let d_pre = allocate(vector_shape.clone())?;
2060	let h_previous = allocate(vec![batch_heads, length, head_dim, state_size])?;
2061	let d_z = allocate(vector_shape.clone())?;
2062	let reverse_summary = allocate(chunk_state_shape.clone())?;
2063	let chunk_exit = allocate(chunk_state_shape)?;
2064	let d_c_head = allocate(head_state_shape.clone())?;
2065	let d_b_head = allocate(head_state_shape)?;
2066	let d_x = allocate(vector_shape)?;
2067	let d_adt = allocate(scalar_shape.clone())?;
2068	let d_gamma = allocate(scalar_shape.clone())?;
2069	let d_scale = allocate(scalar_shape.clone())?;
2070	let d_theta = allocate(vec![batch_heads, length, angles])?;
2071	let d_d_token = allocate(scalar_shape.clone())?;
2072	let d_dt = allocate(scalar_shape.clone())?;
2073	let d_trap = allocate(scalar_shape)?;
2074	let d_angle_head = allocate(vec![batch, heads, length, angles])?;
2075	let d_c = allocate(vec![batch, length, groups, state_size])?;
2076	let d_b = allocate(vec![batch, length, groups, state_size])?;
2077	let d_angle = allocate(vec![batch, length, angles])?;
2078	let d_c_bias = allocate(vec![heads, state_size])?;
2079	let d_b_bias = allocate(vec![heads, state_size])?;
2080	let d_d = allocate(vec![heads])?;
2081
2082	let prepare_buffers = [
2083		BufferBinding::read(c.storage()),
2084		BufferBinding::read(b.storage()),
2085		BufferBinding::read(dt.storage()),
2086		BufferBinding::read(trap.storage()),
2087		BufferBinding::read(adt.storage()),
2088		BufferBinding::read(angle.storage()),
2089		BufferBinding::read(c_bias.storage()),
2090		BufferBinding::read(b_bias.storage()),
2091		BufferBinding::write(c_rot.storage()),
2092		BufferBinding::write(b_rot.storage()),
2093		BufferBinding::write(theta.storage()),
2094		BufferBinding::write(qk.storage()),
2095		BufferBinding::write(decay.storage()),
2096		BufferBinding::write(gamma.storage()),
2097		BufferBinding::write(scale.storage()),
2098	];
2099	let prepare_constants = [
2100		PushConstant::U32(geometry.batch),
2101		PushConstant::U32(geometry.length),
2102		PushConstant::U32(geometry.heads),
2103		PushConstant::U32(geometry.groups),
2104		PushConstant::U32(geometry.state_size),
2105		PushConstant::U32(geometry.angles),
2106	];
2107	let summary_buffers = [
2108		BufferBinding::read(b_rot.storage()),
2109		BufferBinding::read(x.storage()),
2110		BufferBinding::read(decay.storage()),
2111		BufferBinding::read(scale.storage()),
2112		BufferBinding::write(summary.storage()),
2113		BufferBinding::write(product.storage()),
2114	];
2115	let summary_constants = [
2116		PushConstant::U32(geometry.batch),
2117		PushConstant::U32(geometry.length),
2118		PushConstant::U32(geometry.heads),
2119		PushConstant::U32(geometry.head_dim),
2120		PushConstant::U32(geometry.state_size),
2121		PushConstant::U32(chunks_u32),
2122	];
2123	let prefix_buffers = [
2124		BufferBinding::read(summary.storage()),
2125		BufferBinding::read(product.storage()),
2126		BufferBinding::write(entry.storage()),
2127	];
2128	let prefix_constants = [
2129		PushConstant::U32(geometry.batch_heads),
2130		PushConstant::U32(geometry.head_dim),
2131		PushConstant::U32(geometry.state_size),
2132		PushConstant::U32(chunks_u32),
2133	];
2134	let dpre_buffers = [
2135		BufferBinding::read(c_rot.storage()),
2136		BufferBinding::read(b_rot.storage()),
2137		BufferBinding::read(x.storage()),
2138		BufferBinding::read(z.storage()),
2139		BufferBinding::read(decay.storage()),
2140		BufferBinding::read(gamma.storage()),
2141		BufferBinding::read(scale.storage()),
2142		BufferBinding::read(qk.storage()),
2143		BufferBinding::read(d.storage()),
2144		BufferBinding::read(output_gradient.storage()),
2145		BufferBinding::read(entry.storage()),
2146		BufferBinding::write(h_previous.storage()),
2147		BufferBinding::write(d_pre.storage()),
2148		BufferBinding::write(d_z.storage()),
2149	];
2150	let dpre_constants = [
2151		PushConstant::U32(geometry.batch),
2152		PushConstant::U32(geometry.length),
2153		PushConstant::U32(geometry.heads),
2154		PushConstant::U32(geometry.head_dim),
2155		PushConstant::U32(geometry.state_size),
2156		PushConstant::U32(chunks_u32),
2157		PushConstant::U32(u32::from(config.has_z)),
2158		PushConstant::U32(u32::from(config.has_d)),
2159	];
2160	let backward_summary_buffers = [
2161		BufferBinding::read(c_rot.storage()),
2162		BufferBinding::read(decay.storage()),
2163		BufferBinding::read(d_pre.storage()),
2164		BufferBinding::write(reverse_summary.storage()),
2165	];
2166	let backward_summary_constants = summary_constants;
2167	let backward_prefix_buffers = [
2168		BufferBinding::read(reverse_summary.storage()),
2169		BufferBinding::read(product.storage()),
2170		BufferBinding::write(chunk_exit.storage()),
2171	];
2172	let backward_prefix_constants = prefix_constants;
2173	let backward_buffers = [
2174		BufferBinding::read(c_rot.storage()),
2175		BufferBinding::read(b_rot.storage()),
2176		BufferBinding::read(theta.storage()),
2177		BufferBinding::read(x.storage()),
2178		BufferBinding::read(decay.storage()),
2179		BufferBinding::read(gamma.storage()),
2180		BufferBinding::read(scale.storage()),
2181		BufferBinding::read(qk.storage()),
2182		BufferBinding::read(d.storage()),
2183		BufferBinding::read(d_pre.storage()),
2184		BufferBinding::read(h_previous.storage()),
2185		BufferBinding::read(chunk_exit.storage()),
2186		BufferBinding::write(d_c_head.storage()),
2187		BufferBinding::write(d_b_head.storage()),
2188		BufferBinding::write(d_x.storage()),
2189		BufferBinding::write(d_adt.storage()),
2190		BufferBinding::write(d_gamma.storage()),
2191		BufferBinding::write(d_scale.storage()),
2192		BufferBinding::write(d_theta.storage()),
2193		BufferBinding::write(d_d_token.storage()),
2194	];
2195	let backward_constants = [
2196		PushConstant::U32(geometry.batch),
2197		PushConstant::U32(geometry.length),
2198		PushConstant::U32(geometry.heads),
2199		PushConstant::U32(geometry.head_dim),
2200		PushConstant::U32(geometry.state_size),
2201		PushConstant::U32(geometry.angles),
2202		PushConstant::U32(chunks_u32),
2203		PushConstant::U32(u32::from(config.has_d)),
2204	];
2205	let finalize_buffers = [
2206		BufferBinding::read(dt.storage()),
2207		BufferBinding::read(trap.storage()),
2208		BufferBinding::read(angle.storage()),
2209		BufferBinding::read(d_gamma.storage()),
2210		BufferBinding::read(d_scale.storage()),
2211		BufferBinding::read(d_theta.storage()),
2212		BufferBinding::write(d_dt.storage()),
2213		BufferBinding::write(d_trap.storage()),
2214		BufferBinding::write(d_angle_head.storage()),
2215	];
2216	let finalize_constants = [
2217		PushConstant::U32(geometry.batch),
2218		PushConstant::U32(geometry.length),
2219		PushConstant::U32(geometry.heads),
2220		PushConstant::U32(geometry.angles),
2221	];
2222	let group_count = checked_count(&[batch, length, groups, state_size], operation)?;
2223	let angle_count = checked_count(&[batch, length, angles], operation)?;
2224	let bias_count = checked_count(&[heads, state_size], operation)?;
2225	let reduce_count = group_count
2226		.checked_add(angle_count)
2227		.and_then(|count| count.checked_add(bias_count))
2228		.and_then(|count| count.checked_add(heads))
2229		.ok_or_else(|| {
2230			Error::invalid_argument(format!("{operation} chunk reduction size overflows usize"))
2231		})?;
2232	let reduce_count = shader_u32(reduce_count, "chunk reduction size", operation)?;
2233	let reduce_buffers = [
2234		BufferBinding::read(d_c_head.storage()),
2235		BufferBinding::read(d_b_head.storage()),
2236		BufferBinding::read(d_angle_head.storage()),
2237		BufferBinding::read(d_d_token.storage()),
2238		BufferBinding::write(d_c.storage()),
2239		BufferBinding::write(d_b.storage()),
2240		BufferBinding::write(d_angle.storage()),
2241		BufferBinding::write(d_c_bias.storage()),
2242		BufferBinding::write(d_b_bias.storage()),
2243		BufferBinding::write(d_d.storage()),
2244	];
2245	let reduce_constants = [
2246		PushConstant::U32(geometry.batch),
2247		PushConstant::U32(geometry.length),
2248		PushConstant::U32(geometry.heads),
2249		PushConstant::U32(geometry.groups),
2250		PushConstant::U32(geometry.state_size),
2251		PushConstant::U32(geometry.angles),
2252		PushConstant::U32(reduce_count),
2253	];
2254	let dispatches = [
2255		ComputeDispatch {
2256			kernel: KernelId::MlMamba3SisoBackwardPrepareF32,
2257			buffers: &prepare_buffers,
2258			push_constants: &prepare_constants,
2259			workgroups: [geometry.batch_heads.div_ceil(64), 1, 1],
2260			indirect: None,
2261		},
2262		ComputeDispatch {
2263			kernel: KernelId::MlMamba3SisoChunkSummaryF32,
2264			buffers: &summary_buffers,
2265			push_constants: &summary_constants,
2266			workgroups: [chunk_workgroups, 1, 1],
2267			indirect: None,
2268		},
2269		ComputeDispatch {
2270			kernel: KernelId::MlMamba3SisoChunkPrefixF32,
2271			buffers: &prefix_buffers,
2272			push_constants: &prefix_constants,
2273			workgroups: [geometry.batch_heads, 1, 1],
2274			indirect: None,
2275		},
2276		ComputeDispatch {
2277			kernel: KernelId::MlMamba3SisoChunkDpreF32,
2278			buffers: &dpre_buffers,
2279			push_constants: &dpre_constants,
2280			workgroups: [chunk_workgroups, 1, 1],
2281			indirect: None,
2282		},
2283		ComputeDispatch {
2284			kernel: KernelId::MlMamba3SisoChunkBackwardSummaryF32,
2285			buffers: &backward_summary_buffers,
2286			push_constants: &backward_summary_constants,
2287			workgroups: [chunk_workgroups, 1, 1],
2288			indirect: None,
2289		},
2290		ComputeDispatch {
2291			kernel: KernelId::MlMamba3SisoChunkBackwardPrefixF32,
2292			buffers: &backward_prefix_buffers,
2293			push_constants: &backward_prefix_constants,
2294			workgroups: [geometry.batch_heads, 1, 1],
2295			indirect: None,
2296		},
2297		ComputeDispatch {
2298			kernel: KernelId::MlMamba3SisoChunkBackwardF32,
2299			buffers: &backward_buffers,
2300			push_constants: &backward_constants,
2301			workgroups: [chunk_workgroups, 1, 1],
2302			indirect: None,
2303		},
2304		ComputeDispatch {
2305			kernel: KernelId::MlMamba3SisoChunkFinalizeF32,
2306			buffers: &finalize_buffers,
2307			push_constants: &finalize_constants,
2308			workgroups: [geometry.batch_heads.div_ceil(64), 1, 1],
2309			indirect: None,
2310		},
2311		ComputeDispatch {
2312			kernel: KernelId::MlMamba3SisoChunkReduceF32,
2313			buffers: &reduce_buffers,
2314			push_constants: &reduce_constants,
2315			workgroups: [reduce_count.div_ceil(256), 1, 1],
2316			indirect: None,
2317		},
2318	];
2319	let semantic_inputs = [
2320		output_gradient,
2321		c,
2322		b,
2323		x,
2324		z,
2325		adt,
2326		dt,
2327		trap,
2328		angle,
2329		c_bias,
2330		b_bias,
2331		d,
2332	];
2333	let semantic_outputs = [
2334		&d_c, &d_b, &d_x, &d_z, &d_adt, &d_dt, &d_trap, &d_angle, &d_c_bias, &d_b_bias, &d_d,
2335	];
2336	let attributes = [OpAttribute::UnsignedInteger {
2337		name: "config_identity".into(),
2338		value: config.identity(operation)?,
2339	}];
2340	runtime.record_split_semantic(
2341		&dispatches,
2342		SemanticDispatch {
2343			contract,
2344			inputs: &semantic_inputs,
2345			outputs: &semantic_outputs,
2346			attributes: &attributes,
2347		},
2348	)?;
2349	Ok(SsmBackwardResult {
2350		c: d_c,
2351		b: d_b,
2352		x: d_x,
2353		z: d_z,
2354		adt: d_adt,
2355		dt: d_dt,
2356		trap: d_trap,
2357		angle: d_angle,
2358		c_bias: d_c_bias,
2359		b_bias: d_b_bias,
2360		d: d_d,
2361	})
2362}
2363
2364#[allow(
2365	clippy::too_many_arguments,
2366	reason = "preserves the donor upstream plus eleven-operand adjoint boundary"
2367)]
2368fn mamba3_siso_backward_generic(
2369	output_gradient: &Matrix,
2370	c: &Matrix,
2371	b: &Matrix,
2372	x: &Matrix,
2373	z: &Matrix,
2374	adt: &Matrix,
2375	dt: &Matrix,
2376	trap: &Matrix,
2377	angle: &Matrix,
2378	c_bias: &Matrix,
2379	b_bias: &Matrix,
2380	d: &Matrix,
2381	config: SsmConfig,
2382	geometry: &Geometry,
2383) -> Result<SsmBackwardResult> {
2384	let contract = crate::core::operation::ml::MAMBA3_SISO_BACKWARD;
2385	let operation = contract.name();
2386	let runtime = x.runtime();
2387	let allocate = |shape: Vec<usize>| -> Result<Matrix> {
2388		let count = checked_count(&shape, operation)?;
2389		shader_u32(count, "generic SISO tensor element count", operation)?;
2390		Matrix::allocate(runtime, shape, count, DType::F32)
2391	};
2392	let batch = geometry.batch as usize;
2393	let length = geometry.length as usize;
2394	let heads = geometry.heads as usize;
2395	let groups = geometry.groups as usize;
2396	let head_dim = geometry.head_dim as usize;
2397	let state_size = geometry.state_size as usize;
2398	let angles = geometry.angles as usize;
2399	let batch_heads = geometry.batch_heads as usize;
2400	let chunks = length.div_ceil(32);
2401
2402	let entry = allocate(vec![batch_heads, chunks, head_dim, state_size])?;
2403	let theta_entry = allocate(vec![batch_heads, chunks, angles])?;
2404	let chunk_buffer = allocate(vec![batch_heads, 32, head_dim, state_size])?;
2405	let d_c_head = allocate(vec![batch, length, heads, state_size])?;
2406	let d_b_head = allocate(vec![batch, length, heads, state_size])?;
2407	let d_x = allocate(vec![batch, length, heads, head_dim])?;
2408	let d_z = allocate(vec![batch, length, heads, head_dim])?;
2409	let d_adt = allocate(vec![batch, length, heads])?;
2410	let d_dt = allocate(vec![batch, length, heads])?;
2411	let d_trap_partial = allocate(vec![batch, length, heads])?;
2412	let d_angle_head = allocate(vec![batch, heads, length, angles])?;
2413	let d_d_token = allocate(vec![batch, length, heads])?;
2414	let d_c = allocate(vec![batch, length, groups, state_size])?;
2415	let d_b = allocate(vec![batch, length, groups, state_size])?;
2416	let d_angle = allocate(vec![batch, length, angles])?;
2417	let d_c_bias = allocate(vec![heads, state_size])?;
2418	let d_b_bias = allocate(vec![heads, state_size])?;
2419	let d_d = allocate(vec![heads])?;
2420	let d_trap = allocate(vec![batch, length, heads])?;
2421
2422	let generic_buffers = [
2423		BufferBinding::read(c.storage()),
2424		BufferBinding::read(b.storage()),
2425		BufferBinding::read(x.storage()),
2426		BufferBinding::read(z.storage()),
2427		BufferBinding::read(adt.storage()),
2428		BufferBinding::read(dt.storage()),
2429		BufferBinding::read(trap.storage()),
2430		BufferBinding::read(angle.storage()),
2431		BufferBinding::read(c_bias.storage()),
2432		BufferBinding::read(b_bias.storage()),
2433		BufferBinding::read(d.storage()),
2434		BufferBinding::read(output_gradient.storage()),
2435		BufferBinding::read_write(entry.storage()),
2436		BufferBinding::read_write(theta_entry.storage()),
2437		BufferBinding::read_write(chunk_buffer.storage()),
2438		BufferBinding::write(d_c_head.storage()),
2439		BufferBinding::write(d_b_head.storage()),
2440		BufferBinding::write(d_x.storage()),
2441		BufferBinding::write(d_z.storage()),
2442		BufferBinding::write(d_adt.storage()),
2443		BufferBinding::read_write(d_dt.storage()),
2444		BufferBinding::read_write(d_trap_partial.storage()),
2445		BufferBinding::write(d_angle_head.storage()),
2446		BufferBinding::write(d_d_token.storage()),
2447	];
2448	let flags = u32::from(config.has_z) | (u32::from(config.has_d) << 1);
2449	let generic_constants = [
2450		PushConstant::U32(geometry.batch),
2451		PushConstant::U32(geometry.length),
2452		PushConstant::U32(geometry.heads),
2453		PushConstant::U32(geometry.groups),
2454		PushConstant::U32(geometry.head_dim),
2455		PushConstant::U32(geometry.state_size),
2456		PushConstant::U32(geometry.angles),
2457		PushConstant::U32(flags),
2458	];
2459
2460	let group_count = checked_count(&[batch, length, groups, state_size], operation)?;
2461	let angle_count = checked_count(&[batch, length, angles], operation)?;
2462	let bias_count = checked_count(&[heads, state_size], operation)?;
2463	let trap_count = checked_count(&[batch, length, heads], operation)?;
2464	let reduce_count = group_count
2465		.checked_add(angle_count)
2466		.and_then(|count| count.checked_add(bias_count))
2467		.and_then(|count| count.checked_add(heads))
2468		.and_then(|count| count.checked_add(trap_count))
2469		.ok_or_else(|| {
2470			Error::invalid_argument(format!(
2471				"{operation} generic reduction size overflows usize"
2472			))
2473		})?;
2474	let reduce_count = shader_u32(reduce_count, "generic reduction size", operation)?;
2475	let reduce_buffers = [
2476		BufferBinding::read(d_c_head.storage()),
2477		BufferBinding::read(d_b_head.storage()),
2478		BufferBinding::read(d_angle_head.storage()),
2479		BufferBinding::read(d_d_token.storage()),
2480		BufferBinding::read(trap.storage()),
2481		BufferBinding::read(d_trap_partial.storage()),
2482		BufferBinding::write(d_c.storage()),
2483		BufferBinding::write(d_b.storage()),
2484		BufferBinding::write(d_angle.storage()),
2485		BufferBinding::write(d_c_bias.storage()),
2486		BufferBinding::write(d_b_bias.storage()),
2487		BufferBinding::write(d_d.storage()),
2488		BufferBinding::write(d_trap.storage()),
2489	];
2490	let reduce_constants = [
2491		PushConstant::U32(geometry.batch),
2492		PushConstant::U32(geometry.length),
2493		PushConstant::U32(geometry.heads),
2494		PushConstant::U32(geometry.groups),
2495		PushConstant::U32(geometry.state_size),
2496		PushConstant::U32(geometry.angles),
2497		PushConstant::U32(reduce_count),
2498	];
2499	let dispatches = [
2500		ComputeDispatch {
2501			kernel: KernelId::MlMamba3SisoBackwardGenericF32,
2502			buffers: &generic_buffers,
2503			push_constants: &generic_constants,
2504			workgroups: [geometry.batch_heads, 1, 1],
2505			indirect: None,
2506		},
2507		ComputeDispatch {
2508			kernel: KernelId::MlMamba3SisoBackwardGenericReduceF32,
2509			buffers: &reduce_buffers,
2510			push_constants: &reduce_constants,
2511			workgroups: [reduce_count.div_ceil(256), 1, 1],
2512			indirect: None,
2513		},
2514	];
2515	let semantic_inputs = [
2516		output_gradient,
2517		c,
2518		b,
2519		x,
2520		z,
2521		adt,
2522		dt,
2523		trap,
2524		angle,
2525		c_bias,
2526		b_bias,
2527		d,
2528	];
2529	let semantic_outputs = [
2530		&d_c, &d_b, &d_x, &d_z, &d_adt, &d_dt, &d_trap, &d_angle, &d_c_bias, &d_b_bias, &d_d,
2531	];
2532	let attributes = [OpAttribute::UnsignedInteger {
2533		name: "config_identity".into(),
2534		value: config.identity(operation)?,
2535	}];
2536	runtime.record_split_semantic(
2537		&dispatches,
2538		SemanticDispatch {
2539			contract,
2540			inputs: &semantic_inputs,
2541			outputs: &semantic_outputs,
2542			attributes: &attributes,
2543		},
2544	)?;
2545	Ok(SsmBackwardResult {
2546		c: d_c,
2547		b: d_b,
2548		x: d_x,
2549		z: d_z,
2550		adt: d_adt,
2551		dt: d_dt,
2552		trap: d_trap,
2553		angle: d_angle,
2554		c_bias: d_c_bias,
2555		b_bias: d_b_bias,
2556		d: d_d,
2557	})
2558}
2559
2560// Public API
2561// ---------------------------------------------------------------------------
2562
2563/// Split and transform one packed Mamba-3 input projection.
2564///
2565/// `projected` has shape `[rows, projected_width]`, where
2566/// `projected_width = 2*inner_size + 2*num_groups*mimo_rank*state_size
2567/// + 3*num_heads + num_rope_angles`. `dt_bias` has one element per head.
2568///
2569/// The operation records one semantic node and one physical dispatch.
2570///
2571/// # Errors
2572///
2573/// Returns an error for invalid configuration, incompatible shape, dtype or
2574/// Runtime ownership, arithmetic overflow, or failed runtime recording.
2575pub fn mamba3_preprocess(
2576	projected: &Matrix,
2577	dt_bias: &Matrix,
2578	config: Mamba3PreprocessConfig,
2579) -> Result<Mamba3PreprocessResult> {
2580	let result = dispatch_mamba3_preprocess(projected, dt_bias, config)?;
2581	autograd::record_mamba3_preprocess(projected, dt_bias, &result, config)?;
2582	Ok(result)
2583}
2584
2585/// Compute the packed projection and dt-bias adjoints for Mamba-3 preprocess.
2586///
2587/// `output_gradients` follows the exact eight shapes returned by
2588/// [`mamba3_preprocess`]. Its dt-bias reduction is ordered by increasing row.
2589///
2590/// # Errors
2591///
2592/// Returns an error for invalid configuration, incompatible gradients, shape,
2593/// dtype or Runtime ownership, arithmetic overflow, or failed runtime recording.
2594pub fn mamba3_preprocess_backward(
2595	projected: &Matrix,
2596	dt_bias: &Matrix,
2597	output_gradients: &Mamba3PreprocessResult,
2598	config: Mamba3PreprocessConfig,
2599) -> Result<Mamba3PreprocessBackward> {
2600	let result = dispatch_mamba3_preprocess_backward(projected, dt_bias, output_gradients, config)?;
2601	Ok(Mamba3PreprocessBackward {
2602		projected: result.projected,
2603		dt_bias: result.dt_bias,
2604	})
2605}
2606
2607/// The eleven explicit adjoints of mamba3_siso.
2608pub struct SsmBackward {
2609	/// Gradient for C.
2610	pub c: Matrix,
2611	/// Gradient for B.
2612	pub b: Matrix,
2613	/// Gradient for x.
2614	pub x: Matrix,
2615	/// Gradient for z.
2616	pub z: Matrix,
2617	/// Gradient for A times dt.
2618	pub adt: Matrix,
2619	/// Gradient for dt.
2620	pub dt: Matrix,
2621	/// Gradient for the raw trapezoidal gate.
2622	pub trap: Matrix,
2623	/// Gradient for rotary angular velocity.
2624	pub angle: Matrix,
2625	/// Gradient for the C bias.
2626	pub c_bias: Matrix,
2627	/// Gradient for the B bias.
2628	pub b_bias: Matrix,
2629	/// Gradient for the D skip.
2630	pub d: Matrix,
2631}
2632
2633/// The fifteen explicit adjoints of [`mamba3_mimo`].
2634pub struct Mamba3MimoBackward {
2635	/// Gradient for C.
2636	pub c: Matrix,
2637	/// Gradient for B.
2638	pub b: Matrix,
2639	/// Gradient for x.
2640	pub x: Matrix,
2641	/// Gradient for z.
2642	pub z: Matrix,
2643	/// Gradient for A times dt.
2644	pub adt: Matrix,
2645	/// Gradient for dt.
2646	pub dt: Matrix,
2647	/// Gradient for the raw trapezoidal gate.
2648	pub trap: Matrix,
2649	/// Gradient for rotary angular velocity.
2650	pub angle: Matrix,
2651	/// Gradient for the C bias.
2652	pub c_bias: Matrix,
2653	/// Gradient for the B bias.
2654	pub b_bias: Matrix,
2655	/// Gradient for the D skip.
2656	pub d: Matrix,
2657	/// Gradient for the MIMO input projection.
2658	pub mimo_x: Matrix,
2659	/// Gradient for the MIMO gate projection.
2660	pub mimo_z: Matrix,
2661	/// Gradient for the MIMO output projection.
2662	pub mimo_o: Matrix,
2663	/// Gradient for the optional output-normalization weight.
2664	pub norm_weight: Matrix,
2665}
2666
2667/// Run the Mamba-3 SISO selective-state recurrence.
2668///
2669/// Operand layouts are C/B `[B,L,G,N]`, x/z/output `[B,L,H,P]`,
2670/// A-times-dt/dt/trap `[B,L,H]`, angle `[B,L,A]`, C/B bias `[H,N]`, and D
2671/// `[H]`. All operands are same-runtime F32 matrices.
2672///
2673/// # Errors
2674///
2675/// Returns an error for mismatched geometry, unsupported dimensions, shape
2676/// overflow, or failed runtime recording.
2677#[allow(
2678	clippy::too_many_arguments,
2679	reason = "preserves the donor eleven-operand selective-scan contract"
2680)]
2681pub fn mamba3_siso(
2682	c: &Matrix,
2683	b: &Matrix,
2684	x: &Matrix,
2685	z: &Matrix,
2686	adt: &Matrix,
2687	dt: &Matrix,
2688	trap: &Matrix,
2689	angle: &Matrix,
2690	c_bias: &Matrix,
2691	b_bias: &Matrix,
2692	d: &Matrix,
2693	config: SsmConfig,
2694) -> Result<Matrix> {
2695	let output = dispatch_mamba3_siso(c, b, x, z, adt, dt, trap, angle, c_bias, b_bias, d, config)?;
2696	autograd::record_mamba3_siso(
2697		[c, b, x, z, adt, dt, trap, angle, c_bias, b_bias, d],
2698		&output,
2699		config,
2700	)?;
2701	Ok(output)
2702}
2703
2704/// Advance one Mamba-3 SISO token and update four explicit recurrent states.
2705///
2706/// Operand layouts are the length-one forms accepted by [`mamba3_siso`]. State
2707/// layouts are SSM `[B,H,P,N]`, cumulative angle `[B,H,A]`, previous key
2708/// `[B,H,N]`, and previous value `[B,H,P]`. The states are mutated only after
2709/// the complete operation has been validated and recorded.
2710///
2711/// # Errors
2712///
2713/// Returns an error unless `config.sequence_length == 1`, every operand and
2714/// state has the configured same-runtime F32 shape, or recording fails.
2715#[allow(
2716	clippy::too_many_arguments,
2717	reason = "preserves the donor eleven operands plus four explicit recurrent-state buffers"
2718)]
2719pub fn mamba3_siso_step(
2720	c: &Matrix,
2721	b: &Matrix,
2722	x: &Matrix,
2723	z: &Matrix,
2724	adt: &Matrix,
2725	dt: &Matrix,
2726	trap: &Matrix,
2727	angle: &Matrix,
2728	c_bias: &Matrix,
2729	b_bias: &Matrix,
2730	d: &Matrix,
2731	ssm_state: &mut Matrix,
2732	angle_state: &mut Matrix,
2733	k_state: &mut Matrix,
2734	v_state: &mut Matrix,
2735	config: SsmConfig,
2736) -> Result<Matrix> {
2737	dispatch_mamba3_siso_step(
2738		c,
2739		b,
2740		x,
2741		z,
2742		adt,
2743		dt,
2744		trap,
2745		angle,
2746		c_bias,
2747		b_bias,
2748		d,
2749		ssm_state,
2750		angle_state,
2751		k_state,
2752		v_state,
2753		config,
2754	)
2755}
2756
2757/// Run the shared-state Mamba-3 MIMO selective scan.
2758///
2759/// C/B use `[B,L,R*G,N]`; the three MIMO projections use `[H,R,P]`; the
2760/// output-normalization weight always uses `[H,P]` and is consumed only when
2761/// `config.has_output_norm` is true. The remaining layouts match
2762/// [`mamba3_siso`].
2763///
2764/// # Errors
2765///
2766/// Returns an error for mismatched geometry, rank outside `1..=8`, unsupported
2767/// dimensions, shape overflow, or failed runtime recording.
2768#[allow(
2769	clippy::too_many_arguments,
2770	reason = "preserves the donor fifteen-operand MIMO selective-scan contract"
2771)]
2772pub fn mamba3_mimo(
2773	c: &Matrix,
2774	b: &Matrix,
2775	x: &Matrix,
2776	z: &Matrix,
2777	adt: &Matrix,
2778	dt: &Matrix,
2779	trap: &Matrix,
2780	angle: &Matrix,
2781	c_bias: &Matrix,
2782	b_bias: &Matrix,
2783	d: &Matrix,
2784	mimo_x: &Matrix,
2785	mimo_z: &Matrix,
2786	mimo_o: &Matrix,
2787	norm_weight: &Matrix,
2788	config: SsmConfig,
2789) -> Result<Matrix> {
2790	let output = dispatch_mamba3_mimo(
2791		c,
2792		b,
2793		x,
2794		z,
2795		adt,
2796		dt,
2797		trap,
2798		angle,
2799		c_bias,
2800		b_bias,
2801		d,
2802		mimo_x,
2803		mimo_z,
2804		mimo_o,
2805		norm_weight,
2806		config,
2807	)?;
2808	autograd::record_mamba3_mimo(
2809		[
2810			c,
2811			b,
2812			x,
2813			z,
2814			adt,
2815			dt,
2816			trap,
2817			angle,
2818			c_bias,
2819			b_bias,
2820			d,
2821			mimo_x,
2822			mimo_z,
2823			mimo_o,
2824			norm_weight,
2825		],
2826		&output,
2827		config,
2828	)?;
2829	Ok(output)
2830}
2831
2832/// Advance one Mamba-3 MIMO token and update four explicit recurrent states.
2833///
2834/// State layouts are SSM `[B,H,P,N]`, angle `[B,H,A]`, key `[B,H,R,N]`,
2835/// and value `[B,H,R,P]`.
2836///
2837/// # Errors
2838///
2839/// Returns an error unless `config.sequence_length == 1`, every operand and
2840/// state matches the configured same-runtime F32 layout, or recording fails.
2841#[allow(
2842	clippy::too_many_arguments,
2843	reason = "preserves the donor fifteen operands plus four recurrent-state buffers"
2844)]
2845pub fn mamba3_mimo_step(
2846	c: &Matrix,
2847	b: &Matrix,
2848	x: &Matrix,
2849	z: &Matrix,
2850	adt: &Matrix,
2851	dt: &Matrix,
2852	trap: &Matrix,
2853	angle: &Matrix,
2854	c_bias: &Matrix,
2855	b_bias: &Matrix,
2856	d: &Matrix,
2857	mimo_x: &Matrix,
2858	mimo_z: &Matrix,
2859	mimo_o: &Matrix,
2860	norm_weight: &Matrix,
2861	ssm_state: &mut Matrix,
2862	angle_state: &mut Matrix,
2863	k_state: &mut Matrix,
2864	v_state: &mut Matrix,
2865	config: SsmConfig,
2866) -> Result<Matrix> {
2867	dispatch_mamba3_mimo_step(
2868		c,
2869		b,
2870		x,
2871		z,
2872		adt,
2873		dt,
2874		trap,
2875		angle,
2876		c_bias,
2877		b_bias,
2878		d,
2879		mimo_x,
2880		mimo_z,
2881		mimo_o,
2882		norm_weight,
2883		ssm_state,
2884		angle_state,
2885		k_state,
2886		v_state,
2887		config,
2888	)
2889}
2890
2891/// Compute all fifteen explicit Mamba-3 MIMO adjoints.
2892///
2893/// The implementation records the donor's deterministic prepare, post,
2894/// reverse-core, inverse-rotation, and reduction stages as one semantic
2895/// operation.
2896///
2897/// # Errors
2898///
2899/// Returns an error for mismatched geometry, unsupported dimensions, shape
2900/// overflow, or failed runtime recording.
2901#[allow(
2902	clippy::too_many_arguments,
2903	reason = "preserves the donor upstream plus fifteen-operand MIMO adjoint contract"
2904)]
2905pub fn mamba3_mimo_backward(
2906	output_gradient: &Matrix,
2907	c: &Matrix,
2908	b: &Matrix,
2909	x: &Matrix,
2910	z: &Matrix,
2911	adt: &Matrix,
2912	dt: &Matrix,
2913	trap: &Matrix,
2914	angle: &Matrix,
2915	c_bias: &Matrix,
2916	b_bias: &Matrix,
2917	d: &Matrix,
2918	mimo_x: &Matrix,
2919	mimo_z: &Matrix,
2920	mimo_o: &Matrix,
2921	norm_weight: &Matrix,
2922	config: SsmConfig,
2923) -> Result<Mamba3MimoBackward> {
2924	let result = dispatch_mamba3_mimo_backward(
2925		output_gradient,
2926		c,
2927		b,
2928		x,
2929		z,
2930		adt,
2931		dt,
2932		trap,
2933		angle,
2934		c_bias,
2935		b_bias,
2936		d,
2937		mimo_x,
2938		mimo_z,
2939		mimo_o,
2940		norm_weight,
2941		config,
2942	)?;
2943	Ok(Mamba3MimoBackward {
2944		c: result.c,
2945		b: result.b,
2946		x: result.x,
2947		z: result.z,
2948		adt: result.adt,
2949		dt: result.dt,
2950		trap: result.trap,
2951		angle: result.angle,
2952		c_bias: result.c_bias,
2953		b_bias: result.b_bias,
2954		d: result.d,
2955		mimo_x: result.mimo_x,
2956		mimo_z: result.mimo_z,
2957		mimo_o: result.mimo_o,
2958		norm_weight: result.norm_weight,
2959	})
2960}
2961
2962/// Compute all explicit Mamba-3 SISO adjoints.
2963///
2964/// The initial OARS physical route is the donor short-training route and
2965/// accepts L <= 16, P <= 16, N <= 32, and A <= 8.
2966///
2967/// # Errors
2968///
2969/// Returns an error for mismatched inputs, a shape outside the admitted short
2970/// route, overflow, or failed runtime recording.
2971#[allow(
2972	clippy::too_many_arguments,
2973	reason = "preserves the donor upstream plus eleven-operand adjoint contract"
2974)]
2975pub fn mamba3_siso_backward(
2976	output_gradient: &Matrix,
2977	c: &Matrix,
2978	b: &Matrix,
2979	x: &Matrix,
2980	z: &Matrix,
2981	adt: &Matrix,
2982	dt: &Matrix,
2983	trap: &Matrix,
2984	angle: &Matrix,
2985	c_bias: &Matrix,
2986	b_bias: &Matrix,
2987	d: &Matrix,
2988	config: SsmConfig,
2989) -> Result<SsmBackward> {
2990	let result = dispatch_mamba3_siso_backward(
2991		output_gradient,
2992		c,
2993		b,
2994		x,
2995		z,
2996		adt,
2997		dt,
2998		trap,
2999		angle,
3000		c_bias,
3001		b_bias,
3002		d,
3003		config,
3004	)?;
3005	Ok(SsmBackward {
3006		c: result.c,
3007		b: result.b,
3008		x: result.x,
3009		z: result.z,
3010		adt: result.adt,
3011		dt: result.dt,
3012		trap: result.trap,
3013		angle: result.angle,
3014		c_bias: result.c_bias,
3015		b_bias: result.b_bias,
3016		d: result.d,
3017	})
3018}