Oh, that’s a neat trick. For some reason the gradient calculation is wrong though. The gradient should be [5., 7.] in this example, but this returns [12., 18.].
Edit: I think was able to determine the source of the problem. For the entirety of the backward pass, the index t is taken to be its last value in the for loop (i.e., 2 in this example). This results in the miscalculated gradient. Is there a way to rewrite this example so the correct gradient is calculated?