16/31
Part 4 of 6 · A Function of your ownLearn and do

ctx carries tensors from forward to backward

Tensors go in through ctx.save_for_backward(...) and come back out of ctx.saved_tensors. The PyTorch docs ask for this route for every tensor that backward uses: it prevents wrong gradients and memory leaks.

Saving copies nothing. It keeps the tensor alive until backward has run.

Non-tensors, like an int or a float, go straight onto ctx as attributes: ctx.scale = scale.

The stub puts ctx in forward, the older of two styles. Since PyTorch 2.0 you can also write a forward without ctx, plus a separate setup_context(ctx, inputs, output) that does the saving. The docs recommend that style. The math is the same in both styles.

needs_input_grad skips a gradient nobody wants

In a first layer, a is raw data and b is the weight.

Predict

ctx.needs_input_grad holds one True or False per input, in order. What is it in a first layer?

Pick an answer above to see the rest