1use crate::{
4 DType, Error, Matrix, OpAttribute, OperationContract, Result,
5 matrix::autograd,
6 runtime::{
7 BufferBinding, ComputeDispatch, IndirectDispatch, KernelId, OptionalSemanticDispatch,
8 PushConstant, RuntimeHandle, SemanticDispatch,
9 },
10};
11
12const TOP_K_LIMIT: usize = 1024;
13const EXPERT_LIMIT: usize = 256;
14
15pub 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.runtime().same_as(indices.runtime())
40 {
41 return Err(Error::invalid_argument(format!(
42 "{operation} requires a nonempty FP32 [rows,width] table and same-runtime 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.runtime(),
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.runtime().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.runtime().same_as(output_gradient.runtime())
108 {
109 return Err(Error::invalid_argument(format!(
110 "{operation} requires integer indices and matching FP32 [num_indices,width] gradient"
111 )));
112 }
113 let gradient = Matrix::allocate(
114 output_gradient.runtime(),
115 input_shape.to_vec(),
116 rows
117 .checked_mul(*width)
118 .ok_or_else(|| Error::invalid_argument(format!("{operation} size overflows usize")))?,
119 DType::F32,
120 )?;
121 let rows_u32 = as_u32(*rows, operation, "table row count")?;
122 let buffers = [
123 BufferBinding::read(indices.storage()),
124 BufferBinding::read(output_gradient.storage()),
125 BufferBinding::write(gradient.storage()),
126 ];
127 let push_constants = [
128 PushConstant::U32(as_u32(count, operation, "index count")?),
129 PushConstant::U32(rows_u32),
130 PushConstant::U32(as_u32(*width, operation, "table row width")?),
131 PushConstant::U32(u32::from(indices.dtype() != DType::U8)),
132 ];
133 let attributes = [OpAttribute::Shape {
134 name: "input_shape".into(),
135 value: input_shape.to_vec(),
136 }];
137 output_gradient.runtime().record_semantic(
138 ComputeDispatch {
139 kernel: KernelId::MatrixGatherBackwardF32,
140 buffers: &buffers,
141 push_constants: &push_constants,
142 workgroups: [rows_u32, 1, 1],
143 indirect: None,
144 },
145 SemanticDispatch {
146 contract: CONTRACT,
147 inputs: &[indices, output_gradient],
148 outputs: &[&gradient],
149 attributes: &attributes,
150 },
151 )?;
152 Ok(gradient)
153}
154
155#[must_use]
157pub struct TopKResult {
158 pub values: Matrix,
160 pub indices: Matrix,
162}
163
164#[must_use]
166pub struct MoeExpertPlan {
167 pub counts: Matrix,
169 pub offsets: Matrix,
171 pub packed_token: Matrix,
173 pub packed_expert: Matrix,
175 pub packed_slot: Matrix,
177 pub inverse: Matrix,
179}
180
181#[must_use]
189pub struct CompactRowsResult {
190 pub values: Matrix,
192 pub row_map: Matrix,
194 pub count: Matrix,
196 pub dispatch_args: Matrix,
198}
199
200pub fn equal(input: &Matrix, value: f32) -> Result<Matrix> {
211 const CONTRACT: OperationContract = crate::core::operation::matrix::EQUAL;
212 let operation = CONTRACT.name();
213 if input.dtype() != DType::F32 {
214 return Err(Error::invalid_argument(format!(
215 "{operation} requires an F32 input"
216 )));
217 }
218 let element_count = u32::try_from(input.element_count())
219 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
220 let output = Matrix::allocate(
221 input.runtime(),
222 input.shape().to_vec(),
223 input.element_count(),
224 DType::F32,
225 )?;
226 if element_count != 0 {
227 let buffers = [
228 BufferBinding::read(input.storage()),
229 BufferBinding::write(output.storage()),
230 ];
231 let push_constants = [PushConstant::U32(element_count), PushConstant::F32(value)];
232 let inputs = [input];
233 let outputs = [&output];
234 let attributes = [OpAttribute::Float {
235 name: "value".into(),
236 value: f64::from(value),
237 }];
238 input.runtime().record_semantic(
239 ComputeDispatch {
240 kernel: KernelId::MatrixEqualF32,
241 buffers: &buffers,
242 push_constants: &push_constants,
243 workgroups: KernelId::MatrixEqualF32.linear_workgroups(element_count),
244 indirect: None,
245 },
246 SemanticDispatch {
247 contract: CONTRACT,
248 inputs: &inputs,
249 outputs: &outputs,
250 attributes: &attributes,
251 },
252 )?;
253 }
254 Ok(output)
255}
256
257pub fn causal_mask(input: &Matrix) -> Result<Matrix> {
269 const CONTRACT: OperationContract = crate::core::operation::matrix::CAUSAL_MASK;
270 let operation = CONTRACT.name();
271 let (tq, tk) = causal_mask_axes(input, operation)?;
272 let element_count = u32::try_from(input.element_count())
273 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
274 let output = Matrix::allocate(
275 input.runtime(),
276 input.shape().to_vec(),
277 input.element_count(),
278 DType::F32,
279 )?;
280 let buffers = [
281 BufferBinding::read(input.storage()),
282 BufferBinding::write(output.storage()),
283 ];
284 let push_constants = [
285 PushConstant::U32(element_count),
286 PushConstant::U32(tq),
287 PushConstant::U32(tk),
288 ];
289 let inputs = [input];
290 let outputs = [&output];
291 input.runtime().record_semantic(
292 ComputeDispatch {
293 kernel: KernelId::MatrixCausalMaskF32,
294 buffers: &buffers,
295 push_constants: &push_constants,
296 workgroups: KernelId::MatrixCausalMaskF32.linear_workgroups(element_count),
297 indirect: None,
298 },
299 SemanticDispatch {
300 contract: CONTRACT,
301 inputs: &inputs,
302 outputs: &outputs,
303 attributes: &[],
304 },
305 )?;
306 autograd::record_causal_mask(input, &output)?;
307 Ok(output)
308}
309
310pub(crate) fn causal_mask_backward(output_gradient: &Matrix) -> Result<Matrix> {
319 const CONTRACT: OperationContract = crate::core::operation::matrix::CAUSAL_MASK_BACKWARD;
320 let operation = CONTRACT.name();
321 let (tq, tk) = causal_mask_axes(output_gradient, operation)?;
322 let element_count = u32::try_from(output_gradient.element_count())
323 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
324 let input_gradient = Matrix::allocate(
325 output_gradient.runtime(),
326 output_gradient.shape().to_vec(),
327 output_gradient.element_count(),
328 DType::F32,
329 )?;
330 let buffers = [
331 BufferBinding::read(output_gradient.storage()),
332 BufferBinding::write(input_gradient.storage()),
333 ];
334 let push_constants = [
335 PushConstant::U32(element_count),
336 PushConstant::U32(tq),
337 PushConstant::U32(tk),
338 ];
339 let inputs = [output_gradient];
340 let outputs = [&input_gradient];
341 output_gradient.runtime().record_semantic(
342 ComputeDispatch {
343 kernel: KernelId::MatrixCausalMaskBackwardF32,
344 buffers: &buffers,
345 push_constants: &push_constants,
346 workgroups: KernelId::MatrixCausalMaskBackwardF32.linear_workgroups(element_count),
347 indirect: None,
348 },
349 SemanticDispatch {
350 contract: CONTRACT,
351 inputs: &inputs,
352 outputs: &outputs,
353 attributes: &[],
354 },
355 )?;
356 Ok(input_gradient)
357}
358
359pub fn greater_equal(input: &Matrix, value: f32) -> Result<Matrix> {
370 const CONTRACT: OperationContract = crate::core::operation::matrix::GREATER_EQUAL;
371 let operation = CONTRACT.name();
372 if input.dtype() != DType::F32 {
373 return Err(Error::invalid_argument(format!(
374 "{operation} requires an F32 input"
375 )));
376 }
377 let element_count = u32::try_from(input.element_count())
378 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
379 let output = Matrix::allocate(
380 input.runtime(),
381 input.shape().to_vec(),
382 input.element_count(),
383 DType::F32,
384 )?;
385 if element_count != 0 {
386 let buffers = [
387 BufferBinding::read(input.storage()),
388 BufferBinding::write(output.storage()),
389 ];
390 let push_constants = [PushConstant::U32(element_count), PushConstant::F32(value)];
391 let inputs = [input];
392 let outputs = [&output];
393 let attributes = [OpAttribute::Float {
394 name: "value".into(),
395 value: f64::from(value),
396 }];
397 input.runtime().record_semantic(
398 ComputeDispatch {
399 kernel: KernelId::MatrixGreaterEqualF32,
400 buffers: &buffers,
401 push_constants: &push_constants,
402 workgroups: KernelId::MatrixGreaterEqualF32.linear_workgroups(element_count),
403 indirect: None,
404 },
405 SemanticDispatch {
406 contract: CONTRACT,
407 inputs: &inputs,
408 outputs: &outputs,
409 attributes: &attributes,
410 },
411 )?;
412 }
413 Ok(output)
414}
415
416pub fn cast_f32_i32(input: &Matrix) -> Result<Matrix> {
426 const CONTRACT: OperationContract = crate::core::operation::matrix::CAST_F32_I32;
427 let operation = CONTRACT.name();
428 if input.dtype() != DType::F32 {
429 return Err(Error::invalid_argument(format!(
430 "{operation} requires an F32 input"
431 )));
432 }
433 let element_count = u32::try_from(input.element_count())
434 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
435 let output = Matrix::allocate(
436 input.runtime(),
437 input.shape().to_vec(),
438 input.element_count(),
439 DType::I32,
440 )?;
441 if element_count != 0 {
442 let buffers = [
443 BufferBinding::read(input.storage()),
444 BufferBinding::write(output.storage()),
445 ];
446 let push_constants = [PushConstant::U32(element_count)];
447 let inputs = [input];
448 let outputs = [&output];
449 input.runtime().record_semantic(
450 ComputeDispatch {
451 kernel: KernelId::MatrixCastF32I32F32,
452 buffers: &buffers,
453 push_constants: &push_constants,
454 workgroups: KernelId::MatrixCastF32I32F32.linear_workgroups(element_count),
455 indirect: None,
456 },
457 SemanticDispatch {
458 contract: CONTRACT,
459 inputs: &inputs,
460 outputs: &outputs,
461 attributes: &[],
462 },
463 )?;
464 }
465 Ok(output)
466}
467
468pub fn cast_i32_f32(input: &Matrix) -> Result<Matrix> {
478 const CONTRACT: OperationContract = crate::core::operation::matrix::CAST_I32_F32;
479 let operation = CONTRACT.name();
480 if !matches!(input.dtype(), DType::I32 | DType::U32) {
481 return Err(Error::invalid_argument(format!(
482 "{operation} requires an I32 or U32 input"
483 )));
484 }
485 let element_count = u32::try_from(input.element_count())
486 .map_err(|_| Error::invalid_argument(format!("{operation} element count exceeds u32")))?;
487 let output = Matrix::allocate(
488 input.runtime(),
489 input.shape().to_vec(),
490 input.element_count(),
491 DType::F32,
492 )?;
493 if element_count != 0 {
494 let buffers = [
495 BufferBinding::read(input.storage()),
496 BufferBinding::write(output.storage()),
497 ];
498 let source_dtype = if input.dtype() == DType::I32 { 0 } else { 1 };
499 let push_constants = [
500 PushConstant::U32(element_count),
501 PushConstant::U32(source_dtype),
502 ];
503 let inputs = [input];
504 let outputs = [&output];
505 input.runtime().record_semantic(
506 ComputeDispatch {
507 kernel: KernelId::MatrixCastI32F32F32,
508 buffers: &buffers,
509 push_constants: &push_constants,
510 workgroups: KernelId::MatrixCastI32F32F32.linear_workgroups(element_count),
511 indirect: None,
512 },
513 SemanticDispatch {
514 contract: CONTRACT,
515 inputs: &inputs,
516 outputs: &outputs,
517 attributes: &[],
518 },
519 )?;
520 }
521 Ok(output)
522}
523
524fn causal_mask_axes(input: &Matrix, operation: &'static str) -> Result<(u32, u32)> {
525 if input.dtype() != DType::F32 || input.shape().len() < 2 || input.element_count() == 0 {
526 return Err(Error::invalid_argument(format!(
527 "{operation} requires a nonempty FP32 matrix with at least two axes"
528 )));
529 }
530 let tq = as_u32(
531 input.shape()[input.shape().len() - 2],
532 operation,
533 "query extent",
534 )?;
535 let tk = as_u32(
536 input.shape()[input.shape().len() - 1],
537 operation,
538 "key extent",
539 )?;
540 Ok((tq, tk))
541}
542
543pub fn top_k(input: &Matrix, k: i32, dim: i32) -> Result<TopKResult> {
555 const CONTRACT: OperationContract = crate::core::operation::matrix::TOP_K;
556 let operation = CONTRACT.name();
557 if input.dtype() != DType::F32 || !(1..=2).contains(&input.shape().len()) {
558 return Err(Error::invalid_argument(format!(
559 "{operation} requires a rank-one or rank-two F32 matrix"
560 )));
561 }
562 let last_dim = i32::try_from(input.shape().len() - 1)
563 .map_err(|_| Error::invalid_argument(format!("{operation} rank exceeds i32")))?;
564 if dim != -1 && dim != last_dim {
565 return Err(Error::invalid_argument(format!(
566 "{operation} supports only the last axis; found dim {dim}"
567 )));
568 }
569 let requested = usize::try_from(k)
570 .map_err(|_| Error::invalid_argument(format!("{operation} k must be nonnegative")))?;
571 let row_width = *input.shape().last().expect("validated nonempty rank");
572 if row_width == 0 {
573 return Err(Error::invalid_argument(format!(
574 "{operation} requires a nonempty last axis"
575 )));
576 }
577 let selected = requested.min(row_width);
578 if selected > TOP_K_LIMIT {
579 return Err(Error::invalid_argument(format!(
580 "{operation} supports at most {TOP_K_LIMIT} selected values"
581 )));
582 }
583 let rows = if input.shape().len() == 1 {
584 1
585 } else {
586 input.shape()[0]
587 };
588 let output_count = rows
589 .checked_mul(selected)
590 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
591 let mut output_shape = input.shape().to_vec();
592 *output_shape.last_mut().expect("validated nonempty rank") = selected;
593 let values = Matrix::allocate(
594 input.runtime(),
595 output_shape.clone(),
596 output_count,
597 DType::F32,
598 )?;
599 let indices = Matrix::allocate(input.runtime(), output_shape, output_count, DType::I32)?;
600 if selected != 0 && rows != 0 {
601 let rows = as_u32(rows, operation, "row count")?;
602 let row_width = as_u32(row_width, operation, "last-axis extent")?;
603 let selected = as_u32(selected, operation, "k")?;
604 let buffers = [
605 BufferBinding::read(input.storage()),
606 BufferBinding::write(values.storage()),
607 BufferBinding::write(indices.storage()),
608 ];
609 let push_constants = [
610 PushConstant::U32(rows),
611 PushConstant::U32(row_width),
612 PushConstant::U32(selected),
613 ];
614 let inputs = [input];
615 let outputs = [&values, &indices];
616 let attributes = [
617 OpAttribute::SignedInteger {
618 name: "k".into(),
619 value: i64::from(k),
620 },
621 OpAttribute::SignedInteger {
622 name: "dim".into(),
623 value: i64::from(dim),
624 },
625 ];
626 input.runtime().record_semantic(
627 ComputeDispatch {
628 kernel: KernelId::MatrixTopKF32,
629 buffers: &buffers,
630 push_constants: &push_constants,
631 workgroups: [rows, 1, 1],
632 indirect: None,
633 },
634 SemanticDispatch {
635 contract: CONTRACT,
636 inputs: &inputs,
637 outputs: &outputs,
638 attributes: &attributes,
639 },
640 )?;
641 }
642 Ok(TopKResult { values, indices })
643}
644
645pub fn top_k_mask(indices: &Matrix, num_experts: usize) -> Result<Matrix> {
652 const CONTRACT: OperationContract = crate::core::operation::matrix::TOP_K_MASK;
653 let operation = CONTRACT.name();
654 let [tokens, routes_per_token] = indices.shape() else {
655 return Err(Error::invalid_argument(format!(
656 "{operation} requires rank-two I32 indices"
657 )));
658 };
659 if indices.dtype() != DType::I32 || *tokens == 0 || *routes_per_token == 0 {
660 return Err(Error::invalid_argument(format!(
661 "{operation} requires nonempty rank-two I32 indices"
662 )));
663 }
664 if num_experts == 0 {
665 return Err(Error::invalid_argument(format!(
666 "{operation} requires at least one expert"
667 )));
668 }
669 let output_count = tokens
670 .checked_mul(num_experts)
671 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
672 let tokens_u32 = as_u32(*tokens, operation, "token count")?;
673 let experts_u32 = as_u32(num_experts, operation, "expert count")?;
674 let routes_u32 = as_u32(*routes_per_token, operation, "routes per token")?;
675 let output_count_u32 = as_u32(output_count, operation, "output element count")?;
676 let output = Matrix::allocate(
677 indices.runtime(),
678 vec![*tokens, num_experts],
679 output_count,
680 DType::F32,
681 )?;
682 let buffers = [
683 BufferBinding::read(indices.storage()),
684 BufferBinding::write(output.storage()),
685 ];
686 let push_constants = [
687 PushConstant::U32(tokens_u32),
688 PushConstant::U32(experts_u32),
689 PushConstant::U32(routes_u32),
690 ];
691 let inputs = [indices];
692 let outputs = [&output];
693 let attributes = [OpAttribute::SignedInteger {
694 name: "numExperts".into(),
695 value: i64::try_from(num_experts)
696 .map_err(|_| Error::invalid_argument(format!("{operation} expert count exceeds i64")))?,
697 }];
698 indices.runtime().record_semantic(
699 ComputeDispatch {
700 kernel: KernelId::MatrixTopKMaskF32,
701 buffers: &buffers,
702 push_constants: &push_constants,
703 workgroups: KernelId::MatrixTopKMaskF32.linear_workgroups(output_count_u32),
704 indirect: None,
705 },
706 SemanticDispatch {
707 contract: CONTRACT,
708 inputs: &inputs,
709 outputs: &outputs,
710 attributes: &attributes,
711 },
712 )?;
713 Ok(output)
714}
715
716pub fn moe_expert_plan(indices: &Matrix, num_experts: usize) -> Result<MoeExpertPlan> {
727 const CONTRACT: OperationContract = crate::core::operation::matrix::MOE_EXPERT_PLAN;
728 let operation = CONTRACT.name();
729 let [tokens, routes_per_token] = indices.shape() else {
730 return Err(Error::invalid_argument(format!(
731 "{operation} requires rank-two I32 indices"
732 )));
733 };
734 if indices.dtype() != DType::I32 || *tokens == 0 || *routes_per_token == 0 {
735 return Err(Error::invalid_argument(format!(
736 "{operation} requires nonempty rank-two I32 indices"
737 )));
738 }
739 if !(1..=EXPERT_LIMIT).contains(&num_experts) {
740 return Err(Error::invalid_argument(format!(
741 "{operation} expert count must be in 1..={EXPERT_LIMIT}"
742 )));
743 }
744 let route_count = tokens
745 .checked_mul(*routes_per_token)
746 .ok_or_else(|| Error::invalid_argument(format!("{operation} route count overflows usize")))?;
747 let offsets_count = num_experts
748 .checked_add(1)
749 .ok_or_else(|| Error::invalid_argument(format!("{operation} offset count overflows usize")))?;
750 let tokens_u32 = as_u32(*tokens, operation, "token count")?;
751 let routes_per_token_u32 = as_u32(*routes_per_token, operation, "routes per token")?;
752 let experts_u32 = as_u32(num_experts, operation, "expert count")?;
753 let route_count_u32 = as_u32(route_count, operation, "route count")?;
754 let runtime = indices.runtime();
755 let counts = Matrix::allocate(runtime, vec![num_experts], num_experts, DType::U32)?;
756 let offsets = Matrix::allocate(runtime, vec![offsets_count], offsets_count, DType::U32)?;
757 let packed_token = Matrix::allocate(runtime, vec![route_count], route_count, DType::U32)?;
758 let packed_expert = Matrix::allocate(runtime, vec![route_count], route_count, DType::U32)?;
759 let packed_slot = Matrix::allocate(runtime, vec![route_count], route_count, DType::U32)?;
760 let inverse = Matrix::allocate(runtime, vec![route_count], route_count, DType::U32)?;
761 let buffers = [
762 BufferBinding::read(indices.storage()),
763 BufferBinding::write(counts.storage()),
764 BufferBinding::write(offsets.storage()),
765 BufferBinding::write(packed_token.storage()),
766 BufferBinding::write(packed_expert.storage()),
767 BufferBinding::write(packed_slot.storage()),
768 BufferBinding::write(inverse.storage()),
769 ];
770 let push_constants = [
771 PushConstant::U32(tokens_u32),
772 PushConstant::U32(routes_per_token_u32),
773 PushConstant::U32(experts_u32),
774 PushConstant::U32(route_count_u32),
775 ];
776 let inputs = [indices];
777 let outputs = [
778 &counts,
779 &offsets,
780 &packed_token,
781 &packed_expert,
782 &packed_slot,
783 &inverse,
784 ];
785 let attributes = [OpAttribute::SignedInteger {
786 name: "numExperts".into(),
787 value: i64::try_from(num_experts).expect("expert limit fits i64"),
788 }];
789 runtime.record_semantic(
790 ComputeDispatch {
791 kernel: KernelId::MatrixMoeExpertPlanU32,
792 buffers: &buffers,
793 push_constants: &push_constants,
794 workgroups: [1, 1, 1],
795 indirect: None,
796 },
797 SemanticDispatch {
798 contract: CONTRACT,
799 inputs: &inputs,
800 outputs: &outputs,
801 attributes: &attributes,
802 },
803 )?;
804 Ok(MoeExpertPlan {
805 counts,
806 offsets,
807 packed_token,
808 packed_expert,
809 packed_slot,
810 inverse,
811 })
812}
813
814pub fn moe_routing_bias_update(
827 selection_mask: &Matrix,
828 bias: &Matrix,
829 experts_per_token: usize,
830 gamma: f32,
831) -> Result<()> {
832 const CONTRACT: OperationContract = crate::core::operation::matrix::MOE_ROUTING_BIAS_UPDATE;
833 let operation = CONTRACT.name();
834 let [tokens, experts] = selection_mask.shape() else {
835 return Err(Error::invalid_argument(format!(
836 "{operation} requires a rank-two selection mask"
837 )));
838 };
839 if selection_mask.dtype() != DType::F32 || bias.dtype() != DType::F32 {
840 return Err(Error::invalid_argument(format!(
841 "{operation} requires an F32 selection mask and bias"
842 )));
843 }
844 if *tokens == 0 || *experts == 0 || bias.num_elements() != *experts {
845 return Err(Error::invalid_argument(format!(
846 "{operation} requires nonempty [T, E] mask and E-element bias"
847 )));
848 }
849 if !matches!(bias.shape(), [bias_experts] if bias_experts == experts)
850 && !matches!(bias.shape(), [one, bias_experts] if *one == 1 && bias_experts == experts)
851 {
852 return Err(Error::invalid_argument(format!(
853 "{operation} bias must have shape [E] or [1, E]"
854 )));
855 }
856 if !(1..=*experts).contains(&experts_per_token) {
857 return Err(Error::invalid_argument(format!(
858 "{operation} experts_per_token must be in 1..=E"
859 )));
860 }
861 if !gamma.is_finite() || gamma <= 0.0 {
862 return Err(Error::invalid_argument(format!(
863 "{operation} gamma must be finite and positive"
864 )));
865 }
866 let runtime = selection_mask.runtime();
867 if !runtime.same_as(bias.runtime()) {
868 return Err(Error::invalid_argument(format!(
869 "{operation} inputs must belong to the same runtime"
870 )));
871 }
872 let tokens_u32 = as_u32(*tokens, operation, "token count")?;
873 let experts_u32 = as_u32(*experts, operation, "expert count")?;
874 let experts_per_token_u32 = as_u32(experts_per_token, operation, "experts per token")?;
875 let buffers = [
876 BufferBinding::read(selection_mask.storage()),
877 BufferBinding::read_write(bias.storage()),
878 ];
879 let push_constants = [
880 PushConstant::U32(tokens_u32),
881 PushConstant::U32(experts_u32),
882 PushConstant::U32(experts_per_token_u32),
883 PushConstant::F32(gamma),
884 ];
885 let inputs = [selection_mask, bias];
886 let outputs = [bias];
887 let attributes = [
888 OpAttribute::SignedInteger {
889 name: "experts_per_token".into(),
890 value: i64::try_from(experts_per_token).map_err(|_| {
891 Error::invalid_argument(format!("{operation} experts_per_token exceeds i64"))
892 })?,
893 },
894 OpAttribute::Float {
895 name: "gamma".into(),
896 value: f64::from(gamma),
897 },
898 ];
899 runtime.record_semantic(
900 ComputeDispatch {
901 kernel: KernelId::MatrixMoeRoutingBiasUpdateF32,
902 buffers: &buffers,
903 push_constants: &push_constants,
904 workgroups: KernelId::MatrixMoeRoutingBiasUpdateF32.linear_workgroups(experts_u32),
905 indirect: None,
906 },
907 SemanticDispatch {
908 contract: CONTRACT,
909 inputs: &inputs,
910 outputs: &outputs,
911 attributes: &attributes,
912 },
913 )
914}
915
916pub fn repeat_interleave(input: &Matrix, repeats: usize, dim: i32) -> Result<Matrix> {
927 const CONTRACT: OperationContract = crate::core::operation::matrix::REPEAT_INTERLEAVE;
928 let operation = CONTRACT.name();
929 let rank = input.shape().len();
930 if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
931 return Err(Error::invalid_argument(format!(
932 "{operation} requires a rank-one through rank-four F32 matrix"
933 )));
934 }
935 if repeats == 0 {
936 return Err(Error::invalid_argument(format!(
937 "{operation} repeats must be positive"
938 )));
939 }
940 let repeats_u32 = as_u32(repeats, operation, "repeat count")?;
941 let dim = usize::try_from(dim)
942 .map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
943 if dim >= rank {
944 return Err(Error::invalid_argument(format!(
945 "{operation} dim {dim} is outside rank {rank}"
946 )));
947 }
948 let mut output_shape = input.shape().to_vec();
949 output_shape[dim] = output_shape[dim]
950 .checked_mul(repeats)
951 .ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
952 let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
953 count
954 .checked_mul(*extent)
955 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
956 })?;
957 let count = as_u32(output_count, operation, "output element count")?;
958 let output = Matrix::allocate(input.runtime(), output_shape, output_count, DType::F32)?;
959 if count != 0 {
960 let input_dims = shape_u32(input.shape(), operation)?;
961 let input_strides = row_major_strides_u32(input.shape(), operation)?;
962 let buffers = [
963 BufferBinding::read(input.storage()),
964 BufferBinding::write(output.storage()),
965 ];
966 let mut push_constants = vec![
967 PushConstant::U32(count),
968 PushConstant::U32(repeats_u32),
969 PushConstant::U32(dim as u32),
970 PushConstant::U32(rank as u32),
971 ];
972 push_constants.extend(input_dims.map(PushConstant::U32));
973 push_constants.extend(input_strides.map(PushConstant::U32));
974 let inputs = [input];
975 let outputs = [&output];
976 let attributes = [
977 OpAttribute::SignedInteger {
978 name: "repeats".into(),
979 value: i64::from(repeats_u32),
980 },
981 OpAttribute::SignedInteger {
982 name: "dim".into(),
983 value: dim as i64,
984 },
985 ];
986 input.runtime().record_semantic(
987 ComputeDispatch {
988 kernel: KernelId::MatrixRepeatInterleaveF32,
989 buffers: &buffers,
990 push_constants: &push_constants,
991 workgroups: KernelId::MatrixRepeatInterleaveF32.linear_workgroups(count),
992 indirect: None,
993 },
994 SemanticDispatch {
995 contract: CONTRACT,
996 inputs: &inputs,
997 outputs: &outputs,
998 attributes: &attributes,
999 },
1000 )?;
1001 }
1002 autograd::record_repeat_interleave(input, &output, repeats, dim)?;
1003 Ok(output)
1004}
1005
1006pub(crate) fn repeat_interleave_backward(
1007 input_shape: &[usize],
1008 repeats: usize,
1009 dim: usize,
1010 output_gradient: &Matrix,
1011) -> Result<Matrix> {
1012 const CONTRACT: OperationContract = crate::core::operation::matrix::REPEAT_INTERLEAVE_BACKWARD;
1013 let operation = CONTRACT.name();
1014 let rank = input_shape.len();
1015 if output_gradient.dtype() != DType::F32
1016 || !(1..=4).contains(&rank)
1017 || repeats == 0
1018 || dim >= rank
1019 {
1020 return Err(Error::invalid_argument(format!(
1021 "{operation} received invalid saved repeat geometry"
1022 )));
1023 }
1024 let repeats_u32 = as_u32(repeats, operation, "repeat count")?;
1025 let mut expanded_shape = input_shape.to_vec();
1026 expanded_shape[dim] = expanded_shape[dim]
1027 .checked_mul(repeats)
1028 .ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
1029 if output_gradient.shape() != expanded_shape {
1030 return Err(Error::invalid_argument(format!(
1031 "{operation} output gradient shape does not match the saved repeat"
1032 )));
1033 }
1034 let input_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1035 count
1036 .checked_mul(*extent)
1037 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1038 })?;
1039 let count = as_u32(input_count, operation, "input element count")?;
1040 let output = Matrix::allocate(
1041 output_gradient.runtime(),
1042 input_shape.to_vec(),
1043 input_count,
1044 DType::F32,
1045 )?;
1046 if count != 0 {
1047 let input_dims = shape_u32(input_shape, operation)?;
1048 let output_strides = row_major_strides_u32(&expanded_shape, operation)?;
1049 let buffers = [
1050 BufferBinding::read(output_gradient.storage()),
1051 BufferBinding::write(output.storage()),
1052 ];
1053 let mut push_constants = vec![
1054 PushConstant::U32(count),
1055 PushConstant::U32(repeats_u32),
1056 PushConstant::U32(dim as u32),
1057 PushConstant::U32(rank as u32),
1058 ];
1059 push_constants.extend(input_dims.map(PushConstant::U32));
1060 push_constants.extend(output_strides.map(PushConstant::U32));
1061 let inputs = [output_gradient];
1062 let outputs = [&output];
1063 let attributes = [
1064 OpAttribute::Shape {
1065 name: "input_shape".into(),
1066 value: input_shape.to_vec(),
1067 },
1068 OpAttribute::SignedInteger {
1069 name: "repeats".into(),
1070 value: i64::from(repeats_u32),
1071 },
1072 OpAttribute::SignedInteger {
1073 name: "dim".into(),
1074 value: dim as i64,
1075 },
1076 ];
1077 output_gradient.runtime().record_semantic(
1078 ComputeDispatch {
1079 kernel: KernelId::MatrixRepeatInterleaveBackwardF32,
1080 buffers: &buffers,
1081 push_constants: &push_constants,
1082 workgroups: KernelId::MatrixRepeatInterleaveBackwardF32.linear_workgroups(count),
1083 indirect: None,
1084 },
1085 SemanticDispatch {
1086 contract: CONTRACT,
1087 inputs: &inputs,
1088 outputs: &outputs,
1089 attributes: &attributes,
1090 },
1091 )?;
1092 }
1093 Ok(output)
1094}
1095
1096pub fn gather_last_dim(input: &Matrix, indices: &Matrix) -> Result<Matrix> {
1108 const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER_LAST_DIM;
1109 let operation = CONTRACT.name();
1110 let [rows, input_width] = input.shape() else {
1111 return Err(Error::invalid_argument(format!(
1112 "{operation} requires rank-two F32 input"
1113 )));
1114 };
1115 let [index_rows, selected_width] = indices.shape() else {
1116 return Err(Error::invalid_argument(format!(
1117 "{operation} requires rank-two I32 indices"
1118 )));
1119 };
1120 if input.dtype() != DType::F32
1121 || indices.dtype() != DType::I32
1122 || rows != index_rows
1123 || *input_width == 0
1124 || !input.runtime().same_as(indices.runtime())
1125 {
1126 return Err(Error::invalid_argument(format!(
1127 "{operation} requires same-runtime F32 [R,C] and I32 [R,K] with C > 0"
1128 )));
1129 }
1130 let output_count = rows
1131 .checked_mul(*selected_width)
1132 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1133 let rows_u32 = as_u32(*rows, operation, "row count")?;
1134 let input_width_u32 = as_u32(*input_width, operation, "input width")?;
1135 let selected_width_u32 = as_u32(*selected_width, operation, "selected width")?;
1136 let output_count_u32 = as_u32(output_count, operation, "output element count")?;
1137 let output = Matrix::allocate(
1138 input.runtime(),
1139 vec![*rows, *selected_width],
1140 output_count,
1141 DType::F32,
1142 )?;
1143 if output_count_u32 != 0 {
1144 let buffers = [
1145 BufferBinding::read(input.storage()),
1146 BufferBinding::read(indices.storage()),
1147 BufferBinding::write(output.storage()),
1148 ];
1149 let push_constants = [
1150 PushConstant::U32(rows_u32),
1151 PushConstant::U32(input_width_u32),
1152 PushConstant::U32(selected_width_u32),
1153 ];
1154 let inputs = [input, indices];
1155 let outputs = [&output];
1156 input.runtime().record_semantic(
1157 ComputeDispatch {
1158 kernel: KernelId::MatrixGatherLastDimF32,
1159 buffers: &buffers,
1160 push_constants: &push_constants,
1161 workgroups: KernelId::MatrixGatherLastDimF32.linear_workgroups(output_count_u32),
1162 indirect: None,
1163 },
1164 SemanticDispatch {
1165 contract: CONTRACT,
1166 inputs: &inputs,
1167 outputs: &outputs,
1168 attributes: &[],
1169 },
1170 )?;
1171 }
1172 autograd::record_gather_last_dim(input, indices, &output, *input_width)?;
1173 Ok(output)
1174}
1175
1176pub(crate) fn gather_last_dim_backward(
1177 output_gradient: &Matrix,
1178 indices: &Matrix,
1179 input_width: usize,
1180) -> Result<Matrix> {
1181 const CONTRACT: OperationContract = crate::core::operation::matrix::GATHER_LAST_DIM_BACKWARD;
1182 let operation = CONTRACT.name();
1183 let [rows, selected_width] = output_gradient.shape() else {
1184 return Err(Error::invalid_argument(format!(
1185 "{operation} requires rank-two F32 output gradient"
1186 )));
1187 };
1188 if output_gradient.dtype() != DType::F32
1189 || indices.dtype() != DType::I32
1190 || indices.shape() != output_gradient.shape()
1191 || input_width == 0
1192 || !output_gradient.runtime().same_as(indices.runtime())
1193 {
1194 return Err(Error::invalid_argument(format!(
1195 "{operation} received invalid saved gather geometry"
1196 )));
1197 }
1198 let output_count = rows
1199 .checked_mul(input_width)
1200 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1201 let rows_u32 = as_u32(*rows, operation, "row count")?;
1202 let input_width_u32 = as_u32(input_width, operation, "input width")?;
1203 let selected_width_u32 = as_u32(*selected_width, operation, "selected width")?;
1204 let output_count_u32 = as_u32(output_count, operation, "output element count")?;
1205 let output = Matrix::allocate(
1206 output_gradient.runtime(),
1207 vec![*rows, input_width],
1208 output_count,
1209 DType::F32,
1210 )?;
1211 if output_count_u32 != 0 {
1212 let buffers = [
1213 BufferBinding::read(output_gradient.storage()),
1214 BufferBinding::read(indices.storage()),
1215 BufferBinding::write(output.storage()),
1216 ];
1217 let push_constants = [
1218 PushConstant::U32(rows_u32),
1219 PushConstant::U32(input_width_u32),
1220 PushConstant::U32(selected_width_u32),
1221 ];
1222 let inputs = [output_gradient, indices];
1223 let outputs = [&output];
1224 let attributes = [OpAttribute::SignedInteger {
1225 name: "input_width".into(),
1226 value: i64::from(input_width_u32),
1227 }];
1228 output_gradient.runtime().record_semantic(
1229 ComputeDispatch {
1230 kernel: KernelId::MatrixGatherLastDimBackwardF32,
1231 buffers: &buffers,
1232 push_constants: &push_constants,
1233 workgroups: KernelId::MatrixGatherLastDimBackwardF32.linear_workgroups(output_count_u32),
1234 indirect: None,
1235 },
1236 SemanticDispatch {
1237 contract: CONTRACT,
1238 inputs: &inputs,
1239 outputs: &outputs,
1240 attributes: &attributes,
1241 },
1242 )?;
1243 }
1244 Ok(output)
1245}
1246
1247pub fn concat(inputs: &[Matrix], dim: i32) -> Result<Matrix> {
1259 const CONTRACT: OperationContract = crate::core::operation::matrix::CONCAT;
1260 let operation = CONTRACT.name();
1261 let Some(first) = inputs.first() else {
1262 return Err(Error::invalid_argument(format!(
1263 "{operation} requires at least one input"
1264 )));
1265 };
1266 let rank = first.shape().len();
1267 if !(1..=4).contains(&rank) || !matches!(first.dtype().size_bytes(), 1 | 4) {
1268 return Err(Error::invalid_argument(format!(
1269 "{operation} requires rank-one through rank-four inputs of one- or four-byte dtypes"
1270 )));
1271 }
1272 let dim = usize::try_from(dim)
1273 .map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1274 if dim >= rank {
1275 return Err(Error::invalid_argument(format!(
1276 "{operation} dim {dim} is outside rank {rank}"
1277 )));
1278 }
1279 let runtime = first.runtime();
1280 let mut total_extent = 0_usize;
1281 let mut sizes = Vec::with_capacity(inputs.len());
1282 for input in inputs {
1283 if input.dtype() != first.dtype()
1284 || input.shape().len() != rank
1285 || !runtime.same_as(input.runtime())
1286 || input
1287 .shape()
1288 .iter()
1289 .zip(first.shape())
1290 .enumerate()
1291 .any(|(axis, (actual, expected))| axis != dim && actual != expected)
1292 {
1293 return Err(Error::invalid_argument(format!(
1294 "{operation} requires same-runtime, same-dtype inputs with matching non-concatenated extents"
1295 )));
1296 }
1297 let extent = input.shape()[dim];
1298 total_extent = total_extent
1299 .checked_add(extent)
1300 .ok_or_else(|| Error::invalid_argument(format!("{operation} shape overflows usize")))?;
1301 sizes.push(extent);
1302 }
1303 let mut output_shape = first.shape().to_vec();
1304 output_shape[dim] = total_extent;
1305 let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1306 count
1307 .checked_mul(*extent)
1308 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1309 })?;
1310 as_u32(output_count, operation, "output element count")?;
1311 i64::try_from(total_extent)
1312 .map_err(|_| Error::invalid_argument(format!("{operation} axis extent exceeds i64")))?;
1313 let output = Matrix::allocate_output(runtime, output_shape.clone(), output_count, first.dtype())?;
1314
1315 let mut bindings = Vec::with_capacity(inputs.len());
1316 let mut payloads = Vec::with_capacity(inputs.len());
1317 let mut workgroups = Vec::with_capacity(inputs.len());
1318 let mut destination_start = 0_usize;
1319 for input in inputs {
1320 let count = as_u32(input.num_elements(), operation, "input element count")?;
1321 if count != 0 {
1322 bindings.push([
1323 BufferBinding::read(input.storage()),
1324 BufferBinding::write(output.storage()),
1325 ]);
1326 let mut payload = region_push_constants(
1327 count,
1328 rank,
1329 dim,
1330 0,
1331 destination_start,
1332 input.shape(),
1333 &output_shape,
1334 input.shape(),
1335 operation,
1336 )?;
1337 payload.insert(5, PushConstant::U32(first.dtype().size_bytes() as u32));
1338 payloads.push(payload);
1339 workgroups.push(KernelId::MatrixConcatF32.linear_workgroups(count));
1340 }
1341 destination_start = destination_start
1342 .checked_add(input.shape()[dim])
1343 .ok_or_else(|| Error::internal("validated Concat extent overflowed"))?;
1344 }
1345 if !bindings.is_empty() {
1346 let dispatches = bindings
1347 .iter()
1348 .zip(&payloads)
1349 .zip(&workgroups)
1350 .map(|((buffers, push_constants), workgroups)| ComputeDispatch {
1351 kernel: KernelId::MatrixConcatF32,
1352 buffers,
1353 push_constants,
1354 workgroups: *workgroups,
1355 indirect: None,
1356 })
1357 .collect::<Vec<_>>();
1358 let semantic_inputs = inputs.iter().collect::<Vec<_>>();
1359 let semantic_outputs = [&output];
1360 let attributes = [OpAttribute::SignedInteger {
1361 name: "dim".into(),
1362 value: dim as i64,
1363 }];
1364 let semantic = SemanticDispatch {
1365 contract: CONTRACT,
1366 inputs: &semantic_inputs,
1367 outputs: &semantic_outputs,
1368 attributes: &attributes,
1369 };
1370 if dispatches.len() == 1 {
1371 runtime.record_semantic(
1372 dispatches.into_iter().next().expect("one dispatch"),
1373 semantic,
1374 )?;
1375 } else {
1376 runtime.record_split_semantic(&dispatches, semantic)?;
1377 }
1378 }
1379 if first.dtype() == DType::F32 {
1380 autograd::record_concat(inputs, &output, dim, sizes)?;
1381 }
1382 Ok(output)
1383}
1384
1385pub fn transpose(input: &Matrix, dim0: i32, dim1: i32) -> Result<Matrix> {
1397 const CONTRACT: OperationContract = crate::core::operation::matrix::TRANSPOSE;
1398 let operation = CONTRACT.name();
1399 let rank = input.shape().len();
1400 if input.dtype() != DType::F32 || !(2..=3).contains(&rank) {
1401 return Err(Error::invalid_argument(format!(
1402 "{operation} requires a rank-two or rank-three F32 matrix"
1403 )));
1404 }
1405 let resolve = |dim: i32| -> Result<usize> {
1406 let rank_i32 = i32::try_from(rank)
1407 .map_err(|_| Error::invalid_argument(format!("{operation} rank exceeds i32")))?;
1408 let resolved = if dim < 0 {
1409 dim.checked_add(rank_i32).ok_or_else(|| {
1410 Error::invalid_argument(format!("{operation} axis normalization overflows i32"))
1411 })?
1412 } else {
1413 dim
1414 };
1415 usize::try_from(resolved)
1416 .ok()
1417 .filter(|axis| *axis < rank)
1418 .ok_or_else(|| {
1419 Error::invalid_argument(format!("{operation} axis {dim} is outside rank {rank}"))
1420 })
1421 };
1422 let dim0 = resolve(dim0)?;
1423 let dim1 = resolve(dim1)?;
1424 let final_axes = [rank - 2, rank - 1];
1425 if dim0 == dim1 || !final_axes.contains(&dim0) || !final_axes.contains(&dim1) {
1426 return Err(Error::invalid_argument(format!(
1427 "{operation} supports only a swap of the final two axes"
1428 )));
1429 }
1430
1431 let rows = input.shape()[rank - 2];
1432 let columns = input.shape()[rank - 1];
1433 let batch_size = if rank == 3 { input.shape()[0] } else { 1 };
1434 let mut output_shape = input.shape().to_vec();
1435 output_shape.swap(rank - 2, rank - 1);
1436 let output = Matrix::allocate(
1437 input.runtime(),
1438 output_shape,
1439 input.element_count(),
1440 DType::F32,
1441 )?;
1442 if batch_size != 0 && rows != 0 && columns != 0 {
1443 let batch_size = as_u32(batch_size, operation, "batch size")?;
1444 let rows = as_u32(rows, operation, "row count")?;
1445 let columns = as_u32(columns, operation, "column count")?;
1446 let buffers = [
1447 BufferBinding::read(input.storage()),
1448 BufferBinding::write(output.storage()),
1449 ];
1450 let push_constants = [
1451 PushConstant::U32(batch_size),
1452 PushConstant::U32(rows),
1453 PushConstant::U32(columns),
1454 ];
1455 let inputs = [input];
1456 let outputs = [&output];
1457 let attributes = [
1458 OpAttribute::SignedInteger {
1459 name: "dim0".into(),
1460 value: i64::try_from(dim0)
1461 .map_err(|_| Error::invalid_argument("transpose dim0 exceeds i64"))?,
1462 },
1463 OpAttribute::SignedInteger {
1464 name: "dim1".into(),
1465 value: i64::try_from(dim1)
1466 .map_err(|_| Error::invalid_argument("transpose dim1 exceeds i64"))?,
1467 },
1468 ];
1469 input.runtime().record_semantic(
1470 ComputeDispatch {
1471 kernel: KernelId::MatrixTransposeF32,
1472 buffers: &buffers,
1473 push_constants: &push_constants,
1474 workgroups: [columns.div_ceil(32), rows.div_ceil(32), batch_size],
1475 indirect: None,
1476 },
1477 SemanticDispatch {
1478 contract: CONTRACT,
1479 inputs: &inputs,
1480 outputs: &outputs,
1481 attributes: &attributes,
1482 },
1483 )?;
1484 }
1485 autograd::record_transpose(input, &output, dim0, dim1)?;
1486 Ok(output)
1487}
1488
1489pub fn slice(input: &Matrix, dim: i32, start: i64, end: i64) -> Result<Matrix> {
1499 const CONTRACT: OperationContract = crate::core::operation::matrix::SLICE;
1500 let operation = CONTRACT.name();
1501 let rank = input.shape().len();
1502 if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
1503 return Err(Error::invalid_argument(format!(
1504 "{operation} requires a rank-one through rank-four F32 matrix"
1505 )));
1506 }
1507 let dim = usize::try_from(dim)
1508 .map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1509 if dim >= rank {
1510 return Err(Error::invalid_argument(format!(
1511 "{operation} dim {dim} is outside rank {rank}"
1512 )));
1513 }
1514 let start = usize::try_from(start)
1515 .map_err(|_| Error::invalid_argument(format!("{operation} start must be nonnegative")))?;
1516 let end = usize::try_from(end)
1517 .map_err(|_| Error::invalid_argument(format!("{operation} end must be nonnegative")))?;
1518 if start >= end || end > input.shape()[dim] {
1519 return Err(Error::invalid_argument(format!(
1520 "{operation} requires 0 <= start < end <= axis extent"
1521 )));
1522 }
1523 let mut output_shape = input.shape().to_vec();
1524 output_shape[dim] = end - start;
1525 let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1526 count
1527 .checked_mul(*extent)
1528 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1529 })?;
1530 let count = as_u32(output_count, operation, "output element count")?;
1531 let output = Matrix::allocate(
1532 input.runtime(),
1533 output_shape.clone(),
1534 output_count,
1535 DType::F32,
1536 )?;
1537 if count != 0 {
1538 let buffers = [
1539 BufferBinding::read(input.storage()),
1540 BufferBinding::write(output.storage()),
1541 ];
1542 let push_constants = region_push_constants(
1543 count,
1544 rank,
1545 dim,
1546 start,
1547 0,
1548 input.shape(),
1549 &output_shape,
1550 &output_shape,
1551 operation,
1552 )?;
1553 let inputs = [input];
1554 let outputs = [&output];
1555 let attributes = [
1556 OpAttribute::SignedInteger {
1557 name: "dim".into(),
1558 value: dim as i64,
1559 },
1560 OpAttribute::SignedInteger {
1561 name: "start".into(),
1562 value: start as i64,
1563 },
1564 OpAttribute::SignedInteger {
1565 name: "end".into(),
1566 value: end as i64,
1567 },
1568 ];
1569 input.runtime().record_semantic(
1570 ComputeDispatch {
1571 kernel: KernelId::MatrixSliceF32,
1572 buffers: &buffers,
1573 push_constants: &push_constants,
1574 workgroups: KernelId::MatrixSliceF32.linear_workgroups(count),
1575 indirect: None,
1576 },
1577 SemanticDispatch {
1578 contract: CONTRACT,
1579 inputs: &inputs,
1580 outputs: &outputs,
1581 attributes: &attributes,
1582 },
1583 )?;
1584 }
1585 autograd::record_slice(input, &output, dim, start, end)?;
1586 Ok(output)
1587}
1588
1589pub(crate) fn slice_backward(
1590 input_shape: &[usize],
1591 dim: usize,
1592 start: usize,
1593 end: usize,
1594 output_gradient: &Matrix,
1595) -> Result<Matrix> {
1596 const CONTRACT: OperationContract = crate::core::operation::matrix::SLICE_BACKWARD;
1597 let operation = CONTRACT.name();
1598 let rank = input_shape.len();
1599 if output_gradient.dtype() != DType::F32 || !(1..=4).contains(&rank) || dim >= rank {
1600 return Err(Error::invalid_argument(format!(
1601 "{operation} requires rank-one through rank-four F32 geometry"
1602 )));
1603 }
1604 if start >= end || end > input_shape[dim] {
1605 return Err(Error::invalid_argument(format!(
1606 "{operation} received an invalid saved slice range"
1607 )));
1608 }
1609 let mut slice_shape = input_shape.to_vec();
1610 slice_shape[dim] = end - start;
1611 if output_gradient.shape() != slice_shape {
1612 return Err(Error::invalid_argument(format!(
1613 "{operation} output gradient shape does not match the saved slice"
1614 )));
1615 }
1616 let output_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1617 count
1618 .checked_mul(*extent)
1619 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1620 })?;
1621 let copy_count = as_u32(
1622 output_gradient.num_elements(),
1623 operation,
1624 "copy element count",
1625 )?;
1626 let output = Matrix::allocate(
1627 output_gradient.runtime(),
1628 input_shape.to_vec(),
1629 output_count,
1630 DType::F32,
1631 )?;
1632 if copy_count != 0 {
1633 let buffers = [
1634 BufferBinding::read(output_gradient.storage()),
1635 BufferBinding::read_write(output.storage()),
1637 ];
1638 let push_constants = region_push_constants(
1639 copy_count,
1640 rank,
1641 dim,
1642 0,
1643 start,
1644 output_gradient.shape(),
1645 input_shape,
1646 output_gradient.shape(),
1647 operation,
1648 )?;
1649 let inputs = [output_gradient];
1650 let outputs = [&output];
1651 let attributes = [
1652 OpAttribute::Shape {
1653 name: "input_shape".into(),
1654 value: input_shape.to_vec(),
1655 },
1656 OpAttribute::SignedInteger {
1657 name: "dim".into(),
1658 value: dim as i64,
1659 },
1660 OpAttribute::SignedInteger {
1661 name: "start".into(),
1662 value: start as i64,
1663 },
1664 OpAttribute::SignedInteger {
1665 name: "end".into(),
1666 value: end as i64,
1667 },
1668 ];
1669 output_gradient.runtime().record_semantic(
1670 ComputeDispatch {
1671 kernel: KernelId::MatrixSliceBackwardF32,
1672 buffers: &buffers,
1673 push_constants: &push_constants,
1674 workgroups: KernelId::MatrixSliceBackwardF32.linear_workgroups(copy_count),
1675 indirect: None,
1676 },
1677 SemanticDispatch {
1678 contract: CONTRACT,
1679 inputs: &inputs,
1680 outputs: &outputs,
1681 attributes: &attributes,
1682 },
1683 )?;
1684 }
1685 Ok(output)
1686}
1687
1688#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1694pub enum PadMode {
1695 #[default]
1697 Constant = 0,
1698 Replicate = 1,
1700 Reflect = 2,
1702 Circular = 3,
1704}
1705
1706pub fn pad(input: &Matrix, pads: &[usize], mode: PadMode, fill: f32) -> Result<Matrix> {
1718 const CONTRACT: OperationContract = crate::core::operation::matrix::PAD;
1719 let operation = CONTRACT.name();
1720 let shape = input.shape();
1721 let rank = shape.len();
1722 if input.dtype() != DType::F32 || !(1..=5).contains(&rank) {
1723 return Err(Error::invalid_argument(format!(
1724 "{operation} requires a rank-one through rank-five F32 matrix"
1725 )));
1726 }
1727 if pads.len() != 2 * rank {
1728 return Err(Error::invalid_argument(format!(
1729 "{operation} requires one [before, after] pad pair per axis"
1730 )));
1731 }
1732 let mut output_shape = shape.to_vec();
1733 for (axis, extent) in output_shape.iter_mut().enumerate() {
1734 let before = pads[2 * axis];
1735 let after = pads[2 * axis + 1];
1736 if mode == PadMode::Reflect && (before >= *extent || after >= *extent) {
1737 return Err(Error::invalid_argument(format!(
1738 "{operation} reflect pads must be smaller than the axis extent"
1739 )));
1740 }
1741 *extent = extent
1742 .checked_add(before)
1743 .and_then(|extent| extent.checked_add(after))
1744 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
1745 }
1746 let output_count = output_shape.iter().try_fold(1_usize, |count, extent| {
1747 count
1748 .checked_mul(*extent)
1749 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1750 })?;
1751 let count = as_u32(output_count, operation, "output element count")?;
1752 let output = Matrix::allocate(
1753 input.runtime(),
1754 output_shape.clone(),
1755 output_count,
1756 DType::F32,
1757 )?;
1758 if count != 0 {
1759 let buffers = [
1760 BufferBinding::read(input.storage()),
1761 BufferBinding::write(output.storage()),
1762 ];
1763 let push_constants = pad_push_constants(
1764 count,
1765 rank,
1766 mode,
1767 fill,
1768 &PadExtents {
1769 input: shape,
1770 output: &output_shape,
1771 pads,
1772 },
1773 true,
1774 operation,
1775 )?;
1776 let inputs = [input];
1777 let outputs = [&output];
1778 let attributes = [
1779 OpAttribute::Shape {
1780 name: "pads".into(),
1781 value: pads.to_vec(),
1782 },
1783 OpAttribute::UnsignedInteger {
1784 name: "mode".into(),
1785 value: mode as u64,
1786 },
1787 OpAttribute::Float {
1788 name: "fill".into(),
1789 value: fill as f64,
1790 },
1791 ];
1792 input.runtime().record_semantic(
1793 ComputeDispatch {
1794 kernel: KernelId::MatrixPadF32,
1795 buffers: &buffers,
1796 push_constants: &push_constants,
1797 workgroups: KernelId::MatrixPadF32.linear_workgroups(count),
1798 indirect: None,
1799 },
1800 SemanticDispatch {
1801 contract: CONTRACT,
1802 inputs: &inputs,
1803 outputs: &outputs,
1804 attributes: &attributes,
1805 },
1806 )?;
1807 }
1808 autograd::record_pad(input, &output, pads.to_vec(), mode as usize)?;
1809 Ok(output)
1810}
1811
1812pub(crate) fn pad_backward(
1813 input_shape: &[usize],
1814 pads: &[usize],
1815 mode: usize,
1816 output_gradient: &Matrix,
1817) -> Result<Matrix> {
1818 const CONTRACT: OperationContract = crate::core::operation::matrix::PAD_BACKWARD;
1819 let operation = CONTRACT.name();
1820 let rank = input_shape.len();
1821 if output_gradient.dtype() != DType::F32 || !(1..=5).contains(&rank) || pads.len() != 2 * rank {
1822 return Err(Error::invalid_argument(format!(
1823 "{operation} requires rank-one through rank-five F32 geometry"
1824 )));
1825 }
1826 let mut expected = input_shape.to_vec();
1827 for (axis, extent) in expected.iter_mut().enumerate() {
1828 *extent += pads[2 * axis] + pads[2 * axis + 1];
1829 }
1830 if output_gradient.shape() != expected {
1831 return Err(Error::invalid_argument(format!(
1832 "{operation} output gradient shape does not match the saved pad"
1833 )));
1834 }
1835 let output_count = input_shape.iter().try_fold(1_usize, |count, extent| {
1836 count
1837 .checked_mul(*extent)
1838 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
1839 })?;
1840 let count = as_u32(output_count, operation, "output element count")?;
1841 let output = Matrix::allocate(
1842 output_gradient.runtime(),
1843 input_shape.to_vec(),
1844 output_count,
1845 DType::F32,
1846 )?;
1847 if count != 0 {
1848 let pad_mode = match mode {
1849 1 => PadMode::Replicate,
1850 2 => PadMode::Reflect,
1851 3 => PadMode::Circular,
1852 _ => PadMode::Constant,
1853 };
1854 let buffers = [
1855 BufferBinding::read(output_gradient.storage()),
1856 BufferBinding::write(output.storage()),
1857 ];
1858 let push_constants = pad_push_constants(
1859 count,
1860 rank,
1861 pad_mode,
1862 0.0,
1863 &PadExtents {
1864 input: input_shape,
1865 output: output_gradient.shape(),
1866 pads,
1867 },
1868 false,
1869 operation,
1870 )?;
1871 let inputs = [output_gradient];
1872 let outputs = [&output];
1873 let attributes = [
1874 OpAttribute::Shape {
1875 name: "input_shape".into(),
1876 value: input_shape.to_vec(),
1877 },
1878 OpAttribute::Shape {
1879 name: "pads".into(),
1880 value: pads.to_vec(),
1881 },
1882 OpAttribute::UnsignedInteger {
1883 name: "mode".into(),
1884 value: mode as u64,
1885 },
1886 ];
1887 output_gradient.runtime().record_semantic(
1888 ComputeDispatch {
1889 kernel: KernelId::MatrixPadBackwardF32,
1890 buffers: &buffers,
1891 push_constants: &push_constants,
1892 workgroups: KernelId::MatrixPadBackwardF32.linear_workgroups(count),
1893 indirect: None,
1894 },
1895 SemanticDispatch {
1896 contract: CONTRACT,
1897 inputs: &inputs,
1898 outputs: &outputs,
1899 attributes: &attributes,
1900 },
1901 )?;
1902 }
1903 Ok(output)
1904}
1905
1906struct PadExtents<'a> {
1908 input: &'a [usize],
1909 output: &'a [usize],
1910 pads: &'a [usize],
1911}
1912
1913fn pad_push_constants(
1917 count: u32,
1918 rank: usize,
1919 mode: PadMode,
1920 fill: f32,
1921 extents: &PadExtents<'_>,
1922 forward: bool,
1923 operation: &'static str,
1924) -> Result<Vec<PushConstant>> {
1925 let mut push_constants = Vec::with_capacity(if forward { 19 } else { 18 });
1926 push_constants.push(PushConstant::U32(count));
1927 push_constants.push(PushConstant::U32(rank as u32));
1928 push_constants.push(PushConstant::U32(mode as u32));
1929 if forward {
1930 push_constants.push(PushConstant::U32(fill.to_bits()));
1931 }
1932 for shape in [extents.input, extents.output] {
1933 for axis in 0..5 {
1934 push_constants.push(PushConstant::U32(if axis < shape.len() {
1935 as_u32(shape[axis], operation, "pad extent")?
1936 } else {
1937 0
1938 }));
1939 }
1940 }
1941 for axis in 0..5 {
1942 push_constants.push(PushConstant::U32(if axis < rank {
1943 as_u32(extents.pads[2 * axis], operation, "pad before")?
1944 } else {
1945 0
1946 }));
1947 }
1948 Ok(push_constants)
1949}
1950
1951pub fn split(input: &Matrix, sizes: &[i64], dim: i32) -> Result<Vec<Matrix>> {
1966 const CONTRACT: OperationContract = crate::core::operation::matrix::SPLIT;
1967 let operation = CONTRACT.name();
1968 let rank = input.shape().len();
1969 if input.dtype() != DType::F32 || !(1..=4).contains(&rank) {
1970 return Err(Error::invalid_argument(format!(
1971 "{operation} requires a rank-one through rank-four F32 matrix"
1972 )));
1973 }
1974 let dim = usize::try_from(dim)
1975 .map_err(|_| Error::invalid_argument(format!("{operation} dim must be nonnegative")))?;
1976 if dim >= rank {
1977 return Err(Error::invalid_argument(format!(
1978 "{operation} dim {dim} is outside rank {rank}"
1979 )));
1980 }
1981 if sizes.is_empty() {
1982 return Err(Error::invalid_argument(format!(
1983 "{operation} requires at least one size"
1984 )));
1985 }
1986 let mut extents = Vec::with_capacity(sizes.len());
1987 let mut total = 0usize;
1988 for &size in sizes {
1989 let extent = usize::try_from(size)
1990 .map_err(|_| Error::invalid_argument(format!("{operation} sizes must be nonnegative")))?;
1991 if extent == 0 {
1992 return Err(Error::invalid_argument(format!(
1993 "{operation} sizes must be positive"
1994 )));
1995 }
1996 total = total
1997 .checked_add(extent)
1998 .ok_or_else(|| Error::invalid_argument(format!("{operation} sizes overflow usize")))?;
1999 extents.push(extent);
2000 }
2001 if total != input.shape()[dim] {
2002 return Err(Error::invalid_argument(format!(
2003 "{operation} sizes must sum to the dim extent"
2004 )));
2005 }
2006 let runtime = input.runtime();
2007 let lowering = runtime.begin_semantic_lowering()?;
2008 let mut outputs = Vec::with_capacity(extents.len());
2009 let mut offset = 0usize;
2010 for &extent in &extents {
2011 let mut output_shape = input.shape().to_vec();
2012 output_shape[dim] = extent;
2013 let output_count = output_shape.iter().try_fold(1_usize, |count, axis| {
2014 count
2015 .checked_mul(*axis)
2016 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))
2017 })?;
2018 let count = as_u32(output_count, operation, "output element count")?;
2019 let output = Matrix::allocate(runtime, output_shape.clone(), output_count, DType::F32)?;
2020 if count != 0 {
2021 let buffers = [
2022 BufferBinding::read(input.storage()),
2023 BufferBinding::write(output.storage()),
2024 ];
2025 let push_constants = region_push_constants(
2026 count,
2027 rank,
2028 dim,
2029 offset,
2030 0,
2031 input.shape(),
2032 &output_shape,
2033 &output_shape,
2034 operation,
2035 )?;
2036 lowering.record_physical(ComputeDispatch {
2037 kernel: KernelId::MatrixSliceF32,
2038 buffers: &buffers,
2039 push_constants: &push_constants,
2040 workgroups: KernelId::MatrixSliceF32.linear_workgroups(count),
2041 indirect: None,
2042 })?;
2043 }
2044 outputs.push(output);
2045 offset += extent;
2046 }
2047 let inputs = [input];
2048 let output_refs: Vec<&Matrix> = outputs.iter().collect();
2049 let attributes = [OpAttribute::SignedInteger {
2050 name: "dim".into(),
2051 value: dim as i64,
2052 }];
2053 lowering.commit(SemanticDispatch {
2054 contract: CONTRACT,
2055 inputs: &inputs,
2056 outputs: &output_refs,
2057 attributes: &attributes,
2058 })?;
2059 let mut start = 0usize;
2060 for (output, &extent) in outputs.iter().zip(&extents) {
2061 autograd::record_slice(input, output, dim, start, start + extent)?;
2062 start += extent;
2063 }
2064 Ok(outputs)
2065}
2066
2067pub fn compact_rows(input: &Matrix, mask: &Matrix) -> Result<CompactRowsResult> {
2080 const CONTRACT: OperationContract = crate::core::operation::matrix::COMPACT_ROWS;
2081 let operation = CONTRACT.name();
2082 let [t, d] = input.shape() else {
2083 return Err(Error::invalid_argument(format!(
2084 "{operation} requires a rank-two [T,D] input"
2085 )));
2086 };
2087 if input.dtype() != DType::F32
2088 || mask.dtype() != DType::F32
2089 || mask.num_elements() != *t
2090 || !input.runtime().same_as(mask.runtime())
2091 {
2092 return Err(Error::invalid_argument(format!(
2093 "{operation} requires an FP32 [T,D] input and same-runtime FP32 [T] mask"
2094 )));
2095 }
2096 let element_count = t
2097 .checked_mul(*d)
2098 .ok_or_else(|| Error::invalid_argument(format!("{operation} element count overflows usize")))?;
2099 let runtime = input.runtime();
2100 let values = Matrix::allocate(runtime, input.shape().to_vec(), element_count, DType::F32)?;
2101 let row_map = Matrix::allocate(runtime, vec![*t], *t, DType::U32)?;
2102 let t = as_u32(*t, operation, "row count")?;
2103 let d = as_u32(*d, operation, "row width")?;
2104 let emitted_groups = KernelId::MatrixCompactRowsF32.linear_workgroups(as_u32(
2107 element_count,
2108 operation,
2109 "element count",
2110 )?)[0];
2111 if emitted_groups > runtime.max_compute_work_group_count()[0] {
2112 return Err(Error::invalid_argument(format!(
2113 "{operation} indirect group count {emitted_groups} exceeds the device limit"
2114 )));
2115 }
2116 let count = Matrix::allocate(runtime, vec![1], 1, DType::U32)?;
2117 let dispatch_args = Matrix::allocate(runtime, vec![3], 3, DType::U32)?;
2118 let buffers = [
2119 BufferBinding::read(input.storage()),
2120 BufferBinding::read(mask.storage()),
2121 BufferBinding::write(values.storage()),
2122 BufferBinding::write(row_map.storage()),
2123 BufferBinding::write(count.storage()),
2124 BufferBinding::write(dispatch_args.storage()),
2125 ];
2126 let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2127 let inputs = [input, mask];
2128 let outputs = [&values, &row_map, &count, &dispatch_args];
2129 input.runtime().record_semantic(
2130 ComputeDispatch {
2131 kernel: KernelId::MatrixCompactRowsF32,
2132 buffers: &buffers,
2133 push_constants: &push_constants,
2134 workgroups: [1, 1, 1],
2135 indirect: None,
2136 },
2137 SemanticDispatch {
2138 contract: CONTRACT,
2139 inputs: &inputs,
2140 outputs: &outputs,
2141 attributes: &[],
2142 },
2143 )?;
2144 autograd::record_compact_rows(input, &values, &row_map, &count, &dispatch_args)?;
2145 Ok(CompactRowsResult {
2146 values,
2147 row_map,
2148 count,
2149 dispatch_args,
2150 })
2151}
2152
2153pub(crate) fn compact_rows_backward(
2166 output_gradient: &Matrix,
2167 row_map: &Matrix,
2168 count: &Matrix,
2169 dispatch_args: Option<&Matrix>,
2170 input_shape: &[usize],
2171) -> Result<Matrix> {
2172 const CONTRACT: OperationContract = crate::core::operation::matrix::COMPACT_ROWS_BACKWARD;
2173 let operation = CONTRACT.name();
2174 let [t, d] = input_shape else {
2175 return Err(Error::invalid_argument(format!(
2176 "{operation} requires a rank-two [T,D] input shape"
2177 )));
2178 };
2179 if output_gradient.dtype() != DType::F32 || output_gradient.shape() != input_shape {
2180 return Err(Error::invalid_argument(format!(
2181 "{operation} requires an FP32 [T,D] output gradient"
2182 )));
2183 }
2184 if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2185 return Err(Error::invalid_argument(format!(
2186 "{operation} requires a U32 row map with at least T entries"
2187 )));
2188 }
2189 if count.dtype() != DType::U32 || count.num_elements() != 1 {
2190 return Err(Error::invalid_argument(format!(
2191 "{operation} requires a U32 [1] count"
2192 )));
2193 }
2194 let t = as_u32(*t, operation, "row count")?;
2195 let d = as_u32(*d, operation, "row width")?;
2196 let element_count = output_gradient.num_elements();
2197 let element_count_u32 = as_u32(element_count, operation, "element count")?;
2198 let runtime = output_gradient.runtime();
2199 let indirect = indirect_plan(
2200 dispatch_args,
2201 runtime,
2202 element_count_u32,
2203 KernelId::MatrixCompactRowsBackwardIndirectF32,
2204 operation,
2205 )?;
2206 let input_gradient = Matrix::allocate(runtime, input_shape.to_vec(), element_count, DType::F32)?;
2207 let direct_buffers = [
2208 BufferBinding::read(output_gradient.storage()),
2209 BufferBinding::read(row_map.storage()),
2210 BufferBinding::read(count.storage()),
2211 BufferBinding::read_write(input_gradient.storage()),
2212 ];
2213 let indirect_buffers = dispatch_args.map(|dispatch_args| {
2214 [
2215 BufferBinding::read(output_gradient.storage()),
2216 BufferBinding::read(row_map.storage()),
2217 BufferBinding::read(count.storage()),
2218 BufferBinding::read(dispatch_args.storage()),
2219 BufferBinding::read_write(input_gradient.storage()),
2220 ]
2221 });
2222 let (kernel, workgroups, buffers) = if let Some(indirect_buffers) = &indirect_buffers {
2223 (
2224 KernelId::MatrixCompactRowsBackwardIndirectF32,
2225 [0, 0, 0],
2226 indirect_buffers.as_slice(),
2227 )
2228 } else {
2229 (
2230 KernelId::MatrixCompactRowsBackwardF32,
2231 KernelId::MatrixCompactRowsBackwardF32.linear_workgroups(element_count_u32),
2232 direct_buffers.as_slice(),
2233 )
2234 };
2235 let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2236 let inputs = [
2237 Some(output_gradient),
2238 Some(row_map),
2239 Some(count),
2240 dispatch_args,
2241 ];
2242 let outputs = [&input_gradient];
2243 let attributes = [OpAttribute::Shape {
2244 name: "inputShape".into(),
2245 value: input_shape.to_vec(),
2246 }];
2247 runtime.record_optional_semantic(
2248 ComputeDispatch {
2249 kernel,
2250 buffers,
2251 push_constants: &push_constants,
2252 workgroups,
2253 indirect,
2254 },
2255 OptionalSemanticDispatch {
2256 contract: CONTRACT,
2257 inputs: &inputs,
2258 outputs: &outputs,
2259 attributes: &attributes,
2260 },
2261 )?;
2262 Ok(input_gradient)
2263}
2264
2265pub fn scatter_rows(
2277 input: &Matrix,
2278 source: &Matrix,
2279 row_map: &Matrix,
2280 count: &Matrix,
2281) -> Result<Matrix> {
2282 const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS;
2283 let operation = CONTRACT.name();
2284 let [t, d] = input.shape() else {
2285 return Err(Error::invalid_argument(format!(
2286 "{operation} requires a rank-two [T,D] input"
2287 )));
2288 };
2289 if input.dtype() != DType::F32 || source.shape() != input.shape() || source.dtype() != DType::F32
2290 {
2291 return Err(Error::invalid_argument(format!(
2292 "{operation} requires matching FP32 [T,D] input and source"
2293 )));
2294 }
2295 if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2296 return Err(Error::invalid_argument(format!(
2297 "{operation} requires a U32 row map with at least T entries"
2298 )));
2299 }
2300 if count.dtype() != DType::U32 || count.num_elements() != 1 {
2301 return Err(Error::invalid_argument(format!(
2302 "{operation} requires a U32 [1] count"
2303 )));
2304 }
2305 for auxiliary in [source, row_map, count] {
2306 if !auxiliary.runtime().same_as(input.runtime()) {
2307 return Err(Error::invalid_argument(format!(
2308 "{operation} inputs must share one runtime"
2309 )));
2310 }
2311 }
2312 let t = as_u32(*t, operation, "row count")?;
2313 let d = as_u32(*d, operation, "row width")?;
2314 let element_count = input.num_elements();
2315 let output = Matrix::allocate(
2316 input.runtime(),
2317 input.shape().to_vec(),
2318 element_count,
2319 DType::F32,
2320 )?;
2321 let buffers = [
2322 BufferBinding::read(input.storage()),
2323 BufferBinding::read(source.storage()),
2324 BufferBinding::read(row_map.storage()),
2325 BufferBinding::read(count.storage()),
2326 BufferBinding::write(output.storage()),
2327 ];
2328 let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2329 let inputs = [Some(input), Some(source), Some(row_map), Some(count), None];
2330 let outputs = [&output];
2331 input.runtime().record_optional_semantic(
2332 ComputeDispatch {
2333 kernel: KernelId::MatrixScatterRowsF32,
2334 buffers: &buffers,
2335 push_constants: &push_constants,
2336 workgroups: KernelId::MatrixScatterRowsF32.linear_workgroups(as_u32(
2337 element_count,
2338 operation,
2339 "element count",
2340 )?),
2341 indirect: None,
2342 },
2343 OptionalSemanticDispatch {
2344 contract: CONTRACT,
2345 inputs: &inputs,
2346 outputs: &outputs,
2347 attributes: &[],
2348 },
2349 )?;
2350 autograd::record_scatter_rows(input, source, &output, row_map, count, None)?;
2351 Ok(output)
2352}
2353
2354pub fn scatter_rows_indirect(
2368 input: &Matrix,
2369 source: &Matrix,
2370 plan: &CompactRowsResult,
2371) -> Result<Matrix> {
2372 const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS;
2373 let operation = CONTRACT.name();
2374 let [t, d] = input.shape() else {
2375 return Err(Error::invalid_argument(format!(
2376 "{operation} requires a rank-two [T,D] input"
2377 )));
2378 };
2379 if input.dtype() != DType::F32 || source.shape() != input.shape() || source.dtype() != DType::F32
2380 {
2381 return Err(Error::invalid_argument(format!(
2382 "{operation} requires matching FP32 [T,D] input and source"
2383 )));
2384 }
2385 let CompactRowsResult {
2386 row_map,
2387 count,
2388 dispatch_args,
2389 ..
2390 } = plan;
2391 if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2392 return Err(Error::invalid_argument(format!(
2393 "{operation} requires a U32 row map with at least T entries"
2394 )));
2395 }
2396 if count.dtype() != DType::U32 || count.num_elements() != 1 {
2397 return Err(Error::invalid_argument(format!(
2398 "{operation} requires a U32 [1] count"
2399 )));
2400 }
2401 let runtime = input.runtime();
2402 for auxiliary in [source, row_map, count, dispatch_args] {
2403 if !auxiliary.runtime().same_as(runtime) {
2404 return Err(Error::invalid_argument(format!(
2405 "{operation} inputs must share one runtime"
2406 )));
2407 }
2408 }
2409 let t = as_u32(*t, operation, "row count")?;
2410 let d = as_u32(*d, operation, "row width")?;
2411 let element_count_u32 = as_u32(input.num_elements(), operation, "element count")?;
2412 let indirect = indirect_plan(
2413 Some(dispatch_args),
2414 runtime,
2415 element_count_u32,
2416 KernelId::MatrixScatterRowsIndirectF32,
2417 operation,
2418 )?;
2419 let scope = runtime.begin_semantic_lowering()?;
2420 let output = input.copy()?;
2423 let buffers = [
2424 BufferBinding::read(source.storage()),
2425 BufferBinding::read(row_map.storage()),
2426 BufferBinding::read(count.storage()),
2427 BufferBinding::read(dispatch_args.storage()),
2428 BufferBinding::read_write(output.storage()),
2429 ];
2430 let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2431 let inputs = [
2432 Some(input),
2433 Some(source),
2434 Some(row_map),
2435 Some(count),
2436 Some(dispatch_args),
2437 ];
2438 let outputs = [&output];
2439 let semantic = OptionalSemanticDispatch {
2440 contract: CONTRACT,
2441 inputs: &inputs,
2442 outputs: &outputs,
2443 attributes: &[],
2444 };
2445 semantic.validate_kernel(KernelId::MatrixScatterRowsIndirectF32)?;
2446 scope.record_physical(ComputeDispatch {
2447 kernel: KernelId::MatrixScatterRowsIndirectF32,
2448 buffers: &buffers,
2449 push_constants: &push_constants,
2450 workgroups: [0, 0, 0],
2451 indirect,
2452 })?;
2453 scope.commit_optional(semantic)?;
2454 autograd::record_scatter_rows(input, source, &output, row_map, count, Some(dispatch_args))?;
2455 Ok(output)
2456}
2457
2458pub(crate) fn scatter_rows_backward_source(
2472 output_gradient: &Matrix,
2473 row_map: &Matrix,
2474 count: &Matrix,
2475 dispatch_args: Option<&Matrix>,
2476) -> Result<Matrix> {
2477 const CONTRACT: OperationContract = crate::core::operation::matrix::SCATTER_ROWS_BACKWARD_SOURCE;
2478 let operation = CONTRACT.name();
2479 let [t, d] = output_gradient.shape() else {
2480 return Err(Error::invalid_argument(format!(
2481 "{operation} requires a rank-two [T,D] output gradient"
2482 )));
2483 };
2484 if output_gradient.dtype() != DType::F32 {
2485 return Err(Error::invalid_argument(format!(
2486 "{operation} requires an FP32 output gradient"
2487 )));
2488 }
2489 if row_map.dtype() != DType::U32 || row_map.num_elements() < *t {
2490 return Err(Error::invalid_argument(format!(
2491 "{operation} requires a U32 row map with at least T entries"
2492 )));
2493 }
2494 if count.dtype() != DType::U32 || count.num_elements() != 1 {
2495 return Err(Error::invalid_argument(format!(
2496 "{operation} requires a U32 [1] count"
2497 )));
2498 }
2499 let t = as_u32(*t, operation, "row count")?;
2500 let d = as_u32(*d, operation, "row width")?;
2501 let element_count = output_gradient.num_elements();
2502 let element_count_u32 = as_u32(element_count, operation, "element count")?;
2503 let runtime = output_gradient.runtime();
2504 let indirect = indirect_plan(
2505 dispatch_args,
2506 runtime,
2507 element_count_u32,
2508 KernelId::MatrixScatterRowsBackwardSourceIndirectF32,
2509 operation,
2510 )?;
2511 let source_gradient = Matrix::allocate(
2512 runtime,
2513 output_gradient.shape().to_vec(),
2514 element_count,
2515 DType::F32,
2516 )?;
2517 let direct_buffers = [
2518 BufferBinding::read(output_gradient.storage()),
2519 BufferBinding::read(row_map.storage()),
2520 BufferBinding::read(count.storage()),
2521 BufferBinding::write(source_gradient.storage()),
2522 ];
2523 let indirect_buffers = dispatch_args.map(|dispatch_args| {
2524 [
2525 BufferBinding::read(output_gradient.storage()),
2526 BufferBinding::read(row_map.storage()),
2527 BufferBinding::read(count.storage()),
2528 BufferBinding::read(dispatch_args.storage()),
2529 BufferBinding::write(source_gradient.storage()),
2530 ]
2531 });
2532 let (kernel, workgroups, buffers) = if let Some(indirect_buffers) = &indirect_buffers {
2533 (
2534 KernelId::MatrixScatterRowsBackwardSourceIndirectF32,
2535 [0, 0, 0],
2536 indirect_buffers.as_slice(),
2537 )
2538 } else {
2539 (
2540 KernelId::MatrixScatterRowsBackwardSourceF32,
2541 KernelId::MatrixScatterRowsBackwardSourceF32.linear_workgroups(element_count_u32),
2542 direct_buffers.as_slice(),
2543 )
2544 };
2545 let push_constants = [PushConstant::U32(t), PushConstant::U32(d)];
2546 let inputs = [
2547 Some(output_gradient),
2548 Some(row_map),
2549 Some(count),
2550 dispatch_args,
2551 ];
2552 let outputs = [&source_gradient];
2553 runtime.record_optional_semantic(
2554 ComputeDispatch {
2555 kernel,
2556 buffers,
2557 push_constants: &push_constants,
2558 workgroups,
2559 indirect,
2560 },
2561 OptionalSemanticDispatch {
2562 contract: CONTRACT,
2563 inputs: &inputs,
2564 outputs: &outputs,
2565 attributes: &[],
2566 },
2567 )?;
2568 Ok(source_gradient)
2569}
2570
2571pub(crate) fn scatter_rows_backward(
2575 output_gradient: Matrix,
2576 row_map: &Matrix,
2577 count: &Matrix,
2578 dispatch_args: Option<&Matrix>,
2579) -> Result<(Matrix, Matrix)> {
2580 let source_gradient =
2581 scatter_rows_backward_source(&output_gradient, row_map, count, dispatch_args)?;
2582 Ok((output_gradient, source_gradient))
2583}
2584
2585#[allow(
2586 clippy::too_many_arguments,
2587 reason = "the arguments preserve the donor MatrixCopyRegion ABI"
2588)]
2589fn region_push_constants(
2590 count: u32,
2591 rank: usize,
2592 dim: usize,
2593 source_start: usize,
2594 destination_start: usize,
2595 source_shape: &[usize],
2596 destination_shape: &[usize],
2597 copy_shape: &[usize],
2598 operation: &'static str,
2599) -> Result<Vec<PushConstant>> {
2600 let mut push_constants = Vec::with_capacity(17);
2601 for value in [rank, dim, source_start, destination_start] {
2602 as_u32(value, operation, "region field")?;
2603 }
2604 push_constants.push(PushConstant::U32(count));
2605 push_constants.push(PushConstant::U32(rank as u32));
2606 push_constants.push(PushConstant::U32(dim as u32));
2607 push_constants.push(PushConstant::U32(source_start as u32));
2608 push_constants.push(PushConstant::U32(destination_start as u32));
2609 for shape in [source_shape, destination_shape, copy_shape] {
2610 for axis in 0..4 {
2611 push_constants.push(PushConstant::U32(if axis < shape.len() {
2612 as_u32(shape[axis], operation, "region extent")?
2613 } else {
2614 0
2615 }));
2616 }
2617 }
2618 Ok(push_constants)
2619}
2620
2621fn indirect_plan<'a>(
2628 dispatch_args: Option<&'a Matrix>,
2629 runtime: &RuntimeHandle,
2630 element_count: u32,
2631 kernel: KernelId,
2632 operation: &'static str,
2633) -> Result<Option<IndirectDispatch<'a>>> {
2634 let Some(dispatch_args) = dispatch_args else {
2635 return Ok(None);
2636 };
2637 if dispatch_args.dtype() != DType::U32 || dispatch_args.num_elements() != 3 {
2638 return Err(Error::invalid_argument(format!(
2639 "{operation} requires a U32 [3] dispatch-args plan"
2640 )));
2641 }
2642 if !dispatch_args.runtime().same_as(runtime) {
2643 return Err(Error::invalid_argument(format!(
2644 "{operation} inputs must share one runtime"
2645 )));
2646 }
2647 let emitted_groups = kernel.linear_workgroups(element_count)[0];
2648 if emitted_groups > runtime.max_compute_work_group_count()[0] {
2649 return Err(Error::invalid_argument(format!(
2650 "{operation} indirect group count {emitted_groups} exceeds the device limit"
2651 )));
2652 }
2653 Ok(Some(IndirectDispatch {
2654 storage: dispatch_args.storage(),
2655 offset: 0,
2656 }))
2657}
2658
2659fn as_u32(value: usize, operation: &'static str, label: &str) -> Result<u32> {
2660 u32::try_from(value)
2661 .map_err(|_| Error::invalid_argument(format!("{operation} {label} exceeds u32")))
2662}
2663
2664fn shape_u32(shape: &[usize], operation: &'static str) -> Result<[u32; 4]> {
2665 let mut dimensions = [0_u32; 4];
2666 for (axis, extent) in shape.iter().copied().enumerate() {
2667 dimensions[axis] = as_u32(extent, operation, "shape extent")?;
2668 }
2669 Ok(dimensions)
2670}
2671
2672fn row_major_strides_u32(shape: &[usize], operation: &'static str) -> Result<[u32; 4]> {
2673 let mut strides = [0_u32; 4];
2674 let mut stride = 1_usize;
2675 for axis in (0..shape.len()).rev() {
2676 strides[axis] = as_u32(stride, operation, "row-major stride")?;
2677 stride = stride.checked_mul(shape[axis]).ok_or_else(|| {
2678 Error::invalid_argument(format!("{operation} row-major stride overflows usize"))
2679 })?;
2680 }
2681 Ok(strides)
2682}
2683
2684pub(crate) fn concat_backward(
2686 output_gradient: &Matrix,
2687 dim: usize,
2688 sizes: &[usize],
2689) -> Result<Vec<Option<Matrix>>> {
2690 let mut input_gradients = Vec::with_capacity(sizes.len());
2691 let mut start = 0_usize;
2692 for size in sizes {
2693 let end = start
2694 .checked_add(*size)
2695 .ok_or_else(|| Error::internal("saved Concat interval overflows usize"))?;
2696 if *size != 0 {
2697 let dim = i32::try_from(dim).map_err(|_| Error::internal("saved Concat axis exceeds i32"))?;
2698 let start_i64 =
2699 i64::try_from(start).map_err(|_| Error::internal("saved Concat interval exceeds i64"))?;
2700 let end_i64 =
2701 i64::try_from(end).map_err(|_| Error::internal("saved Concat interval exceeds i64"))?;
2702 let input_gradient = slice(output_gradient, dim, start_i64, end_i64)?;
2703 input_gradients.push(Some(input_gradient));
2704 } else {
2705 input_gradients.push(None);
2706 }
2707 start = end;
2708 }
2709 Ok(input_gradients)
2710}
2711
2712pub(crate) fn transpose_backward(
2714 output_gradient: &Matrix,
2715 dim0: usize,
2716 dim1: usize,
2717) -> Result<Matrix> {
2718 let dim0 =
2719 i32::try_from(dim0).map_err(|_| Error::internal("saved Transpose dim0 exceeds i32"))?;
2720 let dim1 =
2721 i32::try_from(dim1).map_err(|_| Error::internal("saved Transpose dim1 exceeds i32"))?;
2722 transpose(output_gradient, dim0, dim1)
2723}