Skip to main content

oa/matrix/
index.rs

1//! Matrix selection and sparse-routing operations.
2
3use crate::{
4	DType, Error, Matrix, OpAttribute, OperationContract, Result,
5	matrix::autograd,
6	runtime::{
7		BufferBinding, ComputeDispatch, EngineHandle, IndirectDispatch, KernelId,
8		OptionalSemanticDispatch, PushConstant, SemanticDispatch,
9	},
10};
11
12const TOP_K_LIMIT: usize = 1024;
13const EXPERT_LIMIT: usize = 256;
14
15/// Gather rows from an FP32 table using arbitrary-shape integer indices.
16///
17/// The table must be `[rows,width]`; indices are flattened and output is
18/// `[num_indices,width]`, matching OA C++ `FnMatrix::gather`. U8, U32, and I32
19/// indices use one bounded kernel. Invalid rows produce NaN without reading
20/// outside the table.
21///
22/// # Errors
23///
24/// Returns an error for incompatible rank, dtype, Engine ownership, shader ABI,
25/// allocation, or recording.
26pub fn gather(input: &Matrix, indices: &Matrix) -> Result<Matrix> {
27	const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER;
28	let operation = CONTRACT.name();
29	let [rows, width] = input.shape() else {
30		return Err(Error::invalid_argument(format!(
31			"{operation} input must have shape [rows,width]"
32		)));
33	};
34	if *rows == 0
35		|| *width == 0
36		|| input.dtype() != DType::F32
37		|| indices.shape().is_empty()
38		|| !matches!(indices.dtype(), DType::U8 | DType::U32 | DType::I32)
39		|| !input.engine_handle().same_as(indices.engine_handle())
40	{
41		return Err(Error::invalid_argument(format!(
42			"{operation} requires a nonempty FP32 [rows,width] table and same-engine U8/U32/I32 indices"
43		)));
44	}
45	let count = indices.num_elements();
46	let output_count = count
47		.checked_mul(*width)
48		.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
49	let output = Matrix::allocate(
50		input.engine_handle(),
51		vec![count, *width],
52		output_count,
53		DType::F32,
54	)?;
55	let output_count_u32 = as_u32(output_count, operation, "output element count")?;
56	if output_count_u32 != 0 {
57		let buffers = [
58			BufferBinding::read(input.storage()),
59			BufferBinding::read(indices.storage()),
60			BufferBinding::write(output.storage()),
61		];
62		let push_constants = [
63			PushConstant::U32(as_u32(count, operation, "index count")?),
64			PushConstant::U32(as_u32(*rows, operation, "table row count")?),
65			PushConstant::U32(as_u32(*width, operation, "table row width")?),
66			PushConstant::U32(u32::from(indices.dtype() != DType::U8)),
67		];
68		input.engine_handle().record_semantic(
69			ComputeDispatch {
70				kernel: KernelId::MatrixGatherF32,
71				buffers: &buffers,
72				push_constants: &push_constants,
73				workgroups: KernelId::MatrixGatherF32.linear_workgroups(output_count_u32),
74				indirect: None,
75			},
76			SemanticDispatch {
77				contract: CONTRACT,
78				inputs: &[input, indices],
79				outputs: &[&output],
80				attributes: &[],
81			},
82		)?;
83	}
84	autograd::record_gather(input, indices, &output)?;
85	Ok(output)
86}
87
88pub(crate) fn gather_backward(
89	input_shape: &[usize],
90	indices: &Matrix,
91	output_gradient: &Matrix,
92) -> Result<Matrix> {
93	const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER_BACKWARD;
94	let operation = CONTRACT.name();
95	let [rows, width] = input_shape else {
96		return Err(Error::invalid_argument(format!(
97			"{operation} input shape must be [rows,width]"
98		)));
99	};
100	let count = indices.num_elements();
101	if *rows == 0
102		|| *width == 0
103		|| indices.shape().is_empty()
104		|| !matches!(indices.dtype(), DType::U8 | DType::U32 | DType::I32)
105		|| output_gradient.dtype() != DType::F32
106		|| output_gradient.shape() != [count, *width]
107		|| !indices
108			.engine_handle()
109			.same_as(output_gradient.engine_handle())
110	{
111		return Err(Error::invalid_argument(format!(
112			"{operation} requires integer indices and matching FP32 [num_indices,width] gradient"
113		)));
114	}
115	let gradient = Matrix::allocate(
116		output_gradient.engine_handle(),
117		input_shape.to_vec(),
118		rows
119			.checked_mul(*width)
120			.ok_or_else(|| Error::invalid_argument(format!("{operation} size overflows usize")))?,
121		DType::F32,
122	)?;
123	let rows_u32 = as_u32(*rows, operation, "table row count")?;
124	let buffers = [
125		BufferBinding::read(indices.storage()),
126		BufferBinding::read(output_gradient.storage()),
127		BufferBinding::write(gradient.storage()),
128	];
129	let push_constants = [
130		PushConstant::U32(as_u32(count, operation, "index count")?),
131		PushConstant::U32(rows_u32),
132		PushConstant::U32(as_u32(*width, operation, "table row width")?),
133		PushConstant::U32(u32::from(indices.dtype() != DType::U8)),
134	];
135	let attributes = [OpAttribute::Shape {
136		name: "input_shape".into(),
137		value: input_shape.to_vec(),
138	}];
139	output_gradient.engine_handle().record_semantic(
140		ComputeDispatch {
141			kernel: KernelId::MatrixGatherBackwardF32,
142			buffers: &buffers,
143			push_constants: &push_constants,
144			workgroups: [rows_u32, 1, 1],
145			indirect: None,
146		},
147		SemanticDispatch {
148			contract: CONTRACT,
149			inputs: &[indices, output_gradient],
150			outputs: &[&gradient],
151			attributes: &attributes,
152		},
153	)?;
154	Ok(gradient)
155}
156
157/// Largest values and exact I32 source indices returned by [`top_k`].
158#[must_use]
159pub struct TopKResult {
160	/// Values in descending order along the selected last axis.
161	pub values: Matrix,
162	/// I32 source indices. Equal values select the lower source index first.
163	pub indices: Matrix,
164}
165
166/// Device-resident stable dropless route plan returned by [`moe_expert_plan`].
167#[must_use]
168pub struct MoeExpertPlan {
169	/// U32 route count for each expert, shaped `[E]`.
170	pub counts: Matrix,
171	/// U32 exclusive expert offsets, shaped `[E + 1]`.
172	pub offsets: Matrix,
173	/// U32 source-token index for each expert-major packed route.
174	pub packed_token: Matrix,
175	/// U32 expert index for each expert-major packed route.
176	pub packed_expert: Matrix,
177	/// U32 original token-major flat route index for each packed route.
178	pub packed_slot: Matrix,
179	/// U32 packed position for each original token-major route.
180	pub inverse: Matrix,
181}
182
183/// Device-resident row-compaction plan returned by [`compact_rows`].
184///
185/// `row_map`, `count`, and `dispatch_args` are auxiliary device values; only
186/// `values` participates in differentiation. `dispatch_args` is consumed by
187/// the indirect-dispatch variants [`scatter_rows_indirect`],
188/// `crate::matrix::compact_rows_backward`, and
189/// `crate::matrix::scatter_rows_backward`.
190#[must_use]
191pub struct CompactRowsResult {
192	/// FP32 packed selected rows, shaped `[T, D]` with unselected slots zeroed.
193	pub values: Matrix,
194	/// U32 source row for each packed slot, shaped `[T]`.
195	pub row_map: Matrix,
196	/// U32 selected-row count, shaped `[1]`.
197	pub count: Matrix,
198	/// U32 indirect-dispatch extents `[(count * D + 255) / 256, 1, 1]`.
199	pub dispatch_args: Matrix,
200}
201
202/// Compare every FP32 element with one scalar and return an FP32 zero/one mask.
203///
204/// Equality follows the device's ordinary IEEE comparison: NaN never compares
205/// equal, while positive and negative zero compare equal. The result is
206/// intentionally detached because a discrete mask has no admitted adjoint.
207///
208/// # Errors
209///
210/// Returns an error when `input` is not FP32, its element count exceeds the
211/// shader ABI, allocation fails, or runtime recording fails.
212pub fn equal(input: &Matrix, value: f32) -> Result<Matrix> {
213	const CONTRACT: OperationContract = crate::core::operation::matrix::EQUAL;
214	let operation = CONTRACT.name();
215	if input.dtype() != DType::F32 {
216		return Err(Error::invalid_argument(format!(
217			"{operation} requires an F32 input"
218		)));
219	}
220	let element_count = u32::try_from(input.element_count())
221		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
222	let output = Matrix::allocate(
223		input.engine_handle(),
224		input.shape().to_vec(),
225		input.element_count(),
226		DType::F32,
227	)?;
228	if element_count != 0 {
229		let buffers = [
230			BufferBinding::read(input.storage()),
231			BufferBinding::write(output.storage()),
232		];
233		let push_constants = [PushConstant::U32(element_count), PushConstant::F32(value)];
234		let inputs = [input];
235		let outputs = [&output];
236		let attributes = [OpAttribute::Float {
237			name: "value".into(),
238			value: f64::from(value),
239		}];
240		input.engine_handle().record_semantic(
241			ComputeDispatch {
242				kernel: KernelId::MatrixEqualF32,
243				buffers: &buffers,
244				push_constants: &push_constants,
245				workgroups: KernelId::MatrixEqualF32.linear_workgroups(element_count),
246				indirect: None,
247			},
248			SemanticDispatch {
249				contract: CONTRACT,
250				inputs: &inputs,
251				outputs: &outputs,
252				attributes: &attributes,
253			},
254		)?;
255	}
256	Ok(output)
257}
258
259/// Apply the additive causal mask to the final two score dimensions.
260///
261/// Every `[.., Tq, Tk]` plane keeps positions `k <= q` and writes `-1e9` above
262/// the diagonal, matching OA C++ `FnMatrix::causalMask`. Inputs require at
263/// least two axes; earlier axes are treated as a flattened batch.
264///
265/// # Errors
266///
267/// Returns an error when `input` is not FP32, has fewer than two axes or an
268/// empty extent, its element count exceeds the shader ABI, allocation fails,
269/// or runtime recording fails.
270pub fn causal_mask(input: &Matrix) -> Result<Matrix> {
271	const CONTRACT: OperationContract = crate::core::operation::matrix::CAUSAL_MASK;
272	let operation = CONTRACT.name();
273	let (tq, tk) = causal_mask_axes(input, operation)?;
274	let element_count = u32::try_from(input.element_count())
275		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
276	let output = Matrix::allocate(
277		input.engine_handle(),
278		input.shape().to_vec(),
279		input.element_count(),
280		DType::F32,
281	)?;
282	let buffers = [
283		BufferBinding::read(input.storage()),
284		BufferBinding::write(output.storage()),
285	];
286	let push_constants = [
287		PushConstant::U32(element_count),
288		PushConstant::U32(tq),
289		PushConstant::U32(tk),
290	];
291	let inputs = [input];
292	let outputs = [&output];
293	input.engine_handle().record_semantic(
294		ComputeDispatch {
295			kernel: KernelId::MatrixCausalMaskF32,
296			buffers: &buffers,
297			push_constants: &push_constants,
298			workgroups: KernelId::MatrixCausalMaskF32.linear_workgroups(element_count),
299			indirect: None,
300		},
301		SemanticDispatch {
302			contract: CONTRACT,
303			inputs: &inputs,
304			outputs: &outputs,
305			attributes: &[],
306		},
307	)?;
308	autograd::record_causal_mask(input, &output)?;
309	Ok(output)
310}
311
312/// Zero the causal-mask adjoint above the diagonal of the final two axes.
313///
314/// This numerical provider performs Matrix/device operations only; it does not
315/// inspect or mutate a gradient tape.
316///
317/// # Errors
318///
319/// Returns an error under the same contract as [`causal_mask`].
320pub(crate) fn causal_mask_backward(output_gradient: &Matrix) -> Result<Matrix> {
321	const CONTRACT: OperationContract = crate::core::operation::matrix::CAUSAL_MASK_BACKWARD;
322	let operation = CONTRACT.name();
323	let (tq, tk) = causal_mask_axes(output_gradient, operation)?;
324	let element_count = u32::try_from(output_gradient.element_count())
325		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
326	let input_gradient = Matrix::allocate(
327		output_gradient.engine_handle(),
328		output_gradient.shape().to_vec(),
329		output_gradient.element_count(),
330		DType::F32,
331	)?;
332	let buffers = [
333		BufferBinding::read(output_gradient.storage()),
334		BufferBinding::write(input_gradient.storage()),
335	];
336	let push_constants = [
337		PushConstant::U32(element_count),
338		PushConstant::U32(tq),
339		PushConstant::U32(tk),
340	];
341	let inputs = [output_gradient];
342	let outputs = [&input_gradient];
343	output_gradient.engine_handle().record_semantic(
344		ComputeDispatch {
345			kernel: KernelId::MatrixCausalMaskBackwardF32,
346			buffers: &buffers,
347			push_constants: &push_constants,
348			workgroups: KernelId::MatrixCausalMaskBackwardF32.linear_workgroups(element_count),
349			indirect: None,
350		},
351		SemanticDispatch {
352			contract: CONTRACT,
353			inputs: &inputs,
354			outputs: &outputs,
355			attributes: &[],
356		},
357	)?;
358	Ok(input_gradient)
359}
360
361/// Compare every FP32 element with one scalar and return an FP32 zero/one mask
362/// for `input >= value`.
363///
364/// Ordering follows the device's ordinary IEEE comparison: NaN always produces
365/// zero. The result is intentionally detached because a discrete mask has no
366/// admitted adjoint.
367///
368/// # Errors
369///
370/// Returns an error under the same contract as [`equal`].
371pub fn greater_equal(input: &Matrix, value: f32) -> Result<Matrix> {
372	const CONTRACT: OperationContract = crate::core::operation::matrix::GREATER_EQUAL;
373	let operation = CONTRACT.name();
374	if input.dtype() != DType::F32 {
375		return Err(Error::invalid_argument(format!(
376			"{operation} requires an F32 input"
377		)));
378	}
379	let element_count = u32::try_from(input.element_count())
380		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
381	let output = Matrix::allocate(
382		input.engine_handle(),
383		input.shape().to_vec(),
384		input.element_count(),
385		DType::F32,
386	)?;
387	if element_count != 0 {
388		let buffers = [
389			BufferBinding::read(input.storage()),
390			BufferBinding::write(output.storage()),
391		];
392		let push_constants = [PushConstant::U32(element_count), PushConstant::F32(value)];
393		let inputs = [input];
394		let outputs = [&output];
395		let attributes = [OpAttribute::Float {
396			name: "value".into(),
397			value: f64::from(value),
398		}];
399		input.engine_handle().record_semantic(
400			ComputeDispatch {
401				kernel: KernelId::MatrixGreaterEqualF32,
402				buffers: &buffers,
403				push_constants: &push_constants,
404				workgroups: KernelId::MatrixGreaterEqualF32.linear_workgroups(element_count),
405				indirect: None,
406			},
407			SemanticDispatch {
408				contract: CONTRACT,
409				inputs: &inputs,
410				outputs: &outputs,
411				attributes: &attributes,
412			},
413		)?;
414	}
415	Ok(output)
416}
417
418/// Convert an FP32 matrix to I32, truncating each element toward zero.
419///
420/// The result is intentionally detached because a discrete cast has no
421/// admitted adjoint.
422///
423/// # Errors
424///
425/// Returns an error when `input` is not FP32, its element count exceeds the
426/// shader ABI, allocation fails, or runtime recording fails.
427pub fn cast_f32_i32(input: &Matrix) -> Result<Matrix> {
428	const CONTRACT: OperationContract = crate::core::operation::matrix::CAST_F32_I32;
429	let operation = CONTRACT.name();
430	if input.dtype() != DType::F32 {
431		return Err(Error::invalid_argument(format!(
432			"{operation} requires an F32 input"
433		)));
434	}
435	let element_count = u32::try_from(input.element_count())
436		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
437	let output = Matrix::allocate(
438		input.engine_handle(),
439		input.shape().to_vec(),
440		input.element_count(),
441		DType::I32,
442	)?;
443	if element_count != 0 {
444		let buffers = [
445			BufferBinding::read(input.storage()),
446			BufferBinding::write(output.storage()),
447		];
448		let push_constants = [PushConstant::U32(element_count)];
449		let inputs = [input];
450		let outputs = [&output];
451		input.engine_handle().record_semantic(
452			ComputeDispatch {
453				kernel: KernelId::MatrixCastF32I32F32,
454				buffers: &buffers,
455				push_constants: &push_constants,
456				workgroups: KernelId::MatrixCastF32I32F32.linear_workgroups(element_count),
457				indirect: None,
458			},
459			SemanticDispatch {
460				contract: CONTRACT,
461				inputs: &inputs,
462				outputs: &outputs,
463				attributes: &[],
464			},
465		)?;
466	}
467	Ok(output)
468}
469
470/// Convert an I32 or U32 matrix to FP32.
471///
472/// The result is intentionally detached because a discrete cast has no
473/// admitted adjoint.
474///
475/// # Errors
476///
477/// Returns an error when `input` is not I32 or U32, its element count exceeds
478/// the shader ABI, allocation fails, or runtime recording fails.
479pub fn cast_i32_f32(input: &Matrix) -> Result<Matrix> {
480	const CONTRACT: OperationContract = crate::core::operation::matrix::CAST_I32_F32;
481	let operation = CONTRACT.name();
482	if !matches!(input.dtype(), DType::I32 | DType::U32) {
483		return Err(Error::invalid_argument(format!(
484			"{operation} requires an I32 or U32 input"
485		)));
486	}
487	let element_count = u32::try_from(input.element_count())
488		.map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
489	let output = Matrix::allocate(
490		input.engine_handle(),
491		input.shape().to_vec(),
492		input.element_count(),
493		DType::F32,
494	)?;
495	if element_count != 0 {
496		let buffers = [
497			BufferBinding::read(input.storage()),
498			BufferBinding::write(output.storage()),
499		];
500		let source_dtype = if input.dtype() == DType::I32 { 0 } else { 1 };
501		let push_constants = [
502			PushConstant::U32(element_count),
503			PushConstant::U32(source_dtype),
504		];
505		let inputs = [input];
506		let outputs = [&output];
507		input.engine_handle().record_semantic(
508			ComputeDispatch {
509				kernel: KernelId::MatrixCastI32F32F32,
510				buffers: &buffers,
511				push_constants: &push_constants,
512				workgroups: KernelId::MatrixCastI32F32F32.linear_workgroups(element_count),
513				indirect: None,
514			},
515			SemanticDispatch {
516				contract: CONTRACT,
517				inputs: &inputs,
518				outputs: &outputs,
519				attributes: &[],
520			},
521		)?;
522	}
523	Ok(output)
524}
525
526fn causal_mask_axes(input: &Matrix, operation: &'static str) -> Result<(u32, u32)> {
527	if input.dtype() != DType::F32 || input.shape().len() < 2 || input.element_count() == 0 {
528		return Err(Error::invalid_argument(format!(
529			"{operation} requires a nonempty FP32 matrix with at least two axes"
530		)));
531	}
532	let tq = as_u32(
533		input.shape()[input.shape().len() - 2],
534		operation,
535		"query extent",
536	)?;
537	let tk = as_u32(
538		input.shape()[input.shape().len() - 1],
539		operation,
540		"key extent",
541	)?;
542	Ok((tq, tk))
543}
544
545/// Return the largest `k` FP32 values and their I32 indices on the last axis.
546///
547/// Rank-one and rank-two inputs are admitted. `dim` may be `-1` or the exact
548/// last-axis index. Values are sorted descending; ties select lower indices.
549/// `k` is clamped to the last-axis extent, matching OA C++.
550///
551/// # Errors
552///
553/// Returns an error for an unsupported rank, dtype, axis, negative `k`, a
554/// request above the admitted 1024-entry GPU limit, an empty last axis, size
555/// overflow, allocation failure, or runtime recording failure.
556pub fn top_k(input: &Matrix, k: i32, dim: i32) -> Result<TopKResult> {
557	const CONTRACT: OperationContract = crate::core::operation::matrix::TOP_K;
558	let operation = CONTRACT.name();
559	if input.dtype() != DType::F32 || !(1..=2).contains(&input.shape().len()) {
560		return Err(Error::invalid_argument(format!(
561			"{operation} requires a rank-one or rank-two F32 matrix"
562		)));
563	}
564	let last_dim = i32::try_from(input.shape().len() - 1)
565		.map_err(|_| Error::invalid_argument(format!("{operation} rank exceeds i32")))?;
566	if dim != -1 && dim != last_dim {
567		return Err(Error::invalid_argument(format!(
568			"{operation} supports only the last axis; found dim {dim}"
569		)));
570	}
571	let requested = usize::try_from(k)
572		.map_err(|_| Error::invalid_argument(format!("{operation} k must be nonnegative")))?;
573	let row_width = *input.shape().last().expect("validated nonempty rank");
574	if row_width == 0 {
575		return Err(Error::invalid_argument(format!(
576			"{operation} requires a nonempty last axis"
577		)));
578	}
579	let selected = requested.min(row_width);
580	if selected > TOP_K_LIMIT {
581		return Err(Error::invalid_argument(format!(
582			"{operation} supports at most {TOP_K_LIMIT} selected values"
583		)));
584	}
585	let rows = if input.shape().len() == 1 {
586		1
587	} else {
588		input.shape()[0]
589	};
590	let output_count = rows
591		.checked_mul(selected)
592		.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
593	let mut output_shape = input.shape().to_vec();
594	*output_shape.last_mut().expect("validated nonempty rank") = selected;
595	let values = Matrix::allocate(
596		input.engine_handle(),
597		output_shape.clone(),
598		output_count,
599		DType::F32,
600	)?;
601	let indices = Matrix::allocate(
602		input.engine_handle(),
603		output_shape,
604		output_count,
605		DType::I32,
606	)?;
607	if selected != 0 && rows != 0 {
608		let rows = as_u32(rows, operation, "row count")?;
609		let row_width = as_u32(row_width, operation, "last-axis extent")?;
610		let selected = as_u32(selected, operation, "k")?;
611		let buffers = [
612			BufferBinding::read(input.storage()),
613			BufferBinding::write(values.storage()),
614			BufferBinding::write(indices.storage()),
615		];
616		let push_constants = [
617			PushConstant::U32(rows),
618			PushConstant::U32(row_width),
619			PushConstant::U32(selected),
620		];
621		let inputs = [input];
622		let outputs = [&values, &indices];
623		let attributes = [
624			OpAttribute::SignedInteger {
625				name: "k".into(),
626				value: i64::from(k),
627			},
628			OpAttribute::SignedInteger {
629				name: "dim".into(),
630				value: i64::from(dim),
631			},
632		];
633		input.engine_handle().record_semantic(
634			ComputeDispatch {
635				kernel: KernelId::MatrixTopKF32,
636				buffers: &buffers,
637				push_constants: &push_constants,
638				workgroups: [rows, 1, 1],
639				indirect: None,
640			},
641			SemanticDispatch {
642				contract: CONTRACT,
643				inputs: &inputs,
644				outputs: &outputs,
645				attributes: &attributes,
646			},
647		)?;
648	}
649	Ok(TopKResult { values, indices })
650}
651
652/// Expand I32 `[T, K]` expert indices into an exact FP32 `[T, E]` mask.
653///
654/// # Errors
655///
656/// Returns an error unless the input is nonempty rank-two I32, `num_experts`
657/// is positive, all sizes fit the shader ABI, or runtime recording fails.
658pub fn top_k_mask(indices: &Matrix, num_experts: usize) -> Result<Matrix> {
659	const CONTRACT: OperationContract = crate::core::operation::matrix::TOP_K_MASK;
660	let operation = CONTRACT.name();
661	let [tokens, routes_per_token] = indices.shape() else {
662		return Err(Error::invalid_argument(format!(
663			"{operation} requires rank-two I32 indices"
664		)));
665	};
666	if indices.dtype() != DType::I32 || *tokens == 0 || *routes_per_token == 0 {
667		return Err(Error::invalid_argument(format!(
668			"{operation} requires nonempty rank-two I32 indices"
669		)));
670	}
671	if num_experts == 0 {
672		return Err(Error::invalid_argument(format!(
673			"{operation} requires at least one expert"
674		)));
675	}
676	let output_count = tokens
677		.checked_mul(num_experts)
678		.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
679	let tokens_u32 = as_u32(*tokens, operation, "token count")?;
680	let experts_u32 = as_u32(num_experts, operation, "expert count")?;
681	let routes_u32 = as_u32(*routes_per_token, operation, "routes per token")?;
682	let output_count_u32 = as_u32(output_count, operation, "output element count")?;
683	let output = Matrix::allocate(
684		indices.engine_handle(),
685		vec![*tokens, num_experts],
686		output_count,
687		DType::F32,
688	)?;
689	let buffers = [
690		BufferBinding::read(indices.storage()),
691		BufferBinding::write(output.storage()),
692	];
693	let push_constants = [
694		PushConstant::U32(tokens_u32),
695		PushConstant::U32(experts_u32),
696		PushConstant::U32(routes_u32),
697	];
698	let inputs = [indices];
699	let outputs = [&output];
700	let attributes = [OpAttribute::SignedInteger {
701		name: "numExperts".into(),
702		value: i64::try_from(num_experts)
703			.map_err(|_| Error::invalid_argument(format!("{operation} expert count exceeds i64")))?,
704	}];
705	indices.engine_handle().record_semantic(
706		ComputeDispatch {
707			kernel: KernelId::MatrixTopKMaskF32,
708			buffers: &buffers,
709			push_constants: &push_constants,
710			workgroups: KernelId::MatrixTopKMaskF32.linear_workgroups(output_count_u32),
711			indirect: None,
712		},
713		SemanticDispatch {
714			contract: CONTRACT,
715			inputs: &inputs,
716			outputs: &outputs,
717			attributes: &attributes,
718		},
719	)?;
720	Ok(output)
721}
722
723/// Build a stable dropless expert-major plan from I32 `[T, K]` indices.
724///
725/// Within every expert, routes preserve their original token-major order. The
726/// operation accepts at most 256 experts, matching the shader's shared state.
727///
728/// # Errors
729///
730/// Returns an error unless indices are nonempty rank-two I32, the expert count
731/// is in `1..=256`, sizes fit the admitted ABI, allocation succeeds, or runtime
732/// recording succeeds.
733pub fn moe_expert_plan(indices: &Matrix, num_experts: usize) -> Result<MoeExpertPlan> {
734	const CONTRACT: OperationContract = crate::core::operation::matrix::MOE_EXPERT_PLAN;
735	let operation = CONTRACT.name();
736	let [tokens, routes_per_token] = indices.shape() else {
737		return Err(Error::invalid_argument(format!(
738			"{operation} requires rank-two I32 indices"
739		)));
740	};
741	if indices.dtype() != DType::I32 || *tokens == 0 || *routes_per_token == 0 {
742		return Err(Error::invalid_argument(format!(
743			"{operation} requires nonempty rank-two I32 indices"
744		)));
745	}
746	if !(1..=EXPERT_LIMIT).contains(&num_experts) {
747		return Err(Error::invalid_argument(format!(
748			"{operation} expert count must be in 1..={EXPERT_LIMIT}"
749		)));
750	}
751	let route_count = tokens
752		.checked_mul(*routes_per_token)
753		.ok_or_else(|| Error::invalid_argument(format!("{operation} route count overflows usize")))?;
754	let offsets_count = num_experts
755		.checked_add(1)
756		.ok_or_else(|| Error::invalid_argument(format!("{operation} offset count overflows usize")))?;
757	let tokens_u32 = as_u32(*tokens, operation, "token count")?;
758	let routes_per_token_u32 = as_u32(*routes_per_token, operation, "routes per token")?;
759	let experts_u32 = as_u32(num_experts, operation, "expert count")?;
760	let route_count_u32 = as_u32(route_count, operation, "route count")?;
761	let engine = indices.engine_handle();
762	let counts = Matrix::allocate(engine, vec![num_experts], num_experts, DType::U32)?;
763	let offsets = Matrix::allocate(engine, vec![offsets_count], offsets_count, DType::U32)?;
764	let packed_token = Matrix::allocate(engine, vec![route_count], route_count, DType::U32)?;
765	let packed_expert = Matrix::allocate(engine, vec![route_count], route_count, DType::U32)?;
766	let packed_slot = Matrix::allocate(engine, vec![route_count], route_count, DType::U32)?;
767	let inverse = Matrix::allocate(engine, vec![route_count], route_count, DType::U32)?;
768	let buffers = [
769		BufferBinding::read(indices.storage()),
770		BufferBinding::write(counts.storage()),
771		BufferBinding::write(offsets.storage()),
772		BufferBinding::write(packed_token.storage()),
773		BufferBinding::write(packed_expert.storage()),
774		BufferBinding::write(packed_slot.storage()),
775		BufferBinding::write(inverse.storage()),
776	];
777	let push_constants = [
778		PushConstant::U32(tokens_u32),
779		PushConstant::U32(routes_per_token_u32),
780		PushConstant::U32(experts_u32),
781		PushConstant::U32(route_count_u32),
782	];
783	let inputs = [indices];
784	let outputs = [
785		&counts,
786		&offsets,
787		&packed_token,
788		&packed_expert,
789		&packed_slot,
790		&inverse,
791	];
792	let attributes = [OpAttribute::SignedInteger {
793		name: "numExperts".into(),
794		value: i64::try_from(num_experts).expect("expert limit fits i64"),
795	}];
796	engine.record_semantic(
797		ComputeDispatch {
798			kernel: KernelId::MatrixMoeExpertPlanU32,
799			buffers: &buffers,
800			push_constants: &push_constants,
801			workgroups: [1, 1, 1],
802			indirect: None,
803		},
804		SemanticDispatch {
805			contract: CONTRACT,
806			inputs: &inputs,
807			outputs: &outputs,
808			attributes: &attributes,
809		},
810	)?;
811	Ok(MoeExpertPlan {
812		counts,
813		offsets,
814		packed_token,
815		packed_expert,
816		packed_slot,
817		inverse,
818	})
819}
820
821/// Update an FP32 expert-routing bias from a dense FP32 selection mask.
822///
823/// `selection_mask` is `[T, E]`; `bias` may be `[E]` or `[1, E]`. Each expert
824/// receives `-gamma`, `+gamma`, or no update when its observed route count is
825/// above, below, or equal to the balanced target `T * K / E`. The update stays
826/// device-resident and mutates `bias` through its existing value identity.
827///
828/// # Errors
829///
830/// Returns an error unless both matrices are FP32 on the same engine, the mask
831/// and bias shapes agree, `experts_per_token` is in `1..=E`, `gamma` is finite
832/// and positive, dimensions fit the shader ABI, or runtime recording fails.
833pub fn moe_routing_bias_update(
834	selection_mask: &Matrix,
835	bias: &Matrix,
836	experts_per_token: usize,
837	gamma: f32,
838) -> Result<()> {
839	const CONTRACT: OperationContract = crate::core::operation::matrix::MOE_ROUTING_BIAS_UPDATE;
840	let operation = CONTRACT.name();
841	let [tokens, experts] = selection_mask.shape() else {
842		return Err(Error::invalid_argument(format!(
843			"{operation} requires a rank-two selection mask"
844		)));
845	};
846	if selection_mask.dtype() != DType::F32 || bias.dtype() != DType::F32 {
847		return Err(Error::invalid_argument(format!(
848			"{operation} requires an F32 selection mask and bias"
849		)));
850	}
851	if *tokens == 0 || *experts == 0 || bias.num_elements() != *experts {
852		return Err(Error::invalid_argument(format!(
853			"{operation} requires nonempty [T, E] mask and E-element bias"
854		)));
855	}
856	if !matches!(bias.shape(), [bias_experts] if bias_experts == experts)
857		&& !matches!(bias.shape(), [one, bias_experts] if *one == 1 && bias_experts == experts)
858	{
859		return Err(Error::invalid_argument(format!(
860			"{operation} bias must have shape [E] or [1, E]"
861		)));
862	}
863	if !(1..=*experts).contains(&experts_per_token) {
864		return Err(Error::invalid_argument(format!(
865			"{operation} experts_per_token must be in 1..=E"
866		)));
867	}
868	if !gamma.is_finite() || gamma <= 0.0 {
869		return Err(Error::invalid_argument(format!(
870			"{operation} gamma must be finite and positive"
871		)));
872	}
873	let engine = selection_mask.engine_handle();
874	if !engine.same_as(bias.engine_handle()) {
875		return Err(Error::invalid_argument(format!(
876			"{operation} inputs must belong to the same engine"
877		)));
878	}
879	let tokens_u32 = as_u32(*tokens, operation, "token count")?;
880	let experts_u32 = as_u32(*experts, operation, "expert count")?;
881	let experts_per_token_u32 = as_u32(experts_per_token, operation, "experts per token")?;
882	let buffers = [
883		BufferBinding::read(selection_mask.storage()),
884		BufferBinding::read_write(bias.storage()),
885	];
886	let push_constants = [
887		PushConstant::U32(tokens_u32),
888		PushConstant::U32(experts_u32),
889		PushConstant::U32(experts_per_token_u32),
890		PushConstant::F32(gamma),
891	];
892	let inputs = [selection_mask, bias];
893	let outputs = [bias];
894	let attributes = [
895		OpAttribute::SignedInteger {
896			name: "experts_per_token".into(),
897			value: i64::try_from(experts_per_token).map_err(|_| {
898				Error::invalid_argument(format!("{operation} experts_per_token exceeds i64"))
899			})?,
900		},
901		OpAttribute::Float {
902			name: "gamma".into(),
903			value: f64::from(gamma),
904		},
905	];
906	engine.record_semantic(
907		ComputeDispatch {
908			kernel: KernelId::MatrixMoeRoutingBiasUpdateF32,
909			buffers: &buffers,
910			push_constants: &push_constants,
911			workgroups: KernelId::MatrixMoeRoutingBiasUpdateF32.linear_workgroups(experts_u32),
912			indirect: None,
913		},
914		SemanticDispatch {
915			contract: CONTRACT,
916			inputs: &inputs,
917			outputs: &outputs,
918			attributes: &attributes,
919		},
920	)
921}
922
923/// Repeat every FP32 element along one matrix axis.
924///
925/// This is the direct Rust spelling of OA C++ `FnMatrix::repeatInterleave`.
926/// Rank-one through rank-four matrices are currently admitted.
927///
928/// # Errors
929///
930/// Returns an error for an unsupported rank or dtype, non-positive repeat
931/// count, invalid axis, shape/ABI overflow, allocation failure, or recording
932/// failure.
933pub fn repeat_interleave(input: &Matrix, repeats: usize, dim: i32) -> Result<Matrix> {
934	const CONTRACT: OperationContract = crate::core::operation::matrix::REPEAT_INTERLEAVE;
935	let operation = CONTRACT.name();
936	let rank = input.shape().len();
937	if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
938		return Err(Error::invalid_argument(format!(
939			"{operation} requires a rank-one through rank-four F32 matrix"
940		)));
941	}
942	if repeats == 0 {
943		return Err(Error::invalid_argument(format!(
944			"{operation} repeats must be positive"
945		)));
946	}
947	let repeats_u32 = as_u32(repeats, operation, "repeat count")?;
948	let dim = usize::try_from(dim)
949		.map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
950	if dim >= rank {
951		return Err(Error::invalid_argument(format!(
952			"{operation} dim {dim} is outside rank {rank}"
953		)));
954	}
955	let mut output_shape = input.shape().to_vec();
956	output_shape[dim] = output_shape[dim]
957		.checked_mul(repeats)
958		.ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
959	let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
960		count
961			.checked_mul(*extent)
962			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
963	})?;
964	let count = as_u32(output_count, operation, "output element count")?;
965	let output = Matrix::allocate(
966		input.engine_handle(),
967		output_shape,
968		output_count,
969		DType::F32,
970	)?;
971	if count != 0 {
972		let input_dims = shape_u32(input.shape(), operation)?;
973		let input_strides = row_major_strides_u32(input.shape(), operation)?;
974		let buffers = [
975			BufferBinding::read(input.storage()),
976			BufferBinding::write(output.storage()),
977		];
978		let mut push_constants = vec![
979			PushConstant::U32(count),
980			PushConstant::U32(repeats_u32),
981			PushConstant::U32(dim as u32),
982			PushConstant::U32(rank as u32),
983		];
984		push_constants.extend(input_dims.map(PushConstant::U32));
985		push_constants.extend(input_strides.map(PushConstant::U32));
986		let inputs = [input];
987		let outputs = [&output];
988		let attributes = [
989			OpAttribute::SignedInteger {
990				name: "repeats".into(),
991				value: i64::from(repeats_u32),
992			},
993			OpAttribute::SignedInteger {
994				name: "dim".into(),
995				value: dim as i64,
996			},
997		];
998		input.engine_handle().record_semantic(
999			ComputeDispatch {
1000				kernel: KernelId::MatrixRepeatInterleaveF32,
1001				buffers: &buffers,
1002				push_constants: &push_constants,
1003				workgroups: KernelId::MatrixRepeatInterleaveF32.linear_workgroups(count),
1004				indirect: None,
1005			},
1006			SemanticDispatch {
1007				contract: CONTRACT,
1008				inputs: &inputs,
1009				outputs: &outputs,
1010				attributes: &attributes,
1011			},
1012		)?;
1013	}
1014	autograd::record_repeat_interleave(input, &output, repeats, dim)?;
1015	Ok(output)
1016}
1017
1018pub(crate) fn repeat_interleave_backward(
1019	input_shape: &[usize],
1020	repeats: usize,
1021	dim: usize,
1022	output_gradient: &Matrix,
1023) -> Result<Matrix> {
1024	const CONTRACT: OperationContract = crate::core::operation::matrix::REPEAT_INTERLEAVE_BACKWARD;
1025	let operation = CONTRACT.name();
1026	let rank = input_shape.len();
1027	if output_gradient.dtype() != DType::F32
1028		|| !(1..=4).contains(&rank)
1029		|| repeats == 0
1030		|| dim >= rank
1031	{
1032		return Err(Error::invalid_argument(format!(
1033			"{operation} received invalid saved repeat geometry"
1034		)));
1035	}
1036	let repeats_u32 = as_u32(repeats, operation, "repeat count")?;
1037	let mut expanded_shape = input_shape.to_vec();
1038	expanded_shape[dim] = expanded_shape[dim]
1039		.checked_mul(repeats)
1040		.ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
1041	if output_gradient.shape() != expanded_shape {
1042		return Err(Error::invalid_argument(format!(
1043			"{operation} output gradient shape does not match the saved repeat"
1044		)));
1045	}
1046	let input_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1047		count
1048			.checked_mul(*extent)
1049			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1050	})?;
1051	let count = as_u32(input_count, operation, "input element count")?;
1052	let output = Matrix::allocate(
1053		output_gradient.engine_handle(),
1054		input_shape.to_vec(),
1055		input_count,
1056		DType::F32,
1057	)?;
1058	if count != 0 {
1059		let input_dims = shape_u32(input_shape, operation)?;
1060		let output_strides = row_major_strides_u32(&expanded_shape, operation)?;
1061		let buffers = [
1062			BufferBinding::read(output_gradient.storage()),
1063			BufferBinding::write(output.storage()),
1064		];
1065		let mut push_constants = vec![
1066			PushConstant::U32(count),
1067			PushConstant::U32(repeats_u32),
1068			PushConstant::U32(dim as u32),
1069			PushConstant::U32(rank as u32),
1070		];
1071		push_constants.extend(input_dims.map(PushConstant::U32));
1072		push_constants.extend(output_strides.map(PushConstant::U32));
1073		let inputs = [output_gradient];
1074		let outputs = [&output];
1075		let attributes = [
1076			OpAttribute::Shape {
1077				name: "input_shape".into(),
1078				value: input_shape.to_vec(),
1079			},
1080			OpAttribute::SignedInteger {
1081				name: "repeats".into(),
1082				value: i64::from(repeats_u32),
1083			},
1084			OpAttribute::SignedInteger {
1085				name: "dim".into(),
1086				value: dim as i64,
1087			},
1088		];
1089		output_gradient.engine_handle().record_semantic(
1090			ComputeDispatch {
1091				kernel: KernelId::MatrixRepeatInterleaveBackwardF32,
1092				buffers: &buffers,
1093				push_constants: &push_constants,
1094				workgroups: KernelId::MatrixRepeatInterleaveBackwardF32.linear_workgroups(count),
1095				indirect: None,
1096			},
1097			SemanticDispatch {
1098				contract: CONTRACT,
1099				inputs: &inputs,
1100				outputs: &outputs,
1101				attributes: &attributes,
1102			},
1103		)?;
1104	}
1105	Ok(output)
1106}
1107
1108/// Gather I32-selected elements from every row's final axis.
1109///
1110/// `input` is FP32 `[R, C]` and `indices` is I32 `[R, K]`; the result is FP32
1111/// `[R, K]`. Out-of-range indices produce zero, matching OA C++. Repeated
1112/// indices accumulate deterministically in the reverse pass.
1113///
1114/// # Errors
1115///
1116/// Returns an error unless both inputs are rank two on the same engine, row
1117/// counts agree, dtypes match the contract, the input width is positive, sizes
1118/// fit the shader ABI, allocation fails, or runtime recording fails.
1119pub fn gather_last_dim(input: &Matrix, indices: &Matrix) -> Result<Matrix> {
1120	const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER_LAST_DIM;
1121	let operation = CONTRACT.name();
1122	let [rows, input_width] = input.shape() else {
1123		return Err(Error::invalid_argument(format!(
1124			"{operation} requires rank-two F32 input"
1125		)));
1126	};
1127	let [index_rows, selected_width] = indices.shape() else {
1128		return Err(Error::invalid_argument(format!(
1129			"{operation} requires rank-two I32 indices"
1130		)));
1131	};
1132	if input.dtype() != DType::F32
1133		|| indices.dtype() != DType::I32
1134		|| rows != index_rows
1135		|| *input_width == 0
1136		|| !input.engine_handle().same_as(indices.engine_handle())
1137	{
1138		return Err(Error::invalid_argument(format!(
1139			"{operation} requires same-engine F32 [R,C] and I32 [R,K] with C > 0"
1140		)));
1141	}
1142	let output_count = rows
1143		.checked_mul(*selected_width)
1144		.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1145	let rows_u32 = as_u32(*rows, operation, "row count")?;
1146	let input_width_u32 = as_u32(*input_width, operation, "input width")?;
1147	let selected_width_u32 = as_u32(*selected_width, operation, "selected width")?;
1148	let output_count_u32 = as_u32(output_count, operation, "output element count")?;
1149	let output = Matrix::allocate(
1150		input.engine_handle(),
1151		vec![*rows, *selected_width],
1152		output_count,
1153		DType::F32,
1154	)?;
1155	if output_count_u32 != 0 {
1156		let buffers = [
1157			BufferBinding::read(input.storage()),
1158			BufferBinding::read(indices.storage()),
1159			BufferBinding::write(output.storage()),
1160		];
1161		let push_constants = [
1162			PushConstant::U32(rows_u32),
1163			PushConstant::U32(input_width_u32),
1164			PushConstant::U32(selected_width_u32),
1165		];
1166		let inputs = [input, indices];
1167		let outputs = [&output];
1168		input.engine_handle().record_semantic(
1169			ComputeDispatch {
1170				kernel: KernelId::MatrixGatherLastDimF32,
1171				buffers: &buffers,
1172				push_constants: &push_constants,
1173				workgroups: KernelId::MatrixGatherLastDimF32.linear_workgroups(output_count_u32),
1174				indirect: None,
1175			},
1176			SemanticDispatch {
1177				contract: CONTRACT,
1178				inputs: &inputs,
1179				outputs: &outputs,
1180				attributes: &[],
1181			},
1182		)?;
1183	}
1184	autograd::record_gather_last_dim(input, indices, &output, *input_width)?;
1185	Ok(output)
1186}
1187
1188pub(crate) fn gather_last_dim_backward(
1189	output_gradient: &Matrix,
1190	indices: &Matrix,
1191	input_width: usize,
1192) -> Result<Matrix> {
1193	const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER_LAST_DIM_BACKWARD;
1194	let operation = CONTRACT.name();
1195	let [rows, selected_width] = output_gradient.shape() else {
1196		return Err(Error::invalid_argument(format!(
1197			"{operation} requires rank-two F32 output gradient"
1198		)));
1199	};
1200	if output_gradient.dtype() != DType::F32
1201		|| indices.dtype() != DType::I32
1202		|| indices.shape() != output_gradient.shape()
1203		|| input_width == 0
1204		|| !output_gradient
1205			.engine_handle()
1206			.same_as(indices.engine_handle())
1207	{
1208		return Err(Error::invalid_argument(format!(
1209			"{operation} received invalid saved gather geometry"
1210		)));
1211	}
1212	let output_count = rows
1213		.checked_mul(input_width)
1214		.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1215	let rows_u32 = as_u32(*rows, operation, "row count")?;
1216	let input_width_u32 = as_u32(input_width, operation, "input width")?;
1217	let selected_width_u32 = as_u32(*selected_width, operation, "selected width")?;
1218	let output_count_u32 = as_u32(output_count, operation, "output element count")?;
1219	let output = Matrix::allocate(
1220		output_gradient.engine_handle(),
1221		vec![*rows, input_width],
1222		output_count,
1223		DType::F32,
1224	)?;
1225	if output_count_u32 != 0 {
1226		let buffers = [
1227			BufferBinding::read(output_gradient.storage()),
1228			BufferBinding::read(indices.storage()),
1229			BufferBinding::write(output.storage()),
1230		];
1231		let push_constants = [
1232			PushConstant::U32(rows_u32),
1233			PushConstant::U32(input_width_u32),
1234			PushConstant::U32(selected_width_u32),
1235		];
1236		let inputs = [output_gradient, indices];
1237		let outputs = [&output];
1238		let attributes = [OpAttribute::SignedInteger {
1239			name: "input_width".into(),
1240			value: i64::from(input_width_u32),
1241		}];
1242		output_gradient.engine_handle().record_semantic(
1243			ComputeDispatch {
1244				kernel: KernelId::MatrixGatherLastDimBackwardF32,
1245				buffers: &buffers,
1246				push_constants: &push_constants,
1247				workgroups: KernelId::MatrixGatherLastDimBackwardF32.linear_workgroups(output_count_u32),
1248				indirect: None,
1249			},
1250			SemanticDispatch {
1251				contract: CONTRACT,
1252				inputs: &inputs,
1253				outputs: &outputs,
1254				attributes: &attributes,
1255			},
1256		)?;
1257	}
1258	Ok(output)
1259}
1260
1261/// Concatenate one or more same-dtype matrices along one axis.
1262///
1263/// This is the direct Rust spelling of OA C++ `FnMatrix::concat`. One semantic
1264/// operation lowers to one copy-region dispatch per nonempty input.
1265///
1266/// # Errors
1267///
1268/// Returns an error when there are no inputs, rank is outside one through four,
1269/// dtype, engine, rank, or non-concatenated extents differ, the axis is invalid,
1270/// shape or shader-ABI arithmetic overflows, allocation fails, or recording
1271/// fails.
1272pub fn concat(inputs: &[Matrix], dim: i32) -> Result<Matrix> {
1273	const CONTRACT: OperationContract = crate::core::operation::matrix::CONCAT;
1274	let operation = CONTRACT.name();
1275	let Some(first) = inputs.first() else {
1276		return Err(Error::invalid_argument(format!(
1277			"{operation} requires at least one input"
1278		)));
1279	};
1280	let rank = first.shape().len();
1281	if !(1..=4).contains(&rank) || !matches!(first.dtype().size_bytes(), 1 | 4) {
1282		return Err(Error::invalid_argument(format!(
1283			"{operation} requires rank-one through rank-four inputs of one- or four-byte dtypes"
1284		)));
1285	}
1286	let dim = usize::try_from(dim)
1287		.map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1288	if dim >= rank {
1289		return Err(Error::invalid_argument(format!(
1290			"{operation} dim {dim} is outside rank {rank}"
1291		)));
1292	}
1293	let engine = first.engine_handle();
1294	let mut total_extent = 0_usize;
1295	let mut sizes = Vec::with_capacity(inputs.len());
1296	for input in inputs {
1297		if input.dtype() != first.dtype()
1298			|| input.shape().len() != rank
1299			|| !engine.same_as(input.engine_handle())
1300			|| input
1301				.shape()
1302				.iter()
1303				.zip(first.shape())
1304				.enumerate()
1305				.any(|(axis, (actual, expected))| axis != dim && actual != expected)
1306		{
1307			return Err(Error::invalid_argument(format!(
1308				"{operation} requires same-engine, same-dtype inputs with matching non-concatenated extents"
1309			)));
1310		}
1311		let extent = input.shape()[dim];
1312		total_extent = total_extent
1313			.checked_add(extent)
1314			.ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
1315		sizes.push(extent);
1316	}
1317	let mut output_shape = first.shape().to_vec();
1318	output_shape[dim] = total_extent;
1319	let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1320		count
1321			.checked_mul(*extent)
1322			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1323	})?;
1324	as_u32(output_count, operation, "output element count")?;
1325	i64::try_from(total_extent)
1326		.map_err(|_| Error::invalid_argument(format!("{operation} axis extent exceeds i64")))?;
1327	let output = Matrix::allocate_output(engine, output_shape.clone(), output_count, first.dtype())?;
1328
1329	let mut bindings = Vec::with_capacity(inputs.len());
1330	let mut payloads = Vec::with_capacity(inputs.len());
1331	let mut workgroups = Vec::with_capacity(inputs.len());
1332	let mut destination_start = 0_usize;
1333	for input in inputs {
1334		let count = as_u32(input.num_elements(), operation, "input element count")?;
1335		if count != 0 {
1336			bindings.push([
1337				BufferBinding::read(input.storage()),
1338				BufferBinding::write(output.storage()),
1339			]);
1340			let mut payload = region_push_constants(
1341				count,
1342				rank,
1343				dim,
1344				0,
1345				destination_start,
1346				input.shape(),
1347				&output_shape,
1348				input.shape(),
1349				operation,
1350			)?;
1351			payload.insert(5, PushConstant::U32(first.dtype().size_bytes() as u32));
1352			payloads.push(payload);
1353			workgroups.push(KernelId::MatrixConcatF32.linear_workgroups(count));
1354		}
1355		destination_start = destination_start
1356			.checked_add(input.shape()[dim])
1357			.ok_or_else(|| Error::internal("validated Concat extent overflowed"))?;
1358	}
1359	if !bindings.is_empty() {
1360		let dispatches = bindings
1361			.iter()
1362			.zip(&payloads)
1363			.zip(&workgroups)
1364			.map(|((buffers, push_constants), workgroups)| ComputeDispatch {
1365				kernel: KernelId::MatrixConcatF32,
1366				buffers,
1367				push_constants,
1368				workgroups: *workgroups,
1369				indirect: None,
1370			})
1371			.collect::<Vec<_>>();
1372		let semantic_inputs = inputs.iter().collect::<Vec<_>>();
1373		let semantic_outputs = [&output];
1374		let attributes = [OpAttribute::SignedInteger {
1375			name: "dim".into(),
1376			value: dim as i64,
1377		}];
1378		let semantic = SemanticDispatch {
1379			contract: CONTRACT,
1380			inputs: &semantic_inputs,
1381			outputs: &semantic_outputs,
1382			attributes: &attributes,
1383		};
1384		if dispatches.len() == 1 {
1385			engine.record_semantic(
1386				dispatches.into_iter().next().expect("one dispatch"),
1387				semantic,
1388			)?;
1389		} else {
1390			engine.record_split_semantic(&dispatches, semantic)?;
1391		}
1392	}
1393	if first.dtype() == DType::F32 {
1394		autograd::record_concat(inputs, &output, dim, sizes)?;
1395	}
1396	Ok(output)
1397}
1398
1399/// Materialize a swap of the last two axes of a rank-two or rank-three Matrix.
1400///
1401/// `dim0` and `dim1` accept positive or negative axes, but the current donor
1402/// contract only admits the final two axes in either order. The result owns new
1403/// storage and preserves the input dtype and batch order.
1404///
1405/// # Errors
1406///
1407/// Returns an error unless the input is rank-two or rank-three F32, the axes
1408/// select the distinct final two dimensions, all geometry fits the shader ABI,
1409/// allocation succeeds, and runtime recording succeeds.
1410pub fn transpose(input: &Matrix, dim0: i32, dim1: i32) -> Result<Matrix> {
1411	const CONTRACT: OperationContract = crate::core::operation::matrix::TRANSPOSE;
1412	let operation = CONTRACT.name();
1413	let rank = input.shape().len();
1414	if input.dtype() != DType::F32 || !(2..=3).contains(&rank) {
1415		return Err(Error::invalid_argument(format!(
1416			"{operation} requires a rank-two or rank-three F32 matrix"
1417		)));
1418	}
1419	let resolve = |dim: i32| -> Result<usize> {
1420		let rank_i32 = i32::try_from(rank)
1421			.map_err(|_| Error::invalid_argument(format!("{operation} rank exceeds i32")))?;
1422		let resolved = if dim < 0 {
1423			dim.checked_add(rank_i32).ok_or_else(|| {
1424				Error::invalid_argument(format!("{operation} axis normalization overflows i32"))
1425			})?
1426		} else {
1427			dim
1428		};
1429		usize::try_from(resolved)
1430			.ok()
1431			.filter(|axis| *axis < rank)
1432			.ok_or_else(|| {
1433				Error::invalid_argument(format!("{operation} axis {dim} is outside rank {rank}"))
1434			})
1435	};
1436	let dim0 = resolve(dim0)?;
1437	let dim1 = resolve(dim1)?;
1438	let final_axes = [rank - 2, rank - 1];
1439	if dim0 == dim1 || !final_axes.contains(&dim0) || !final_axes.contains(&dim1) {
1440		return Err(Error::invalid_argument(format!(
1441			"{operation} supports only a swap of the final two axes"
1442		)));
1443	}
1444
1445	let rows = input.shape()[rank - 2];
1446	let columns = input.shape()[rank - 1];
1447	let batch_size = if rank == 3 { input.shape()[0] } else { 1 };
1448	let mut output_shape = input.shape().to_vec();
1449	output_shape.swap(rank - 2, rank - 1);
1450	let output = Matrix::allocate(
1451		input.engine_handle(),
1452		output_shape,
1453		input.element_count(),
1454		DType::F32,
1455	)?;
1456	if batch_size != 0 && rows != 0 && columns != 0 {
1457		let batch_size = as_u32(batch_size, operation, "batch size")?;
1458		let rows = as_u32(rows, operation, "row count")?;
1459		let columns = as_u32(columns, operation, "column count")?;
1460		let buffers = [
1461			BufferBinding::read(input.storage()),
1462			BufferBinding::write(output.storage()),
1463		];
1464		let push_constants = [
1465			PushConstant::U32(batch_size),
1466			PushConstant::U32(rows),
1467			PushConstant::U32(columns),
1468		];
1469		let inputs = [input];
1470		let outputs = [&output];
1471		let attributes = [
1472			OpAttribute::SignedInteger {
1473				name: "dim0".into(),
1474				value: i64::try_from(dim0)
1475					.map_err(|_| Error::invalid_argument("transpose dim0 exceeds i64"))?,
1476			},
1477			OpAttribute::SignedInteger {
1478				name: "dim1".into(),
1479				value: i64::try_from(dim1)
1480					.map_err(|_| Error::invalid_argument("transpose dim1 exceeds i64"))?,
1481			},
1482		];
1483		input.engine_handle().record_semantic(
1484			ComputeDispatch {
1485				kernel: KernelId::MatrixTransposeF32,
1486				buffers: &buffers,
1487				push_constants: &push_constants,
1488				workgroups: [columns.div_ceil(32), rows.div_ceil(32), batch_size],
1489				indirect: None,
1490			},
1491			SemanticDispatch {
1492				contract: CONTRACT,
1493				inputs: &inputs,
1494				outputs: &outputs,
1495				attributes: &attributes,
1496			},
1497		)?;
1498	}
1499	autograd::record_transpose(input, &output, dim0, dim1)?;
1500	Ok(output)
1501}
1502
1503/// Materialize a half-open interval along one matrix axis.
1504///
1505/// This is the direct Rust spelling of OA C++ `FnMatrix::slice`. The current
1506/// checkpoint admits rank-one through rank-four FP32 matrices.
1507///
1508/// # Errors
1509///
1510/// Returns an error when the rank, dtype, axis, range, shader ABI, allocation,
1511/// or runtime recording contract is invalid.
1512pub fn slice(input: &Matrix, dim: i32, start: i64, end: i64) -> Result<Matrix> {
1513	const CONTRACT: OperationContract = crate::core::operation::matrix::SLICE;
1514	let operation = CONTRACT.name();
1515	let rank = input.shape().len();
1516	if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
1517		return Err(Error::invalid_argument(format!(
1518			"{operation} requires a rank-one through rank-four F32 matrix"
1519		)));
1520	}
1521	let dim = usize::try_from(dim)
1522		.map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1523	if dim >= rank {
1524		return Err(Error::invalid_argument(format!(
1525			"{operation} dim {dim} is outside rank {rank}"
1526		)));
1527	}
1528	let start = usize::try_from(start)
1529		.map_err(|_| Error::invalid_argument(format!("{operation} start must be nonnegative")))?;
1530	let end = usize::try_from(end)
1531		.map_err(|_| Error::invalid_argument(format!("{operation} end must be nonnegative")))?;
1532	if start >= end || end > input.shape()[dim] {
1533		return Err(Error::invalid_argument(format!(
1534			"{operation} requires 0 <= start < end <= axis extent"
1535		)));
1536	}
1537	let mut output_shape = input.shape().to_vec();
1538	output_shape[dim] = end - start;
1539	let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1540		count
1541			.checked_mul(*extent)
1542			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1543	})?;
1544	let count = as_u32(output_count, operation, "output element count")?;
1545	let output = Matrix::allocate(
1546		input.engine_handle(),
1547		output_shape.clone(),
1548		output_count,
1549		DType::F32,
1550	)?;
1551	if count != 0 {
1552		let buffers = [
1553			BufferBinding::read(input.storage()),
1554			BufferBinding::write(output.storage()),
1555		];
1556		let push_constants = region_push_constants(
1557			count,
1558			rank,
1559			dim,
1560			start,
1561			0,
1562			input.shape(),
1563			&output_shape,
1564			&output_shape,
1565			operation,
1566		)?;
1567		let inputs = [input];
1568		let outputs = [&output];
1569		let attributes = [
1570			OpAttribute::SignedInteger {
1571				name: "dim".into(),
1572				value: dim as i64,
1573			},
1574			OpAttribute::SignedInteger {
1575				name: "start".into(),
1576				value: start as i64,
1577			},
1578			OpAttribute::SignedInteger {
1579				name: "end".into(),
1580				value: end as i64,
1581			},
1582		];
1583		input.engine_handle().record_semantic(
1584			ComputeDispatch {
1585				kernel: KernelId::MatrixSliceF32,
1586				buffers: &buffers,
1587				push_constants: &push_constants,
1588				workgroups: KernelId::MatrixSliceF32.linear_workgroups(count),
1589				indirect: None,
1590			},
1591			SemanticDispatch {
1592				contract: CONTRACT,
1593				inputs: &inputs,
1594				outputs: &outputs,
1595				attributes: &attributes,
1596			},
1597		)?;
1598	}
1599	autograd::record_slice(input, &output, dim, start, end)?;
1600	Ok(output)
1601}
1602
1603pub(crate) fn slice_backward(
1604	input_shape: &[usize],
1605	dim: usize,
1606	start: usize,
1607	end: usize,
1608	output_gradient: &Matrix,
1609) -> Result<Matrix> {
1610	const CONTRACT: OperationContract = crate::core::operation::matrix::SLICE_BACKWARD;
1611	let operation = CONTRACT.name();
1612	let rank = input_shape.len();
1613	if output_gradient.dtype() != DType::F32 || !(1..=4).contains(&rank) || dim >= rank {
1614		return Err(Error::invalid_argument(format!(
1615			"{operation} requires rank-one through rank-four F32 geometry"
1616		)));
1617	}
1618	if start >= end || end > input_shape[dim] {
1619		return Err(Error::invalid_argument(format!(
1620			"{operation} received an invalid saved slice range"
1621		)));
1622	}
1623	let mut slice_shape = input_shape.to_vec();
1624	slice_shape[dim] = end - start;
1625	if output_gradient.shape() != slice_shape {
1626		return Err(Error::invalid_argument(format!(
1627			"{operation} output gradient shape does not match the saved slice"
1628		)));
1629	}
1630	let output_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1631		count
1632			.checked_mul(*extent)
1633			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1634	})?;
1635	let copy_count = as_u32(
1636		output_gradient.num_elements(),
1637		operation,
1638		"copy element count",
1639	)?;
1640	let output = Matrix::allocate(
1641		output_gradient.engine_handle(),
1642		input_shape.to_vec(),
1643		output_count,
1644		DType::F32,
1645	)?;
1646	if copy_count != 0 {
1647		let buffers = [
1648			BufferBinding::read(output_gradient.storage()),
1649			// The donor region copy leaves the initialized padding untouched.
1650			BufferBinding::read_write(output.storage()),
1651		];
1652		let push_constants = region_push_constants(
1653			copy_count,
1654			rank,
1655			dim,
1656			0,
1657			start,
1658			output_gradient.shape(),
1659			input_shape,
1660			output_gradient.shape(),
1661			operation,
1662		)?;
1663		let inputs = [output_gradient];
1664		let outputs = [&output];
1665		let attributes = [
1666			OpAttribute::Shape {
1667				name: "input_shape".into(),
1668				value: input_shape.to_vec(),
1669			},
1670			OpAttribute::SignedInteger {
1671				name: "dim".into(),
1672				value: dim as i64,
1673			},
1674			OpAttribute::SignedInteger {
1675				name: "start".into(),
1676				value: start as i64,
1677			},
1678			OpAttribute::SignedInteger {
1679				name: "end".into(),
1680				value: end as i64,
1681			},
1682		];
1683		output_gradient.engine_handle().record_semantic(
1684			ComputeDispatch {
1685				kernel: KernelId::MatrixSliceBackwardF32,
1686				buffers: &buffers,
1687				push_constants: &push_constants,
1688				workgroups: KernelId::MatrixSliceBackwardF32.linear_workgroups(copy_count),
1689				indirect: None,
1690			},
1691			SemanticDispatch {
1692				contract: CONTRACT,
1693				inputs: &inputs,
1694				outputs: &outputs,
1695				attributes: &attributes,
1696			},
1697		)?;
1698	}
1699	Ok(output)
1700}
1701
1702/// Border contract for [`pad`].
1703///
1704/// Constant fills padded elements with `fill`; the remaining modes source
1705/// padded elements from the input border. The numeric discriminants are the
1706/// kernel push-constant mode values.
1707#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1708pub enum PadMode {
1709	/// Fill padded elements with a constant value.
1710	#[default]
1711	Constant = 0,
1712	/// Clamp each padded coordinate to the nearest edge element.
1713	Replicate = 1,
1714	/// Mirror the border without repeating the edge element.
1715	Reflect = 2,
1716	/// Wrap padded coordinates around the axis extent.
1717	Circular = 3,
1718}
1719
1720/// Pad a rank-one through rank-five FP32 matrix per dimension.
1721///
1722/// `pads` holds one `[before, after]` pair per axis in input order;
1723/// `output[i] = input[i] + before_i + after_i` per axis. `fill` applies only
1724/// to [`PadMode::Constant`]. Reflect mode requires each pad amount to be
1725/// smaller than the axis extent.
1726///
1727/// # Errors
1728///
1729/// Returns an error when the rank, dtype, pad arity, reflect bound, shader
1730/// ABI, allocation, or runtime recording contract is invalid.
1731pub fn pad(input: &Matrix, pads: &[usize], mode: PadMode, fill: f32) -> Result<Matrix> {
1732	const CONTRACT: OperationContract = crate::core::operation::matrix::PAD;
1733	let operation = CONTRACT.name();
1734	let shape = input.shape();
1735	let rank = shape.len();
1736	if input.dtype() != DType::F32 || !(1..=5).contains(&rank) {
1737		return Err(Error::invalid_argument(format!(
1738			"{operation} requires a rank-one through rank-five F32 matrix"
1739		)));
1740	}
1741	if pads.len() != 2 * rank {
1742		return Err(Error::invalid_argument(format!(
1743			"{operation} requires one [before, after] pad pair per axis"
1744		)));
1745	}
1746	let mut output_shape = shape.to_vec();
1747	for (axis, extent) in output_shape.iter_mut().enumerate() {
1748		let before = pads[2 * axis];
1749		let after = pads[2 * axis + 1];
1750		if mode == PadMode::Reflect && (before >= *extent || after >= *extent) {
1751			return Err(Error::invalid_argument(format!(
1752				"{operation} reflect pads must be smaller than the axis extent"
1753			)));
1754		}
1755		*extent = extent
1756			.checked_add(before)
1757			.and_then(|extent| extent.checked_add(after))
1758			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1759	}
1760	let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1761		count
1762			.checked_mul(*extent)
1763			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1764	})?;
1765	let count = as_u32(output_count, operation, "output element count")?;
1766	let output = Matrix::allocate(
1767		input.engine_handle(),
1768		output_shape.clone(),
1769		output_count,
1770		DType::F32,
1771	)?;
1772	if count != 0 {
1773		let buffers = [
1774			BufferBinding::read(input.storage()),
1775			BufferBinding::write(output.storage()),
1776		];
1777		let push_constants = pad_push_constants(
1778			count,
1779			rank,
1780			mode,
1781			fill,
1782			&PadExtents {
1783				input: shape,
1784				output: &output_shape,
1785				pads,
1786			},
1787			true,
1788			operation,
1789		)?;
1790		let inputs = [input];
1791		let outputs = [&output];
1792		let attributes = [
1793			OpAttribute::Shape {
1794				name: "pads".into(),
1795				value: pads.to_vec(),
1796			},
1797			OpAttribute::UnsignedInteger {
1798				name: "mode".into(),
1799				value: mode as u64,
1800			},
1801			OpAttribute::Float {
1802				name: "fill".into(),
1803				value: fill as f64,
1804			},
1805		];
1806		input.engine_handle().record_semantic(
1807			ComputeDispatch {
1808				kernel: KernelId::MatrixPadF32,
1809				buffers: &buffers,
1810				push_constants: &push_constants,
1811				workgroups: KernelId::MatrixPadF32.linear_workgroups(count),
1812				indirect: None,
1813			},
1814			SemanticDispatch {
1815				contract: CONTRACT,
1816				inputs: &inputs,
1817				outputs: &outputs,
1818				attributes: &attributes,
1819			},
1820		)?;
1821	}
1822	autograd::record_pad(input, &output, pads.to_vec(), mode as usize)?;
1823	Ok(output)
1824}
1825
1826pub(crate) fn pad_backward(
1827	input_shape: &[usize],
1828	pads: &[usize],
1829	mode: usize,
1830	output_gradient: &Matrix,
1831) -> Result<Matrix> {
1832	const CONTRACT: OperationContract = crate::core::operation::matrix::PAD_BACKWARD;
1833	let operation = CONTRACT.name();
1834	let rank = input_shape.len();
1835	if output_gradient.dtype() != DType::F32 || !(1..=5).contains(&rank) || pads.len() != 2 * rank {
1836		return Err(Error::invalid_argument(format!(
1837			"{operation} requires rank-one through rank-five F32 geometry"
1838		)));
1839	}
1840	let mut expected = input_shape.to_vec();
1841	for (axis, extent) in expected.iter_mut().enumerate() {
1842		*extent += pads[2 * axis] + pads[2 * axis + 1];
1843	}
1844	if output_gradient.shape() != expected {
1845		return Err(Error::invalid_argument(format!(
1846			"{operation} output gradient shape does not match the saved pad"
1847		)));
1848	}
1849	let output_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1850		count
1851			.checked_mul(*extent)
1852			.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1853	})?;
1854	let count = as_u32(output_count, operation, "output element count")?;
1855	let output = Matrix::allocate(
1856		output_gradient.engine_handle(),
1857		input_shape.to_vec(),
1858		output_count,
1859		DType::F32,
1860	)?;
1861	if count != 0 {
1862		let pad_mode = match mode {
1863			1 => PadMode::Replicate,
1864			2 => PadMode::Reflect,
1865			3 => PadMode::Circular,
1866			_ => PadMode::Constant,
1867		};
1868		let buffers = [
1869			BufferBinding::read(output_gradient.storage()),
1870			BufferBinding::write(output.storage()),
1871		];
1872		let push_constants = pad_push_constants(
1873			count,
1874			rank,
1875			pad_mode,
1876			0.0,
1877			&PadExtents {
1878				input: input_shape,
1879				output: output_gradient.shape(),
1880				pads,
1881			},
1882			false,
1883			operation,
1884		)?;
1885		let inputs = [output_gradient];
1886		let outputs = [&output];
1887		let attributes = [
1888			OpAttribute::Shape {
1889				name: "input_shape".into(),
1890				value: input_shape.to_vec(),
1891			},
1892			OpAttribute::Shape {
1893				name: "pads".into(),
1894				value: pads.to_vec(),
1895			},
1896			OpAttribute::UnsignedInteger {
1897				name: "mode".into(),
1898				value: mode as u64,
1899			},
1900		];
1901		output_gradient.engine_handle().record_semantic(
1902			ComputeDispatch {
1903				kernel: KernelId::MatrixPadBackwardF32,
1904				buffers: &buffers,
1905				push_constants: &push_constants,
1906				workgroups: KernelId::MatrixPadBackwardF32.linear_workgroups(count),
1907				indirect: None,
1908			},
1909			SemanticDispatch {
1910				contract: CONTRACT,
1911				inputs: &inputs,
1912				outputs: &outputs,
1913				attributes: &attributes,
1914			},
1915		)?;
1916	}
1917	Ok(output)
1918}
1919
1920/// Shapes shared by the pad kernel push layout.
1921struct PadExtents<'a> {
1922	input: &'a [usize],
1923	output: &'a [usize],
1924	pads: &'a [usize],
1925}
1926
1927/// Pack the shared pad kernel push layout: count, rank, mode, optional fill
1928/// bits, five in/out extents, and five pad-before values. Resource indices
1929/// are prepended by runtime recording.
1930fn pad_push_constants(
1931	count: u32,
1932	rank: usize,
1933	mode: PadMode,
1934	fill: f32,
1935	extents: &PadExtents<'_>,
1936	forward: bool,
1937	operation: &'static str,
1938) -> Result<Vec<PushConstant>> {
1939	let mut push_constants = Vec::with_capacity(if forward { 19 } else { 18 });
1940	push_constants.push(PushConstant::U32(count));
1941	push_constants.push(PushConstant::U32(rank as u32));
1942	push_constants.push(PushConstant::U32(mode as u32));
1943	if forward {
1944		push_constants.push(PushConstant::U32(fill.to_bits()));
1945	}
1946	for shape in [extents.input, extents.output] {
1947		for axis in 0..5 {
1948			push_constants.push(PushConstant::U32(if axis < shape.len() {
1949				as_u32(shape[axis], operation, "pad extent")?
1950			} else {
1951				0
1952			}));
1953		}
1954	}
1955	for axis in 0..5 {
1956		push_constants.push(PushConstant::U32(if axis < rank {
1957			as_u32(extents.pads[2 * axis], operation, "pad before")?
1958		} else {
1959			0
1960		}));
1961	}
1962	Ok(push_constants)
1963}
1964
1965/// Split `input` along `dim` into one device-resident matrix per `sizes` entry.
1966///
1967/// Every output owns an independent copy of its `[offset, offset + size)` slice
1968/// along `dim`, matching OA C++ `FnMatrix::split`. The family records as one
1969/// variadic semantic operation whose physical lowering is one slice dispatch
1970/// per output; each output also carries a `Slice` adjoint, so reverse
1971/// differentiation flows only through the segments used downstream.
1972///
1973/// # Errors
1974///
1975/// Returns an error when `input` is not FP32 or has rank outside 1..=4, `dim`
1976/// is outside the rank, `sizes` is empty, contains a non-positive extent, or
1977/// does not sum to the `dim` extent, an output size exceeds the shader ABI,
1978/// allocation fails, or runtime recording fails.
1979pub fn split(input: &Matrix, sizes: &[i64], dim: i32) -> Result<Vec<Matrix>> {
1980	const CONTRACT: OperationContract = crate::core::operation::matrix::SPLIT;
1981	let operation = CONTRACT.name();
1982	let rank = input.shape().len();
1983	if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
1984		return Err(Error::invalid_argument(format!(
1985			"{operation} requires a rank-one through rank-four F32 matrix"
1986		)));
1987	}
1988	let dim = usize::try_from(dim)
1989		.map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1990	if dim >= rank {
1991		return Err(Error::invalid_argument(format!(
1992			"{operation} dim {dim} is outside rank {rank}"
1993		)));
1994	}
1995	if sizes.is_empty() {
1996		return Err(Error::invalid_argument(format!(
1997			"{operation} requires at least one size"
1998		)));
1999	}
2000	let mut extents = Vec::with_capacity(sizes.len());
2001	let mut total = 0usize;
2002	for &size in sizes {
2003		let extent = usize::try_from(size)
2004			.map_err(|_| Error::invalid_argument(format!("{operation} sizes must be nonnegative")))?;
2005		if extent == 0 {
2006			return Err(Error::invalid_argument(format!(
2007				"{operation} sizes must be positive"
2008			)));
2009		}
2010		total = total
2011			.checked_add(extent)
2012			.ok_or_else(|| Error::invalid_argument(format!("{operation} sizes overflow usize")))?;
2013		extents.push(extent);
2014	}
2015	if total != input.shape()[dim] {
2016		return Err(Error::invalid_argument(format!(
2017			"{operation} sizes must sum to the dim extent"
2018		)));
2019	}
2020	let engine = input.engine_handle();
2021	let lowering = engine.begin_semantic_lowering()?;
2022	let mut outputs = Vec::with_capacity(extents.len());
2023	let mut offset = 0usize;
2024	for &extent in &extents {
2025		let mut output_shape = input.shape().to_vec();
2026		output_shape[dim] = extent;
2027		let output_count = output_shape.iter().try_fold(1_usize, |count, axis| {
2028			count
2029				.checked_mul(*axis)
2030				.ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
2031		})?;
2032		let count = as_u32(output_count, operation, "output element count")?;
2033		let output = Matrix::allocate(engine, output_shape.clone(), output_count, DType::F32)?;
2034		if count != 0 {
2035			let buffers = [
2036				BufferBinding::read(input.storage()),
2037				BufferBinding::write(output.storage()),
2038			];
2039			let push_constants = region_push_constants(
2040				count,
2041				rank,
2042				dim,
2043				offset,
2044				0,
2045				input.shape(),
2046				&output_shape,
2047				&output_shape,
2048				operation,
2049			)?;
2050			lowering.record_physical(ComputeDispatch {
2051				kernel: KernelId::MatrixSliceF32,
2052				buffers: &buffers,
2053				push_constants: &push_constants,
2054				workgroups: KernelId::MatrixSliceF32.linear_workgroups(count),
2055				indirect: None,
2056			})?;
2057		}
2058		outputs.push(output);
2059		offset += extent;
2060	}
2061	let inputs = [input];
2062	let output_refs: Vec<&Matrix> = outputs.iter().collect();
2063	let attributes = [OpAttribute::SignedInteger {
2064		name: "dim".into(),
2065		value: dim as i64,
2066	}];
2067	lowering.commit(SemanticDispatch {
2068		contract: CONTRACT,
2069		inputs: &inputs,
2070		outputs: &output_refs,
2071		attributes: &attributes,
2072	})?;
2073	let mut start = 0usize;
2074	for (output, &extent) in outputs.iter().zip(&extents) {
2075		autograd::record_slice(input, output, dim, start, start + extent)?;
2076		start += extent;
2077	}
2078	Ok(outputs)
2079}
2080
2081/// Compact the selected rows of `input` on device without host readback.
2082///
2083/// `input` is `[T, D]` FP32 and `mask` is `[T]` FP32; one workgroup runs the
2084/// donor chunked prefix scan so `row_map`, `count`, and `dispatch_args` stay
2085/// device-resident, matching OA C++ `FnMatrix::compactRows`. `values` keeps
2086/// fixed `[T, D]` capacity with unselected slots zeroed.
2087///
2088/// # Errors
2089///
2090/// Returns an error when `input` is not rank-two FP32, `mask` is not FP32 with
2091/// `T` elements, an extent exceeds the shader ABI, allocation fails, or
2092/// runtime recording fails.
2093pub fn compact_rows(input: &Matrix, mask: &Matrix) -> Result<CompactRowsResult> {
2094	const CONTRACT: OperationContract = crate::core::operation::matrix::COMPACT_ROWS;
2095	let operation = CONTRACT.name();
2096	let [t, d] = input.shape() else {
2097		return Err(Error::invalid_argument(format!(
2098			"{operation} requires a rank-two [T,D] input"
2099		)));
2100	};
2101	if input.dtype() != DType::F32
2102		|| mask.dtype() != DType::F32
2103		|| mask.num_elements() != *t
2104		|| !input.engine_handle().same_as(mask.engine_handle())
2105	{
2106		return Err(Error::invalid_argument(format!(
2107			"{operation} requires an FP32 [T,D] input and same-engine FP32 [T] mask"
2108		)));
2109	}
2110	let element_count = t
2111		.checked_mul(*d)
2112		.ok_or_else(|| Error::invalid_argument(format!("{operation} element count overflows usize")))?;
2113	let engine = input.engine_handle();
2114	let values = Matrix::allocate(engine, input.shape().to_vec(), element_count, DType::F32)?;
2115	let row_map = Matrix::allocate(engine, vec![*t], *t, DType::U32)?;
2116	let t = as_u32(*t, operation, "row count")?;
2117	let d = as_u32(*d, operation, "row width")?;
2118	// Producer-side bound proof: the emitted X group count cannot be inspected
2119	// by later indirect consumers, so it must fit the device limit here.
2120	let emitted_groups = KernelId::MatrixCompactRowsF32.linear_workgroups(as_u32(
2121		element_count,
2122		operation,
2123		"element count",
2124	)?)[0];
2125	if emitted_groups > engine.max_compute_work_group_count()[0] {
2126		return Err(Error::invalid_argument(format!(
2127			"{operation} indirect group count {emitted_groups} exceeds the device limit"
2128		)));
2129	}
2130	let count = Matrix::allocate(engine, vec![1], 1, DType::U32)?;
2131	let dispatch_args = Matrix::allocate(engine, vec![3], 3, DType::U32)?;
2132	let buffers = [
2133		BufferBinding::read(input.storage()),
2134		BufferBinding::read(mask.storage()),
2135		BufferBinding::write(values.storage()),
2136		BufferBinding::write(row_map.storage()),
2137		BufferBinding::write(count.storage()),
2138		BufferBinding::write(dispatch_args.storage()),
2139	];
2140	let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2141	let inputs = [input, mask];
2142	let outputs = [&values, &row_map, &count, &dispatch_args];
2143	input.engine_handle().record_semantic(
2144		ComputeDispatch {
2145			kernel: KernelId::MatrixCompactRowsF32,
2146			buffers: &buffers,
2147			push_constants: &push_constants,
2148			workgroups: [1, 1, 1],
2149			indirect: None,
2150		},
2151		SemanticDispatch {
2152			contract: CONTRACT,
2153			inputs: &inputs,
2154			outputs: &outputs,
2155			attributes: &[],
2156		},
2157	)?;
2158	autograd::record_compact_rows(input, &values, &row_map, &count, &dispatch_args)?;
2159	Ok(CompactRowsResult {
2160		values,
2161		row_map,
2162		count,
2163		dispatch_args,
2164	})
2165}
2166
2167/// Expand a packed compact-rows gradient back to the saved `[T,D]` geometry.
2168///
2169/// With `dispatch_args` the GPU-authored group count drives a
2170/// `vkCmdDispatchIndirect` launch and selected packed rows store into their
2171/// mapped source rows; without it the direct-dispatch variant covers the full
2172/// `[T,D]` extent. Both match OA C++ `FnMatrix::compactRowsBwd`. This
2173/// numerical provider does not inspect a tape.
2174///
2175/// # Errors
2176///
2177/// Returns an error when the auxiliary inputs are not U32, shapes disagree, or
2178/// recording fails.
2179pub(crate) fn compact_rows_backward(
2180	output_gradient: &Matrix,
2181	row_map: &Matrix,
2182	count: &Matrix,
2183	dispatch_args: Option<&Matrix>,
2184	input_shape: &[usize],
2185) -> Result<Matrix> {
2186	const CONTRACT: OperationContract = crate::core::operation::matrix::COMPACT_ROWS_BACKWARD;
2187	let operation = CONTRACT.name();
2188	let [t, d] = input_shape else {
2189		return Err(Error::invalid_argument(format!(
2190			"{operation} requires a rank-two [T,D] input shape"
2191		)));
2192	};
2193	if output_gradient.dtype() != DType::F32 || output_gradient.shape() != input_shape {
2194		return Err(Error::invalid_argument(format!(
2195			"{operation} requires an FP32 [T,D] output gradient"
2196		)));
2197	}
2198	if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2199		return Err(Error::invalid_argument(format!(
2200			"{operation} requires a U32 row map with at least T entries"
2201		)));
2202	}
2203	if count.dtype() != DType::U32 || count.num_elements() != 1 {
2204		return Err(Error::invalid_argument(format!(
2205			"{operation} requires a U32 [1] count"
2206		)));
2207	}
2208	let t = as_u32(*t, operation, "row count")?;
2209	let d = as_u32(*d, operation, "row width")?;
2210	let element_count = output_gradient.num_elements();
2211	let element_count_u32 = as_u32(element_count, operation, "element count")?;
2212	let engine = output_gradient.engine_handle();
2213	let indirect = indirect_plan(
2214		dispatch_args,
2215		engine,
2216		element_count_u32,
2217		KernelId::MatrixCompactRowsBackwardIndirectF32,
2218		operation,
2219	)?;
2220	let input_gradient = Matrix::allocate(engine, input_shape.to_vec(), element_count, DType::F32)?;
2221	let direct_buffers = [
2222		BufferBinding::read(output_gradient.storage()),
2223		BufferBinding::read(row_map.storage()),
2224		BufferBinding::read(count.storage()),
2225		BufferBinding::read_write(input_gradient.storage()),
2226	];
2227	let indirect_buffers = dispatch_args.map(|dispatch_args| {
2228		[
2229			BufferBinding::read(output_gradient.storage()),
2230			BufferBinding::read(row_map.storage()),
2231			BufferBinding::read(count.storage()),
2232			BufferBinding::read(dispatch_args.storage()),
2233			BufferBinding::read_write(input_gradient.storage()),
2234		]
2235	});
2236	let (kernel, workgroups, buffers) = if let Some(indirect_buffers) = &indirect_buffers {
2237		(
2238			KernelId::MatrixCompactRowsBackwardIndirectF32,
2239			[0, 0, 0],
2240			indirect_buffers.as_slice(),
2241		)
2242	} else {
2243		(
2244			KernelId::MatrixCompactRowsBackwardF32,
2245			KernelId::MatrixCompactRowsBackwardF32.linear_workgroups(element_count_u32),
2246			direct_buffers.as_slice(),
2247		)
2248	};
2249	let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2250	let inputs = [
2251		Some(output_gradient),
2252		Some(row_map),
2253		Some(count),
2254		dispatch_args,
2255	];
2256	let outputs = [&input_gradient];
2257	let attributes = [OpAttribute::Shape {
2258		name: "inputShape".into(),
2259		value: input_shape.to_vec(),
2260	}];
2261	engine.record_optional_semantic(
2262		ComputeDispatch {
2263			kernel,
2264			buffers,
2265			push_constants: &push_constants,
2266			workgroups,
2267			indirect,
2268		},
2269		OptionalSemanticDispatch {
2270			contract: CONTRACT,
2271			inputs: &inputs,
2272			outputs: &outputs,
2273			attributes: &attributes,
2274		},
2275	)?;
2276	Ok(input_gradient)
2277}
2278
2279/// Add the compacted `source` rows into `input` at their saved positions.
2280///
2281/// Both matrices are matching `[T, D]` FP32; `row_map` and `count` are the U32
2282/// device plan from [`compact_rows`]. Each output element is `input[i]`
2283/// plus `source[packed_row, d]` when the row is selected, matching OA C++
2284/// `FnMatrix::scatterRows` in its direct-dispatch form.
2285///
2286/// # Errors
2287///
2288/// Returns an error when shapes or dtypes disagree, the auxiliary inputs are
2289/// not U32, an extent exceeds the shader ABI, or recording fails.
2290pub fn scatter_rows(
2291	input: &Matrix,
2292	source: &Matrix,
2293	row_map: &Matrix,
2294	count: &Matrix,
2295) -> Result<Matrix> {
2296	const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS;
2297	let operation = CONTRACT.name();
2298	let [t, d] = input.shape() else {
2299		return Err(Error::invalid_argument(format!(
2300			"{operation} requires a rank-two [T,D] input"
2301		)));
2302	};
2303	if input.dtype() != DType::F32 || source.shape() != input.shape() || source.dtype() != DType::F32
2304	{
2305		return Err(Error::invalid_argument(format!(
2306			"{operation} requires matching FP32 [T,D] input and source"
2307		)));
2308	}
2309	if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2310		return Err(Error::invalid_argument(format!(
2311			"{operation} requires a U32 row map with at least T entries"
2312		)));
2313	}
2314	if count.dtype() != DType::U32 || count.num_elements() != 1 {
2315		return Err(Error::invalid_argument(format!(
2316			"{operation} requires a U32 [1] count"
2317		)));
2318	}
2319	for auxiliary in [source, row_map, count] {
2320		if !auxiliary.engine_handle().same_as(input.engine_handle()) {
2321			return Err(Error::invalid_argument(format!(
2322				"{operation} inputs must share one engine"
2323			)));
2324		}
2325	}
2326	let t = as_u32(*t, operation, "row count")?;
2327	let d = as_u32(*d, operation, "row width")?;
2328	let element_count = input.num_elements();
2329	let output = Matrix::allocate(
2330		input.engine_handle(),
2331		input.shape().to_vec(),
2332		element_count,
2333		DType::F32,
2334	)?;
2335	let buffers = [
2336		BufferBinding::read(input.storage()),
2337		BufferBinding::read(source.storage()),
2338		BufferBinding::read(row_map.storage()),
2339		BufferBinding::read(count.storage()),
2340		BufferBinding::write(output.storage()),
2341	];
2342	let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2343	let inputs = [Some(input), Some(source), Some(row_map), Some(count), None];
2344	let outputs = [&output];
2345	input.engine_handle().record_optional_semantic(
2346		ComputeDispatch {
2347			kernel: KernelId::MatrixScatterRowsF32,
2348			buffers: &buffers,
2349			push_constants: &push_constants,
2350			workgroups: KernelId::MatrixScatterRowsF32.linear_workgroups(as_u32(
2351				element_count,
2352				operation,
2353				"element count",
2354			)?),
2355			indirect: None,
2356		},
2357		OptionalSemanticDispatch {
2358			contract: CONTRACT,
2359			inputs: &inputs,
2360			outputs: &outputs,
2361			attributes: &[],
2362		},
2363	)?;
2364	autograd::record_scatter_rows(input, source, &output, row_map, count, None)?;
2365	Ok(output)
2366}
2367
2368/// Add the compacted `source` rows into a copy of `input` through a
2369/// GPU-authored indirect dispatch.
2370///
2371/// `plan` is the [`CompactRowsResult`] produced by [`compact_rows`]. Every
2372/// unselected row is preserved by the initial copy and only `count * D`
2373/// selected values are touched, matching OA C++ `FnMatrix::scatterRows` in its
2374/// indirect plan-taking form.
2375///
2376/// # Errors
2377///
2378/// Returns an error when shapes or dtypes disagree, the plan does not hold a
2379/// valid U32 `[T]`/`[1]`/`[3]` triple, an extent exceeds the shader ABI or
2380/// device dispatch limit, or recording fails.
2381pub fn scatter_rows_indirect(
2382	input: &Matrix,
2383	source: &Matrix,
2384	plan: &CompactRowsResult,
2385) -> Result<Matrix> {
2386	const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS;
2387	let operation = CONTRACT.name();
2388	let [t, d] = input.shape() else {
2389		return Err(Error::invalid_argument(format!(
2390			"{operation} requires a rank-two [T,D] input"
2391		)));
2392	};
2393	if input.dtype() != DType::F32 || source.shape() != input.shape() || source.dtype() != DType::F32
2394	{
2395		return Err(Error::invalid_argument(format!(
2396			"{operation} requires matching FP32 [T,D] input and source"
2397		)));
2398	}
2399	let CompactRowsResult {
2400		row_map,
2401		count,
2402		dispatch_args,
2403		..
2404	} = plan;
2405	if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2406		return Err(Error::invalid_argument(format!(
2407			"{operation} requires a U32 row map with at least T entries"
2408		)));
2409	}
2410	if count.dtype() != DType::U32 || count.num_elements() != 1 {
2411		return Err(Error::invalid_argument(format!(
2412			"{operation} requires a U32 [1] count"
2413		)));
2414	}
2415	let engine = input.engine_handle();
2416	for auxiliary in [source, row_map, count, dispatch_args] {
2417		if !auxiliary.engine_handle().same_as(engine) {
2418			return Err(Error::invalid_argument(format!(
2419				"{operation} inputs must share one engine"
2420			)));
2421		}
2422	}
2423	let t = as_u32(*t, operation, "row count")?;
2424	let d = as_u32(*d, operation, "row width")?;
2425	let element_count_u32 = as_u32(input.num_elements(), operation, "element count")?;
2426	let indirect = indirect_plan(
2427		Some(dispatch_args),
2428		engine,
2429		element_count_u32,
2430		KernelId::MatrixScatterRowsIndirectF32,
2431		operation,
2432	)?;
2433	let scope = engine.begin_semantic_lowering()?;
2434	// Preserve every unselected row first, then touch only count*D selected
2435	// values through the GPU-authored indirect launch dimensions.
2436	let output = input.copy()?;
2437	let buffers = [
2438		BufferBinding::read(source.storage()),
2439		BufferBinding::read(row_map.storage()),
2440		BufferBinding::read(count.storage()),
2441		BufferBinding::read(dispatch_args.storage()),
2442		BufferBinding::read_write(output.storage()),
2443	];
2444	let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2445	let inputs = [
2446		Some(input),
2447		Some(source),
2448		Some(row_map),
2449		Some(count),
2450		Some(dispatch_args),
2451	];
2452	let outputs = [&output];
2453	let semantic = OptionalSemanticDispatch {
2454		contract: CONTRACT,
2455		inputs: &inputs,
2456		outputs: &outputs,
2457		attributes: &[],
2458	};
2459	semantic.validate_kernel(KernelId::MatrixScatterRowsIndirectF32)?;
2460	scope.record_physical(ComputeDispatch {
2461		kernel: KernelId::MatrixScatterRowsIndirectF32,
2462		buffers: &buffers,
2463		push_constants: &push_constants,
2464		workgroups: [0, 0, 0],
2465		indirect,
2466	})?;
2467	scope.commit_optional(semantic)?;
2468	autograd::record_scatter_rows(input, source, &output, row_map, count, Some(dispatch_args))?;
2469	Ok(output)
2470}
2471
2472/// Gather the scatter-rows output gradient into packed source geometry.
2473///
2474/// With `dispatch_args` the GPU-authored group count drives a
2475/// `vkCmdDispatchIndirect` launch; without it the direct-dispatch variant
2476/// covers the full `[T,D]` extent. Each packed row copies its mapped output
2477/// row into the zero-initialized result, matching OA C++
2478/// `FnMatrix::scatterRowsBwdSource`. This numerical provider does not inspect
2479/// a tape.
2480///
2481/// # Errors
2482///
2483/// Returns an error when the auxiliary inputs are not U32, shapes disagree, or
2484/// recording fails.
2485pub(crate) fn scatter_rows_backward_source(
2486	output_gradient: &Matrix,
2487	row_map: &Matrix,
2488	count: &Matrix,
2489	dispatch_args: Option<&Matrix>,
2490) -> Result<Matrix> {
2491	const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS_BACKWARD_SOURCE;
2492	let operation = CONTRACT.name();
2493	let [t, d] = output_gradient.shape() else {
2494		return Err(Error::invalid_argument(format!(
2495			"{operation} requires a rank-two [T,D] output gradient"
2496		)));
2497	};
2498	if output_gradient.dtype() != DType::F32 {
2499		return Err(Error::invalid_argument(format!(
2500			"{operation} requires an FP32 output gradient"
2501		)));
2502	}
2503	if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2504		return Err(Error::invalid_argument(format!(
2505			"{operation} requires a U32 row map with at least T entries"
2506		)));
2507	}
2508	if count.dtype() != DType::U32 || count.num_elements() != 1 {
2509		return Err(Error::invalid_argument(format!(
2510			"{operation} requires a U32 [1] count"
2511		)));
2512	}
2513	let t = as_u32(*t, operation, "row count")?;
2514	let d = as_u32(*d, operation, "row width")?;
2515	let element_count = output_gradient.num_elements();
2516	let element_count_u32 = as_u32(element_count, operation, "element count")?;
2517	let engine = output_gradient.engine_handle();
2518	let indirect = indirect_plan(
2519		dispatch_args,
2520		engine,
2521		element_count_u32,
2522		KernelId::MatrixScatterRowsBackwardSourceIndirectF32,
2523		operation,
2524	)?;
2525	let source_gradient = Matrix::allocate(
2526		engine,
2527		output_gradient.shape().to_vec(),
2528		element_count,
2529		DType::F32,
2530	)?;
2531	let direct_buffers = [
2532		BufferBinding::read(output_gradient.storage()),
2533		BufferBinding::read(row_map.storage()),
2534		BufferBinding::read(count.storage()),
2535		BufferBinding::write(source_gradient.storage()),
2536	];
2537	let indirect_buffers = dispatch_args.map(|dispatch_args| {
2538		[
2539			BufferBinding::read(output_gradient.storage()),
2540			BufferBinding::read(row_map.storage()),
2541			BufferBinding::read(count.storage()),
2542			BufferBinding::read(dispatch_args.storage()),
2543			BufferBinding::write(source_gradient.storage()),
2544		]
2545	});
2546	let (kernel, workgroups, buffers) = if let Some(indirect_buffers) = &indirect_buffers {
2547		(
2548			KernelId::MatrixScatterRowsBackwardSourceIndirectF32,
2549			[0, 0, 0],
2550			indirect_buffers.as_slice(),
2551		)
2552	} else {
2553		(
2554			KernelId::MatrixScatterRowsBackwardSourceF32,
2555			KernelId::MatrixScatterRowsBackwardSourceF32.linear_workgroups(element_count_u32),
2556			direct_buffers.as_slice(),
2557		)
2558	};
2559	let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2560	let inputs = [
2561		Some(output_gradient),
2562		Some(row_map),
2563		Some(count),
2564		dispatch_args,
2565	];
2566	let outputs = [&source_gradient];
2567	engine.record_optional_semantic(
2568		ComputeDispatch {
2569			kernel,
2570			buffers,
2571			push_constants: &push_constants,
2572			workgroups,
2573			indirect,
2574		},
2575		OptionalSemanticDispatch {
2576			contract: CONTRACT,
2577			inputs: &inputs,
2578			outputs: &outputs,
2579			attributes: &[],
2580		},
2581	)?;
2582	Ok(source_gradient)
2583}
2584
2585/// Reverse numerical provider for `scatter_rows` returning `(input, source)`
2586/// gradients. The base input flows through unchanged, so its gradient is the
2587/// output gradient itself rather than a redundant device copy.
2588pub(crate) fn scatter_rows_backward(
2589	output_gradient: Matrix,
2590	row_map: &Matrix,
2591	count: &Matrix,
2592	dispatch_args: Option<&Matrix>,
2593) -> Result<(Matrix, Matrix)> {
2594	let source_gradient =
2595		scatter_rows_backward_source(&output_gradient, row_map, count, dispatch_args)?;
2596	Ok((output_gradient, source_gradient))
2597}
2598
2599#[allow(
2600	clippy::too_many_arguments,
2601	reason = "the arguments preserve the donor MatrixCopyRegion ABI"
2602)]
2603fn region_push_constants(
2604	count: u32,
2605	rank: usize,
2606	dim: usize,
2607	source_start: usize,
2608	destination_start: usize,
2609	source_shape: &[usize],
2610	destination_shape: &[usize],
2611	copy_shape: &[usize],
2612	operation: &'static str,
2613) -> Result<Vec<PushConstant>> {
2614	let mut push_constants = Vec::with_capacity(17);
2615	for value in [rank, dim, source_start, destination_start] {
2616		as_u32(value, operation, "region field")?;
2617	}
2618	push_constants.push(PushConstant::U32(count));
2619	push_constants.push(PushConstant::U32(rank as u32));
2620	push_constants.push(PushConstant::U32(dim as u32));
2621	push_constants.push(PushConstant::U32(source_start as u32));
2622	push_constants.push(PushConstant::U32(destination_start as u32));
2623	for shape in [source_shape, destination_shape, copy_shape] {
2624		for axis in 0..4 {
2625			push_constants.push(PushConstant::U32(if axis < shape.len() {
2626				as_u32(shape[axis], operation, "region extent")?
2627			} else {
2628				0
2629			}));
2630		}
2631	}
2632	Ok(push_constants)
2633}
2634
2635/// Validate an optional compact-rows indirect plan and return its dispatch
2636/// descriptor.
2637///
2638/// `element_count` bounds the X group count the producer could have emitted;
2639/// the host cannot inspect the GPU-authored values, so the producer-side
2640/// limit proof is re-asserted here from the admitted `[T,D]` extent.
2641fn indirect_plan<'a>(
2642	dispatch_args: Option<&'a Matrix>,
2643	engine: &EngineHandle,
2644	element_count: u32,
2645	kernel: KernelId,
2646	operation: &'static str,
2647) -> Result<Option<IndirectDispatch<'a>>> {
2648	let Some(dispatch_args) = dispatch_args else {
2649		return Ok(None);
2650	};
2651	if dispatch_args.dtype() != DType::U32 || dispatch_args.num_elements() != 3 {
2652		return Err(Error::invalid_argument(format!(
2653			"{operation} requires a U32 [3] dispatch-args plan"
2654		)));
2655	}
2656	if !dispatch_args.engine_handle().same_as(engine) {
2657		return Err(Error::invalid_argument(format!(
2658			"{operation} inputs must share one engine"
2659		)));
2660	}
2661	let emitted_groups = kernel.linear_workgroups(element_count)[0];
2662	if emitted_groups > engine.max_compute_work_group_count()[0] {
2663		return Err(Error::invalid_argument(format!(
2664			"{operation} indirect group count {emitted_groups} exceeds the device limit"
2665		)));
2666	}
2667	Ok(Some(IndirectDispatch {
2668		storage: dispatch_args.storage(),
2669		offset: 0,
2670	}))
2671}
2672
2673fn as_u32(value: usize, operation: &'static str, label: &str) -> Result<u32> {
2674	u32::try_from(value)
2675		.map_err(|_| Error::invalid_argument(format!("{operation} {label} exceeds u32")))
2676}
2677
2678fn shape_u32(shape: &[usize], operation: &'static str) -> Result<[u32; 4]> {
2679	let mut dimensions = [0_u32; 4];
2680	for (axis, extent) in shape.iter().copied().enumerate() {
2681		dimensions[axis] = as_u32(extent, operation, "shape extent")?;
2682	}
2683	Ok(dimensions)
2684}
2685
2686fn row_major_strides_u32(shape: &[usize], operation: &'static str) -> Result<[u32; 4]> {
2687	let mut strides = [0_u32; 4];
2688	let mut stride = 1_usize;
2689	for axis in (0..shape.len()).rev() {
2690		strides[axis] = as_u32(stride, operation, "row-major stride")?;
2691		stride = stride.checked_mul(shape[axis]).ok_or_else(|| {
2692			Error::invalid_argument(format!("{operation} row-major stride overflows usize"))
2693		})?;
2694	}
2695	Ok(strides)
2696}
2697
2698/// Split a concat adjoint; empty source intervals produce no device work.
2699pub(crate) fn concat_backward(
2700	output_gradient: &Matrix,
2701	dim: usize,
2702	sizes: &[usize],
2703) -> Result<Vec<Option<Matrix>>> {
2704	let mut input_gradients = Vec::with_capacity(sizes.len());
2705	let mut start = 0_usize;
2706	for size in sizes {
2707		let end = start
2708			.checked_add(*size)
2709			.ok_or_else(|| Error::internal("saved Concat interval overflows usize"))?;
2710		if *size != 0 {
2711			let dim = i32::try_from(dim).map_err(|_| Error::internal("saved Concat axis exceeds i32"))?;
2712			let start_i64 =
2713				i64::try_from(start).map_err(|_| Error::internal("saved Concat interval exceeds i64"))?;
2714			let end_i64 =
2715				i64::try_from(end).map_err(|_| Error::internal("saved Concat interval exceeds i64"))?;
2716			let input_gradient = slice(output_gradient, dim, start_i64, end_i64)?;
2717			input_gradients.push(Some(input_gradient));
2718		} else {
2719			input_gradients.push(None);
2720		}
2721		start = end;
2722	}
2723	Ok(input_gradients)
2724}
2725
2726/// Invert the forward axis exchange for the incoming adjoint.
2727pub(crate) fn transpose_backward(
2728	output_gradient: &Matrix,
2729	dim0: usize,
2730	dim1: usize,
2731) -> Result<Matrix> {
2732	let dim0 =
2733		i32::try_from(dim0).map_err(|_| Error::internal("saved Transpose dim0 exceeds i32"))?;
2734	let dim1 =
2735		i32::try_from(dim1).map_err(|_| Error::internal("saved Transpose dim1 exceeds i32"))?;
2736	transpose(output_gradient, dim0, dim1)
2737}