29/31
Part 6 of 6 · What interviewers ask nextLearn and do

Mixed precision needs two decorators

The last follow-up is precision.

What runsThe result
Forward, under autocasta @ b runs in bf16y is bf16
Backward, no decoratorgrad_out bf16 @ b fp32a dtype error
Backward, with custom_bwdthe same autocast state as forwardruns

Under autocast, PyTorch's switch that runs matmuls in 16-bit floats, your forward's a @ b comes out in 16 bits. Your backward runs outside the autocast region, though. Two decorators fix it:

class MatMul(torch.autograd.Function):
    @staticmethod
    @torch.amp.custom_fwd(device_type="cuda")
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        ...

    @staticmethod
    @torch.amp.custom_bwd(device_type="cuda")
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        ...

With them, both gradient matmuls run in half precision. The engine casts each returned gradient to its input's dtype, so fp32 weights still get an fp32 .grad.

Predict

fp16 has one more hazard. What does it store for a gradient of 1e-8?

Pick an answer above to see the rest