29/31
Part 6 of 6 · What interviewers ask nextLearn and do
Mixed precision needs two decorators
The last follow-up is precision.
| What runs | The result | |
|---|---|---|
| Forward, under autocast | a @ b runs in bf16 | y is bf16 |
| Backward, no decorator | grad_out bf16 @ b fp32 | a dtype error |
Backward, with custom_bwd | the same autocast state as forward | runs |
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.
fp16 has one more hazard. What does it store for a gradient of 1e-8?
Pick an answer above to see the rest