1use super::{ACTIVE_TAPES, GradNode, GradientTape};
7use crate::matrix::{autograd::GradientContext, sum_to_shape};
8use crate::ml::autograd::node::operation::BackwardStatus;
9use crate::ml::{flow as flow_lowering, matrix as ml_matrix};
10use crate::{DType, Error, Matrix, Result, matrix};
11use std::{collections::HashMap, rc::Rc};
12
13impl GradientTape {
14 pub fn backward(&self, root: &Matrix) -> Result<()> {
27 let self_weak = Rc::downgrade(&self.recording);
28 let another_tape_is_active = ACTIVE_TAPES.with(|tapes| {
29 tapes
30 .borrow()
31 .iter()
32 .any(|candidate| candidate.strong_count() != 0 && !candidate.ptr_eq(&self_weak))
33 });
34 if another_tape_is_active {
35 return Err(Error::failed_precondition(
36 "gradient backward requires every other tape on this thread to be closed",
37 ));
38 }
39 self.close();
40 if self.recording.consumed.get() {
41 return Err(Error::failed_precondition(
42 "gradient tape has already been consumed",
43 ));
44 }
45 if !root.shape().is_empty() || root.dtype() != DType::F32 {
46 return Err(Error::invalid_argument(
47 "gradient tape root must be an FP32 scalar",
48 ));
49 }
50 let nodes = self.recording.nodes.borrow();
51 let root_found = nodes
52 .iter()
53 .any(|entry| entry.node.produces(root.value_id()));
54 if !root_found {
55 return Err(Error::failed_precondition(
56 "gradient tape root was not produced by this tape",
57 ));
58 }
59 for entry in nodes.iter() {
60 entry.node.validate_versions()?;
61 }
62 for watched in self.recording.watched_parameters.borrow().iter() {
63 watched.parameter.validate_version(watched.version)?;
64 }
65 self.recording.consumed.set(true);
66
67 let runtime = root.runtime().clone();
68 let mut gradients = HashMap::<u64, Matrix>::new();
69 gradients.insert(
70 root.value_id(),
71 Matrix::new_from_slice_handle(&runtime, vec![], &[1.0_f32])?,
72 );
73 for entry in nodes.iter().rev() {
74 let node = &entry.node;
75 let Some(reached_output_id) = reached_output_id(node, &gradients) else {
76 continue;
77 };
78 let attachment = runtime.attach_semantic_autograd(reached_output_id, entry.sequence)?;
79 let backward_first = runtime.semantic_operation_count();
80 match node {
81 GradNode::Matrix(node) => {
82 if !node.backward(&mut MatrixGradients(&mut gradients))? {
83 continue;
84 }
85 }
86 GradNode::Operation(node) => {
87 if matches!(node.backward(&mut gradients)?, BackwardStatus::Skipped) {
88 continue;
89 }
90 }
91 GradNode::Audio(node) => {
92 let Some(output_gradient) = gradients.remove(&reached_output_id) else {
93 continue;
94 };
95 let (input_id, input_gradient) =
96 crate::audio::autograd::backward(node, &output_gradient)?;
97 accumulate_value_gradient(&mut gradients, input_id, input_gradient)?;
98 }
99 GradNode::FlowLinearState {
100 clean,
101 noise,
102 time,
103 output_id,
104 } => {
105 let Some(output_gradient) = gradients.remove(output_id) else {
106 continue;
107 };
108 let one_minus_time = matrix::add_scalar(&matrix::scale(time, -1.0)?, 1.0)?;
109 let clean_gradient = matrix::mul(&output_gradient, &one_minus_time)?;
110 let noise_gradient = matrix::mul(&output_gradient, time)?;
111 let velocity = matrix::sub(noise, clean)?;
112 let time_gradient = matrix::mul(&output_gradient, &velocity)?;
113 accumulate_value_gradient(
114 &mut gradients,
115 clean.value_id(),
116 sum_to_shape(&clean_gradient, clean.shape())?,
117 )?;
118 accumulate_value_gradient(
119 &mut gradients,
120 noise.value_id(),
121 sum_to_shape(&noise_gradient, noise.shape())?,
122 )?;
123 accumulate_value_gradient(
124 &mut gradients,
125 time.value_id(),
126 sum_to_flow_time_shape(&time_gradient, time.shape(), clean.shape())?,
127 )?;
128 }
129 GradNode::FlowLinearVelocity {
130 clean,
131 noise,
132 output_id,
133 } => {
134 let Some(output_gradient) = gradients.remove(output_id) else {
135 continue;
136 };
137 accumulate_value_gradient(
138 &mut gradients,
139 clean.value_id(),
140 matrix::scale(&output_gradient, -1.0)?,
141 )?;
142 accumulate_value_gradient(&mut gradients, noise.value_id(), output_gradient)?;
143 }
144 GradNode::FlowEulerStep {
145 state,
146 velocity,
147 delta_time,
148 output_id,
149 } => {
150 let Some(output_gradient) = gradients.remove(output_id) else {
151 continue;
152 };
153 accumulate_value_gradient(&mut gradients, state.value_id(), output_gradient.clone())?;
154 accumulate_value_gradient(
155 &mut gradients,
156 velocity.value_id(),
157 matrix::scale(&output_gradient, *delta_time)?,
158 )?;
159 }
160 GradNode::FlowMaskedMse {
161 prediction,
162 target,
163 mask,
164 denominator,
165 output_id,
166 } => {
167 let Some(output_gradient) = gradients.remove(output_id) else {
168 continue;
169 };
170 let prediction_gradient = flow_lowering::masked_mse_backward(
171 prediction,
172 target,
173 mask,
174 denominator,
175 &output_gradient,
176 )?;
177 accumulate_value_gradient(&mut gradients, prediction.value_id(), prediction_gradient)?;
178 }
179
180 GradNode::Linear {
181 input,
182 output_id,
183 weight,
184 weight_value,
185 bias,
186 ..
187 } => {
188 let Some(output_gradient) = gradients.remove(output_id) else {
189 continue;
190 };
191 let (input_gradient, weight_gradient, bias_gradient) =
192 ml_matrix::linear_backward(input, weight_value, &output_gradient)?;
193 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
194 weight.accumulate_gradient(weight_gradient)?;
195 if let Some(bias) = bias {
196 bias.accumulate_gradient(bias_gradient)?;
197 }
198 }
199 GradNode::Conv2d {
200 input,
201 output_id,
202 weight,
203 weight_value,
204 bias,
205 bias_value,
206 stride,
207 padding,
208 groups,
209 ..
210 } => {
211 let Some(output_gradient) = gradients.remove(output_id) else {
212 continue;
213 };
214 let (input_gradient, weight_gradient, bias_gradient) =
215 crate::ml::matrix::conv_2d_backward(
216 input,
217 weight_value,
218 &output_gradient,
219 *stride,
220 *padding,
221 *groups,
222 )?;
223 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
224 accumulate_value_gradient(
225 &mut gradients,
226 weight_value.value_id(),
227 weight_gradient.clone(),
228 )?;
229 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
230 if let Some(weight) = weight {
231 weight.accumulate_gradient(weight_gradient)?;
232 }
233 if let Some(bias) = bias {
234 bias.accumulate_gradient(bias_gradient)?;
235 }
236 }
237 GradNode::Conv3d {
238 input,
239 output_id,
240 weight,
241 weight_value,
242 bias,
243 bias_value,
244 stride,
245 padding,
246 groups,
247 ..
248 } => {
249 let Some(output_gradient) = gradients.remove(output_id) else {
250 continue;
251 };
252 let (input_gradient, weight_gradient, bias_gradient) =
253 crate::ml::matrix::conv_3d_backward(
254 input,
255 weight_value,
256 &output_gradient,
257 *stride,
258 *padding,
259 *groups,
260 )?;
261 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
262 accumulate_value_gradient(
263 &mut gradients,
264 weight_value.value_id(),
265 weight_gradient.clone(),
266 )?;
267 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
268 if let Some(weight) = weight {
269 weight.accumulate_gradient(weight_gradient)?;
270 }
271 if let Some(bias) = bias {
272 bias.accumulate_gradient(bias_gradient)?;
273 }
274 }
275 GradNode::Conv1d {
276 input,
277 output_id,
278 weight,
279 weight_value,
280 bias,
281 bias_value,
282 stride,
283 padding,
284 dilation,
285 ..
286 } => {
287 let Some(output_gradient) = gradients.remove(output_id) else {
288 continue;
289 };
290 let (input_gradient, weight_gradient, bias_gradient) =
291 crate::ml::matrix::conv_1d_backward(
292 input,
293 weight_value,
294 &output_gradient,
295 *stride,
296 *padding,
297 *dilation,
298 )?;
299 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
300 accumulate_value_gradient(
301 &mut gradients,
302 weight_value.value_id(),
303 weight_gradient.clone(),
304 )?;
305 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
306 if let Some(weight) = weight {
307 weight.accumulate_gradient(weight_gradient)?;
308 }
309 if let Some(bias) = bias {
310 bias.accumulate_gradient(bias_gradient)?;
311 }
312 }
313 GradNode::Conv1dTranspose {
314 input,
315 output_id,
316 weight,
317 weight_value,
318 stride,
319 padding,
320 dilation,
321 ..
322 } => {
323 let Some(output_gradient) = gradients.remove(output_id) else {
324 continue;
325 };
326 let (input_gradient, weight_gradient) = crate::ml::matrix::conv_1d_transpose_backward(
327 input,
328 weight_value,
329 &output_gradient,
330 *stride,
331 *padding,
332 *dilation,
333 )?;
334 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
335 accumulate_value_gradient(
336 &mut gradients,
337 weight_value.value_id(),
338 weight_gradient.clone(),
339 )?;
340 if let Some(weight) = weight {
341 weight.accumulate_gradient(weight_gradient)?;
342 }
343 }
344 GradNode::Conv2dTranspose {
345 input,
346 output_id,
347 weight,
348 weight_value,
349 bias,
350 bias_value,
351 stride,
352 padding,
353 ..
354 } => {
355 let Some(output_gradient) = gradients.remove(output_id) else {
356 continue;
357 };
358 let (input_gradient, weight_gradient, bias_gradient) =
359 crate::ml::matrix::conv_2d_transpose_backward(
360 input,
361 weight_value,
362 &output_gradient,
363 *stride,
364 *padding,
365 )?;
366 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
367 accumulate_value_gradient(
368 &mut gradients,
369 weight_value.value_id(),
370 weight_gradient.clone(),
371 )?;
372 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
373 if let Some(weight) = weight {
374 weight.accumulate_gradient(weight_gradient)?;
375 }
376 if let Some(bias) = bias {
377 bias.accumulate_gradient(bias_gradient)?;
378 }
379 }
380 GradNode::Conv3dTranspose {
381 input,
382 output_id,
383 weight,
384 weight_value,
385 bias,
386 bias_value,
387 stride,
388 padding,
389 ..
390 } => {
391 let Some(output_gradient) = gradients.remove(output_id) else {
392 continue;
393 };
394 let (input_gradient, weight_gradient, bias_gradient) =
395 crate::ml::matrix::conv_3d_transpose_backward(
396 input,
397 weight_value,
398 &output_gradient,
399 *stride,
400 *padding,
401 )?;
402 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
403 accumulate_value_gradient(
404 &mut gradients,
405 weight_value.value_id(),
406 weight_gradient.clone(),
407 )?;
408 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
409 if let Some(weight) = weight {
410 weight.accumulate_gradient(weight_gradient)?;
411 }
412 if let Some(bias) = bias {
413 bias.accumulate_gradient(bias_gradient)?;
414 }
415 }
416 GradNode::Embedding {
417 indices,
418 output_id,
419 weight,
420 weight_value,
421 ..
422 } => {
423 let Some(output_gradient) = gradients.remove(output_id) else {
424 continue;
425 };
426 let weight_gradient =
427 ml_matrix::embedding_backward(indices, &output_gradient, weight_value)?;
428 weight.accumulate_gradient(weight_gradient)?;
429 }
430 GradNode::LayerNorm {
431 input,
432 normalized,
433 inverse_stddev,
434 output_id,
435 weight,
436 weight_value,
437 bias,
438 ..
439 } => {
440 let Some(output_gradient) = gradients.remove(output_id) else {
441 continue;
442 };
443 let (input_gradient, weight_gradient, bias_gradient) = ml_matrix::layer_norm_backward(
444 input,
445 weight_value,
446 normalized,
447 inverse_stddev,
448 &output_gradient,
449 )?;
450 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
451 weight.accumulate_gradient(weight_gradient)?;
452 bias.accumulate_gradient(bias_gradient)?;
453 }
454 GradNode::BatchNorm2d {
455 input,
456 mean,
457 variance,
458 output_id,
459 weight,
460 weight_value,
461 bias,
462 bias_value,
463 epsilon,
464 training,
465 ..
466 } => {
467 let Some(output_gradient) = gradients.remove(output_id) else {
468 continue;
469 };
470 let (input_gradient, weight_gradient, bias_gradient) =
471 crate::ml::matrix::batch_norm_2d_backward(
472 input,
473 weight_value,
474 mean,
475 variance,
476 &output_gradient,
477 *epsilon,
478 *training,
479 )?;
480 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
481 accumulate_value_gradient(
482 &mut gradients,
483 weight_value.value_id(),
484 weight_gradient.clone(),
485 )?;
486 accumulate_value_gradient(&mut gradients, bias_value.value_id(), bias_gradient.clone())?;
487 if let Some(weight) = weight {
488 weight.accumulate_gradient(weight_gradient)?;
489 }
490 if let Some(bias) = bias {
491 bias.accumulate_gradient(bias_gradient)?;
492 }
493 }
494 GradNode::RmsNorm {
495 input,
496 output_id,
497 weight,
498 weight_value,
499 epsilon,
500 ..
501 } => {
502 let Some(output_gradient) = gradients.remove(output_id) else {
503 continue;
504 };
505 let (input_gradient, weight_gradient) =
506 ml_matrix::rms_norm_backward(input, weight_value, &output_gradient, *epsilon)?;
507 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
508 accumulate_value_gradient(
509 &mut gradients,
510 weight_value.value_id(),
511 weight_gradient.clone(),
512 )?;
513 if let Some(weight) = weight {
514 weight.accumulate_gradient(weight_gradient)?;
515 }
516 }
517 GradNode::RmsNormGated(node) => {
518 let Some(output_gradient) = gradients.remove(&node.output_id) else {
519 continue;
520 };
521 let result = ml_matrix::rms_norm_gated_backward(
522 &node.input,
523 &node.weight_value,
524 node.bias_value.as_ref(),
525 &node.gate,
526 &output_gradient,
527 node.epsilon,
528 )?;
529 accumulate_value_gradient(&mut gradients, node.input.value_id(), result.input)?;
530 accumulate_value_gradient(
531 &mut gradients,
532 node.weight_value.value_id(),
533 result.weight.clone(),
534 )?;
535 accumulate_value_gradient(&mut gradients, node.gate.value_id(), result.gate)?;
536 if let Some(weight) = &node.weight {
537 weight.accumulate_gradient(result.weight)?;
538 }
539 if let (Some(bias_value), Some(bias_gradient)) = (&node.bias_value, result.bias) {
540 accumulate_value_gradient(
541 &mut gradients,
542 bias_value.value_id(),
543 bias_gradient.clone(),
544 )?;
545 if let Some(bias) = &node.bias {
546 bias.accumulate_gradient(bias_gradient)?;
547 }
548 }
549 }
550 GradNode::ChannelNorm(node) => {
551 let Some(output_gradient) = gradients.remove(&node.output_id) else {
552 continue;
553 };
554 let result = ml_matrix::channel_norm_backward_saved(
555 &node.input,
556 &node.weight_value,
557 node.output.as_ref(),
558 &output_gradient,
559 node.epsilon,
560 )?;
561 accumulate_value_gradient(&mut gradients, node.input.value_id(), result.input)?;
562 accumulate_value_gradient(
563 &mut gradients,
564 node.weight_value.value_id(),
565 result.weight.clone(),
566 )?;
567 accumulate_value_gradient(
568 &mut gradients,
569 node.bias_value.value_id(),
570 result.bias.clone(),
571 )?;
572 if let Some(weight) = &node.weight {
573 weight.accumulate_gradient(result.weight)?;
574 }
575 if let Some(bias) = &node.bias {
576 bias.accumulate_gradient(result.bias)?;
577 }
578 }
579
580 GradNode::Bmm {
581 left,
582 right,
583 output_id,
584 } => {
585 let Some(output_gradient) = gradients.remove(output_id) else {
586 continue;
587 };
588 let left_gradient = ml_matrix::bmm_nt(&output_gradient, right)?;
589 let right_gradient = ml_matrix::bmm_tn(left, &output_gradient)?;
590 accumulate_value_gradient(&mut gradients, left.value_id(), left_gradient)?;
591 accumulate_value_gradient(&mut gradients, right.value_id(), right_gradient)?;
592 }
593 GradNode::BmmNt {
594 left,
595 right,
596 output_id,
597 } => {
598 let Some(output_gradient) = gradients.remove(output_id) else {
599 continue;
600 };
601 let left_gradient = ml_matrix::bmm(&output_gradient, right)?;
602 let right_gradient = ml_matrix::bmm_tn(&output_gradient, left)?;
603 accumulate_value_gradient(&mut gradients, left.value_id(), left_gradient)?;
604 accumulate_value_gradient(&mut gradients, right.value_id(), right_gradient)?;
605 }
606 GradNode::BmmTn {
607 left,
608 right,
609 output_id,
610 } => {
611 let Some(output_gradient) = gradients.remove(output_id) else {
612 continue;
613 };
614 let left_gradient = ml_matrix::bmm_nt(right, &output_gradient)?;
615 let right_gradient = ml_matrix::bmm(left, &output_gradient)?;
616 accumulate_value_gradient(&mut gradients, left.value_id(), left_gradient)?;
617 accumulate_value_gradient(&mut gradients, right.value_id(), right_gradient)?;
618 }
619 GradNode::SplitHeads {
620 input,
621 output_id,
622 batch,
623 sequence_length,
624 num_heads,
625 } => {
626 let Some(output_gradient) = gradients.remove(output_id) else {
627 continue;
628 };
629 let (input_gradient, _) = ml_matrix::merge_heads_dispatch(
630 &output_gradient,
631 *batch,
632 *sequence_length,
633 *num_heads,
634 )?;
635 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
636 }
637 GradNode::MergeHeads {
638 input,
639 output_id,
640 batch,
641 sequence_length,
642 num_heads,
643 } => {
644 let Some(output_gradient) = gradients.remove(output_id) else {
645 continue;
646 };
647 let (input_gradient, _) = ml_matrix::split_heads_dispatch(
648 &output_gradient,
649 *batch,
650 *sequence_length,
651 *num_heads,
652 )?;
653 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
654 }
655 GradNode::SoftmaxScaledMasked {
656 input,
657 output,
658 output_id,
659 scale,
660 } => {
661 let Some(output_gradient) = gradients.remove(output_id) else {
662 continue;
663 };
664 let input_gradient =
665 ml_matrix::softmax_scaled_masked_backward(output, &output_gradient, *scale)?;
666 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
667 }
668 GradNode::ScaledDotProductAttention {
669 query,
670 key,
671 value,
672 probabilities,
673 output_id,
674 scale,
675 } => {
676 let Some(output_gradient) = gradients.remove(output_id) else {
677 continue;
678 };
679 let probability_gradient = ml_matrix::bmm_nt(&output_gradient, value)?;
680 let [batch_heads, sequence_length, _] = probabilities.shape() else {
681 return Err(Error::internal(
682 "saved SDPA probabilities lost rank-three shape",
683 ));
684 };
685 let rows = batch_heads
686 .checked_mul(*sequence_length)
687 .ok_or_else(|| Error::internal("saved SDPA probability rows overflow usize"))?;
688 let score_gradient = ml_matrix::softmax_scaled_masked_backward(
689 &probabilities.reshape([rows, *sequence_length])?,
690 &probability_gradient.reshape([rows, *sequence_length])?,
691 *scale,
692 )?
693 .reshape([*batch_heads, *sequence_length, *sequence_length])?;
694 let query_gradient = ml_matrix::bmm(&score_gradient, key)?;
695 let key_gradient = ml_matrix::bmm_tn(&score_gradient, query)?;
696 let value_gradient = ml_matrix::bmm_tn(probabilities, &output_gradient)?;
697 accumulate_value_gradient(&mut gradients, query.value_id(), query_gradient)?;
698 accumulate_value_gradient(&mut gradients, key.value_id(), key_gradient)?;
699 accumulate_value_gradient(&mut gradients, value.value_id(), value_gradient)?;
700 }
701 GradNode::LinearAttention(node) => {
702 let Some(output_gradient) = gradients.remove(&node.output.value_id()) else {
703 continue;
704 };
705 let (dq, dk, dv) = ml_matrix::causal_linear_attention_backward(
706 &node.query,
707 &node.key,
708 &node.value,
709 &node.output,
710 &node.denominator,
711 &output_gradient,
712 node.epsilon,
713 )?;
714 accumulate_value_gradient(&mut gradients, node.query.value_id(), dq)?;
715 accumulate_value_gradient(&mut gradients, node.key.value_id(), dk)?;
716 accumulate_value_gradient(&mut gradients, node.value.value_id(), dv)?;
717 }
718 GradNode::FlashAttention {
719 query,
720 key,
721 value,
722 output,
723 log_sum_exp,
724 output_id,
725 scale,
726 } => {
727 let Some(output_gradient) = gradients.remove(output_id) else {
728 continue;
729 };
730 let (query_grad, key_grad, value_grad) = ml_matrix::flash_attention_causal_backward(
731 query,
732 key,
733 value,
734 output,
735 log_sum_exp,
736 &output_gradient,
737 *scale,
738 )?;
739 accumulate_value_gradient(&mut gradients, query.value_id(), query_grad)?;
740 accumulate_value_gradient(&mut gradients, key.value_id(), key_grad)?;
741 accumulate_value_gradient(&mut gradients, value.value_id(), value_grad)?;
742 }
743 GradNode::MoeRouteWeights {
744 probabilities,
745 expert_indices,
746 output,
747 output_id,
748 } => {
749 let Some(output_gradient) = gradients.remove(output_id) else {
750 continue;
751 };
752 let probability_gradient = crate::ml::matrix::moe_route_weights_backward(
753 &output_gradient,
754 probabilities,
755 expert_indices,
756 output,
757 )?;
758 accumulate_value_gradient(
759 &mut gradients,
760 probabilities.value_id(),
761 probability_gradient,
762 )?;
763 }
764 GradNode::MoeGather {
765 input,
766 inverse,
767 output_id,
768 } => {
769 let Some(output_gradient) = gradients.remove(output_id) else {
770 continue;
771 };
772 let input_gradient =
773 crate::ml::matrix::moe_gather_backward(&output_gradient, inverse, input.shape()[0])?;
774 accumulate_value_gradient(&mut gradients, input.value_id(), input_gradient)?;
775 }
776 GradNode::MoeCombine {
777 packed,
778 route_gate,
779 inverse,
780 packed_slot,
781 output_id,
782 } => {
783 let Some(output_gradient) = gradients.remove(output_id) else {
784 continue;
785 };
786 let result = crate::ml::matrix::moe_combine_backward(
787 &output_gradient,
788 packed,
789 route_gate,
790 inverse,
791 packed_slot,
792 )?;
793 accumulate_value_gradient(&mut gradients, packed.value_id(), result.packed)?;
794 accumulate_value_gradient(&mut gradients, route_gate.value_id(), result.route_gate)?;
795 }
796 GradNode::GroupedGemmM {
797 input,
798 weight,
799 weight_value,
800 offsets,
801 output_id,
802 ..
803 } => {
804 let Some(output_gradient) = gradients.remove(output_id) else {
805 continue;
806 };
807 let result = crate::ml::matrix::grouped_gemm_m_backward(
808 &output_gradient,
809 input,
810 weight_value,
811 offsets,
812 )?;
813 accumulate_value_gradient(&mut gradients, input.value_id(), result.input)?;
814 accumulate_value_gradient(
815 &mut gradients,
816 weight_value.value_id(),
817 result.weight.clone(),
818 )?;
819 if let Some(weight) = weight {
820 weight.accumulate_gradient(result.weight)?;
821 }
822 }
823 GradNode::GroupedLinearM {
824 input,
825 weight,
826 weight_value,
827 bias,
828 bias_value,
829 offsets,
830 output_id,
831 ..
832 } => {
833 let Some(output_gradient) = gradients.remove(output_id) else {
834 continue;
835 };
836 let result = crate::ml::matrix::grouped_linear_m_backward(
837 &output_gradient,
838 input,
839 weight_value,
840 offsets,
841 )?;
842 accumulate_value_gradient(&mut gradients, input.value_id(), result.input)?;
843 accumulate_value_gradient(
844 &mut gradients,
845 weight_value.value_id(),
846 result.weight.clone(),
847 )?;
848 accumulate_value_gradient(&mut gradients, bias_value.value_id(), result.bias.clone())?;
849 if let Some(weight) = weight {
850 weight.accumulate_gradient(result.weight)?;
851 }
852 if let Some(bias) = bias {
853 bias.accumulate_gradient(result.bias)?;
854 }
855 }
856 GradNode::Mamba3Siso(node) => {
857 let Some(output_gradient) = gradients.remove(&node.output_id) else {
858 continue;
859 };
860 let result = crate::ml::matrix::mamba3_siso_backward(
861 &output_gradient,
862 &node.c,
863 &node.b,
864 &node.x,
865 &node.z,
866 &node.adt,
867 &node.dt,
868 &node.trap,
869 &node.angle,
870 &node.c_bias,
871 &node.b_bias,
872 &node.d,
873 node.config,
874 )?;
875 for (input, gradient) in [
876 (&node.c, result.c),
877 (&node.b, result.b),
878 (&node.x, result.x),
879 (&node.z, result.z),
880 (&node.adt, result.adt),
881 (&node.dt, result.dt),
882 (&node.trap, result.trap),
883 (&node.angle, result.angle),
884 (&node.c_bias, result.c_bias),
885 (&node.b_bias, result.b_bias),
886 (&node.d, result.d),
887 ] {
888 accumulate_value_gradient(&mut gradients, input.value_id(), gradient)?;
889 }
890 }
891 GradNode::Mamba3Mimo(node) => {
892 let Some(output_gradient) = gradients.remove(&node.output_id) else {
893 continue;
894 };
895 let [
896 c,
897 b,
898 x,
899 z,
900 adt,
901 dt,
902 trap,
903 angle,
904 c_bias,
905 b_bias,
906 d,
907 mimo_x,
908 mimo_z,
909 mimo_o,
910 norm_weight,
911 ] = &node.inputs;
912 let result = crate::ml::matrix::mamba3_mimo_backward(
913 &output_gradient,
914 c,
915 b,
916 x,
917 z,
918 adt,
919 dt,
920 trap,
921 angle,
922 c_bias,
923 b_bias,
924 d,
925 mimo_x,
926 mimo_z,
927 mimo_o,
928 norm_weight,
929 node.config,
930 )?;
931 for (input, gradient) in node.inputs.iter().zip([
932 result.c,
933 result.b,
934 result.x,
935 result.z,
936 result.adt,
937 result.dt,
938 result.trap,
939 result.angle,
940 result.c_bias,
941 result.b_bias,
942 result.d,
943 result.mimo_x,
944 result.mimo_z,
945 result.mimo_o,
946 result.norm_weight,
947 ]) {
948 accumulate_value_gradient(&mut gradients, input.value_id(), gradient)?;
949 }
950 }
951 GradNode::Mamba3Preprocess(node) => {
952 let output_gradients = crate::ml::matrix::Mamba3PreprocessResult {
953 x: take_or_zero_gradient(&mut gradients, &node.outputs[0])?,
954 z: take_or_zero_gradient(&mut gradients, &node.outputs[1])?,
955 bh: take_or_zero_gradient(&mut gradients, &node.outputs[2])?,
956 ch: take_or_zero_gradient(&mut gradients, &node.outputs[3])?,
957 dt: take_or_zero_gradient(&mut gradients, &node.outputs[4])?,
958 adt: take_or_zero_gradient(&mut gradients, &node.outputs[5])?,
959 trap: take_or_zero_gradient(&mut gradients, &node.outputs[6])?,
960 angle: take_or_zero_gradient(&mut gradients, &node.outputs[7])?,
961 };
962 let result = crate::ml::matrix::mamba3_preprocess_backward(
963 &node.projected,
964 &node.dt_bias,
965 &output_gradients,
966 node.config,
967 )?;
968 accumulate_value_gradient(&mut gradients, node.projected.value_id(), result.projected)?;
969 accumulate_value_gradient(&mut gradients, node.dt_bias.value_id(), result.dt_bias)?;
970 }
971 GradNode::RnnScan(node) => {
972 let Some(output_gradient) = gradients.remove(&node.output_id) else {
973 continue;
974 };
975 let (gates_i_gradient, weight_gradient, bias_gradient) =
976 crate::ml::matrix::rnn_scan_backward(
977 &output_gradient,
978 &node.gates_i,
979 &node.hidden_previous,
980 &node.weight_value,
981 &node.bias_value,
982 node.has_bias,
983 )?;
984 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
985 accumulate_value_gradient(
986 &mut gradients,
987 node.weight_value.value_id(),
988 weight_gradient.clone(),
989 )?;
990 if node.has_bias {
991 accumulate_value_gradient(
992 &mut gradients,
993 node.bias_value.value_id(),
994 bias_gradient.clone(),
995 )?;
996 }
997 if let Some(weight) = &node.weight {
998 weight.accumulate_gradient(weight_gradient)?;
999 }
1000 if let Some(bias) = &node.bias {
1001 bias.accumulate_gradient(bias_gradient)?;
1002 }
1003 }
1004 GradNode::RnnCell(node) => {
1005 let Some(output_gradient) = gradients.remove(&node.output_id) else {
1006 continue;
1007 };
1008 let (gates_i_gradient, hidden_gradient, weight_gradient, bias_gradient) =
1009 crate::ml::matrix::rnn_cell_backward(
1010 &node.gates_i,
1011 &node.gates_h,
1012 &node.hidden,
1013 &output_gradient,
1014 &node.weight_value,
1015 &node.bias_value,
1016 node.has_bias,
1017 )?;
1018 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
1019 accumulate_value_gradient(&mut gradients, node.hidden.value_id(), hidden_gradient)?;
1020 accumulate_value_gradient(
1021 &mut gradients,
1022 node.weight_value.value_id(),
1023 weight_gradient.clone(),
1024 )?;
1025 if node.has_bias {
1026 accumulate_value_gradient(
1027 &mut gradients,
1028 node.bias_value.value_id(),
1029 bias_gradient.clone(),
1030 )?;
1031 }
1032 if let Some(weight) = &node.weight {
1033 weight.accumulate_gradient(weight_gradient)?;
1034 }
1035 if let Some(bias) = &node.bias {
1036 bias.accumulate_gradient(bias_gradient)?;
1037 }
1038 }
1039 GradNode::GruScan(node) => {
1040 let Some(output_gradient) = gradients.remove(&node.output_id) else {
1041 continue;
1042 };
1043 let (gates_i_gradient, weight_gradient, bias_gradient) =
1044 crate::ml::matrix::gru_scan_backward(
1045 &output_gradient,
1046 &node.gates_i,
1047 &node.hidden_previous,
1048 &node.weight_value,
1049 &node.bias_value,
1050 node.has_bias,
1051 )?;
1052 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
1053 accumulate_value_gradient(
1054 &mut gradients,
1055 node.weight_value.value_id(),
1056 weight_gradient.clone(),
1057 )?;
1058 if node.has_bias {
1059 accumulate_value_gradient(
1060 &mut gradients,
1061 node.bias_value.value_id(),
1062 bias_gradient.clone(),
1063 )?;
1064 }
1065 if let Some(weight) = &node.weight {
1066 weight.accumulate_gradient(weight_gradient)?;
1067 }
1068 if let Some(bias) = &node.bias {
1069 bias.accumulate_gradient(bias_gradient)?;
1070 }
1071 }
1072 GradNode::GruCell(node) => {
1073 let Some(output_gradient) = gradients.remove(&node.output_id) else {
1074 continue;
1075 };
1076 let (gates_i_gradient, hidden_gradient, weight_gradient, bias_gradient) =
1077 crate::ml::matrix::gru_cell_backward(
1078 &node.gates_i,
1079 &node.gates_h,
1080 &node.hidden,
1081 &output_gradient,
1082 &node.weight_value,
1083 &node.bias_value,
1084 node.has_bias,
1085 )?;
1086 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
1087 accumulate_value_gradient(&mut gradients, node.hidden.value_id(), hidden_gradient)?;
1088 accumulate_value_gradient(
1089 &mut gradients,
1090 node.weight_value.value_id(),
1091 weight_gradient.clone(),
1092 )?;
1093 if node.has_bias {
1094 accumulate_value_gradient(
1095 &mut gradients,
1096 node.bias_value.value_id(),
1097 bias_gradient.clone(),
1098 )?;
1099 }
1100 if let Some(weight) = &node.weight {
1101 weight.accumulate_gradient(weight_gradient)?;
1102 }
1103 if let Some(bias) = &node.bias {
1104 bias.accumulate_gradient(bias_gradient)?;
1105 }
1106 }
1107 GradNode::LstmScan(node) => {
1108 let Some(output_gradient) = gradients.remove(&node.output_id) else {
1109 continue;
1110 };
1111 let (gates_i_gradient, weight_gradient, bias_gradient) =
1112 crate::ml::matrix::lstm_scan_backward(
1113 &output_gradient,
1114 &node.gates_i,
1115 &node.hidden_previous,
1116 &node.cell_previous,
1117 &node.cell_state,
1118 &node.weight_value,
1119 &node.bias_value,
1120 node.has_bias,
1121 )?;
1122 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
1123 accumulate_value_gradient(
1124 &mut gradients,
1125 node.weight_value.value_id(),
1126 weight_gradient.clone(),
1127 )?;
1128 if node.has_bias {
1129 accumulate_value_gradient(
1130 &mut gradients,
1131 node.bias_value.value_id(),
1132 bias_gradient.clone(),
1133 )?;
1134 }
1135 if let Some(weight) = &node.weight {
1136 weight.accumulate_gradient(weight_gradient)?;
1137 }
1138 if let Some(bias) = &node.bias {
1139 bias.accumulate_gradient(bias_gradient)?;
1140 }
1141 }
1142 GradNode::LstmCell(node) => {
1143 let hidden_gradient = gradients.remove(&node.output_id);
1144 let cell_gradient = gradients.remove(&node.cell_next_id);
1145 if hidden_gradient.is_none() && cell_gradient.is_none() {
1146 continue;
1147 }
1148 let hidden_gradient = match hidden_gradient {
1149 Some(gradient) => gradient,
1150 None => Matrix::new_from_slice_handle(
1151 node.hidden.runtime(),
1152 node.hidden.shape().to_vec(),
1153 &vec![0.0_f32; node.hidden.element_count()],
1154 )?,
1155 };
1156 let cell_gradient = match cell_gradient {
1157 Some(gradient) => gradient,
1158 None => Matrix::new_from_slice_handle(
1159 node.cell.runtime(),
1160 node.cell.shape().to_vec(),
1161 &vec![0.0_f32; node.cell.element_count()],
1162 )?,
1163 };
1164 let (
1165 gates_i_gradient,
1166 hidden_state_gradient,
1167 cell_state_gradient,
1168 weight_gradient,
1169 bias_gradient,
1170 ) = crate::ml::matrix::lstm_cell_backward(
1171 &node.gates_i,
1172 &node.gates_h,
1173 &node.hidden,
1174 &node.cell,
1175 &hidden_gradient,
1176 &cell_gradient,
1177 &node.weight_value,
1178 &node.bias_value,
1179 node.has_bias,
1180 )?;
1181 accumulate_value_gradient(&mut gradients, node.gates_i.value_id(), gates_i_gradient)?;
1182 accumulate_value_gradient(
1183 &mut gradients,
1184 node.hidden.value_id(),
1185 hidden_state_gradient,
1186 )?;
1187 accumulate_value_gradient(&mut gradients, node.cell.value_id(), cell_state_gradient)?;
1188 accumulate_value_gradient(
1189 &mut gradients,
1190 node.weight_value.value_id(),
1191 weight_gradient.clone(),
1192 )?;
1193 if node.has_bias {
1194 accumulate_value_gradient(
1195 &mut gradients,
1196 node.bias_value.value_id(),
1197 bias_gradient.clone(),
1198 )?;
1199 }
1200 if let Some(weight) = &node.weight {
1201 weight.accumulate_gradient(weight_gradient)?;
1202 }
1203 if let Some(bias) = &node.bias {
1204 bias.accumulate_gradient(bias_gradient)?;
1205 }
1206 }
1207 }
1208 if let Some((forward, generation)) = attachment {
1209 runtime.complete_semantic_autograd(forward, entry.sequence, generation, backward_first)?;
1210 }
1211 }
1212 for watched in self.recording.watched_parameters.borrow().iter() {
1213 if let Some(gradient) = gradients.remove(&watched.data_id) {
1214 watched.parameter.accumulate_gradient(gradient)?;
1215 }
1216 }
1217 Ok(())
1218 }
1219}
1220
1221fn reached_output_id(node: &GradNode, gradients: &HashMap<u64, Matrix>) -> Option<u64> {
1222 match node {
1223 GradNode::Mamba3Preprocess(node) => node
1224 .outputs
1225 .iter()
1226 .map(Matrix::value_id)
1227 .find(|output_id| gradients.contains_key(output_id)),
1228 GradNode::LstmCell(node) => [node.output_id, node.cell_next_id]
1229 .into_iter()
1230 .find(|output_id| gradients.contains_key(output_id)),
1231 _ => gradients
1232 .contains_key(&node.output_id())
1233 .then(|| node.output_id()),
1234 }
1235}
1236
1237fn take_or_zero_gradient(gradients: &mut HashMap<u64, Matrix>, output: &Matrix) -> Result<Matrix> {
1238 if let Some(gradient) = gradients.remove(&output.value_id()) {
1239 return Ok(gradient);
1240 }
1241 Matrix::new_from_slice_handle(
1242 output.runtime(),
1243 output.shape().to_vec(),
1244 &vec![0.0_f32; output.element_count()],
1245 )
1246}
1247
1248pub(in crate::ml::autograd) fn accumulate_value_gradient(
1249 gradients: &mut HashMap<u64, Matrix>,
1250 value_id: u64,
1251 gradient: Matrix,
1252) -> Result<()> {
1253 if let Some(previous) = gradients.remove(&value_id) {
1254 gradients.insert(value_id, matrix::add(&previous, &gradient)?);
1255 } else {
1256 gradients.insert(value_id, gradient);
1257 }
1258 Ok(())
1259}
1260
1261fn sum_to_flow_time_shape(
1262 gradient: &Matrix,
1263 time_shape: &[usize],
1264 state_shape: &[usize],
1265) -> Result<Matrix> {
1266 if time_shape.len() == 1
1267 && state_shape.len() > 1
1268 && time_shape[0] != 1
1269 && time_shape[0] == state_shape[0]
1270 {
1271 let mut result = gradient.clone();
1272 for axis in 1..state_shape.len() {
1273 result = matrix::sum(
1274 &result,
1275 i32::try_from(axis).map_err(|_| Error::internal("flow time adjoint axis exceeds i32"))?,
1276 )?;
1277 }
1278 return result.reshape(time_shape.to_vec());
1279 }
1280 sum_to_shape(gradient, time_shape)
1281}
1282
1283struct MatrixGradients<'a>(&'a mut HashMap<u64, Matrix>);
1285
1286impl GradientContext for MatrixGradients<'_> {
1287 fn take_output(&mut self, output_id: u64) -> Option<Matrix> {
1288 self.0.remove(&output_id)
1289 }
1290 fn accumulate(&mut self, value_id: u64, gradient: Matrix) -> Result<()> {
1291 accumulate_value_gradient(self.0, value_id, gradient)
1292 }
1293}