net = nn.Sequential(nn.Flatten(),
nn.Linear(64 * 64, 8192), nn.ReLU(),
nn.Linear(8192, 8192), nn.ReLU(),
nn.Linear(8192, 10)).to(gpu)
X = torch.randn(2048, 1, 64, 64, device=gpu)
y = torch.randint(0, 10, (2048,), device=gpu)
opt = torch.optim.SGD(net.parameters(), lr=0.01)
loss = nn.CrossEntropyLoss()
def step(autocast, dtype=None):
opt.zero_grad(set_to_none=True)
if autocast:
with torch.autocast('cuda', dtype=dtype):
l = loss(net(X), y)
else:
l = loss(net(X), y)
l.backward(); opt.step()
torch.set_float32_matmul_precision('highest') # Unfair baseline: tf32 off
print(d2l.Benchmark(lambda: step(False), desc='fp32 (tf32 off)'))
torch.set_float32_matmul_precision('high') # Fair baseline: tf32 on
print(d2l.Benchmark(lambda: step(False), desc='tf32'))
print(d2l.Benchmark(lambda: step(True, torch.bfloat16), desc='bf16 autocast'))