def net_fn(params, X, dtype):
h = X.reshape(X.shape[0], -1).astype(dtype)
for W in params[:-1]:
h = jax.nn.relu(h @ W.astype(dtype))
return h @ params[-1].astype(dtype)
key = jax.random.PRNGKey(0)
sizes = [(64 * 64, 8192), (8192, 8192), (8192, 10)]
params = [jax.random.normal(k, s) * 0.02
for k, s in zip(jax.random.split(key, 3), sizes)]
X = jax.random.normal(key, (2048, 64 * 64))
def loss_fn(params, dtype):
return (net_fn(params, X, dtype) ** 2).sum()
grad_fn = jax.jit(jax.grad(loss_fn), static_argnums=1)
with jax.default_matmul_precision('highest'): # Unfair baseline: tf32 off
print(d2l.Benchmark(lambda: grad_fn(params, jnp.float32),
desc='fp32 (tf32 off)'))
# The default on this card is tf32-class compute -- the fair baseline
print(d2l.Benchmark(lambda: grad_fn(params, jnp.float32), desc='tf32'))
print(d2l.Benchmark(lambda: grad_fn(params, jnp.bfloat16), desc='bf16'))