%matplotlib inline
import os
from d2l import jax as d2l
from d2l.nnx_resnet import ResNet50, Bottleneck
from flax import nnx
import jax
from jax import numpy as jnp
import optax
import numpy as np
import tensorflow as tf # only used for tf.data input pipeline
# Activation (gradient) checkpointing. Fine-tuning ResNet-50 at batch size 128
# would otherwise hold the whole forward graph's activations live for the
# backward pass (~23 GB). Wrapping each residual block (`Bottleneck`) in
# `nnx.remat` recomputes that block's activations during backprop instead of
# storing them, cutting the peak to ~6 GB. `nnx.remat` propagates state
# correctly, so gradients and batch-norm running statistics are identical to
# the un-checkpointed model.
if not getattr(Bottleneck, '_d2l_remat', False):
Bottleneck.__call__ = nnx.remat(Bottleneck.__call__)
Bottleneck._d2l_remat = True