{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-1 fw=all -->\n",
    "\n",
    "# Normalization Layers\n",
    "\n",
    "Training deep neural networks is difficult.\n",
    "Getting them to converge in a reasonable amount of time can be tricky.\n",
    "In this section, we describe *batch normalization*, a popular and effective technique\n",
    "that consistently accelerates the convergence of deep networks [@Ioffe.Szegedy.2015].\n",
    "Together with residual blocks---covered later in that section --- batch normalization\n",
    "has made it possible for practitioners to routinely train networks with over 100 layers.\n",
    "A secondary (serendipitous) benefit of batch normalization lies in its inherent regularization.\n",
    "Batch statistics are not the only option, though: we also cover layer normalization\n",
    "and group normalization, close cousins that normalize each example on its own."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-batch-normalization"
   },
   "source": [
    "from d2l import jax as d2l\n",
    "from flax import nnx\n",
    "from jax import numpy as jnp\n",
    "import jax"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-2 fw=all -->\n",
    "\n",
    "## Training Deep Networks\n",
    "\n",
    "When working with data, we often preprocess before training.\n",
    "Choices regarding data preprocessing often make an enormous difference in the final results.\n",
    "Recall our application of MLPs to predicting house prices (that section).\n",
    "Our first step when working with real data\n",
    "was to standardize each input feature to have zero mean and unit marginal\n",
    "variance across observations. In vector notation, the mean is\n",
    "$\\boldsymbol{\\mu}=\\boldsymbol{0}$ and the covariance has unit diagonal,\n",
    "$\\Sigma_{ii}=1$; its off-diagonal entries need not vanish\n",
    "[@friedman1987exploratory].\n",
    "Yet another strategy is to rescale vectors to unit length, possibly zero mean *per observation*.\n",
    "This can work well, e.g., for spatial sensor data. These preprocessing techniques and many others, are\n",
    "beneficial for keeping the estimation problem well controlled. \n",
    "For a review of feature selection and extraction see the article of @guyon2008feature, for example.\n",
    "Standardizing vectors also has the nice side-effect of constraining the function complexity of functions that act upon it. For instance, the celebrated radius-margin bound [@Vapnik95] in support vector machines and the Perceptron Convergence Theorem [@Novikoff62] rely on inputs of bounded norm. \n",
    "\n",
    "Intuitively, this standardization plays nicely with our optimizers\n",
    "since it puts the parameters *a priori* on a similar scale.\n",
    "As such, it is only natural to ask whether a corresponding normalization step *inside* a deep network\n",
    "might not be beneficial. While this is not quite the reasoning that led to the invention of batch normalization [@Ioffe.Szegedy.2015], it is a useful way of understanding it and its cousin, layer normalization [@Ba.Kiros.Hinton.2016], within a unified framework.\n",
    "\n",
    "Second, for a typical MLP or CNN, as we train,\n",
    "the variables \n",
    "in intermediate layers (e.g., affine transformation outputs in MLP)\n",
    "may take values with widely varying magnitudes:\n",
    "whether along the layers from input to output, across units in the same layer,\n",
    "and over time due to our updates to the model parameters.\n",
    "The inventors of batch normalization postulated informally\n",
    "that this drift in the distribution of such variables could hamper the convergence of the network.\n",
    "Intuitively, we might conjecture that if one\n",
    "layer has variable activations that are 100 times that of another layer,\n",
    "this might necessitate compensatory adjustments in the learning rates. Adaptive solvers\n",
    "such as AdaGrad [@Duchi.Hazan.Singer.2011], Adam [@Kingma.Ba.2014], Yogi [@Zaheer.Reddi.Sachan.ea.2018], or Distributed Shampoo [@anil2020scalable] aim to address this from the viewpoint of optimization, e.g., by adding aspects of second-order methods. \n",
    "The alternative is to prevent the problem from occurring, simply by adaptive normalization.\n",
    "\n",
    "Third, deeper networks are complex and tend to be more liable to overfitting.\n",
    "This means that regularization becomes more critical. A common technique for regularization is noise\n",
    "injection. This has been known for a long time, e.g., with regard to noise injection for the\n",
    "inputs [@Bishop.1995]. It also forms the basis of dropout in that section. As it turns out, quite serendipitously, batch normalization conveys all three benefits: preprocessing, numerical stability, and regularization.\n",
    "\n",
    "Batch normalization is applied to individual layers, or optionally, to all of them:\n",
    "In each training iteration,\n",
    "we first normalize the inputs (of batch normalization)\n",
    "by subtracting their mean and\n",
    "dividing by their standard deviation,\n",
    "where both are estimated based on the statistics of the current minibatch.\n",
    "Next, we apply a scale coefficient and an offset to recover the lost degrees\n",
    "of freedom. It is precisely due to this *normalization* based on *batch* statistics\n",
    "that *batch normalization* derives its name.\n",
    "\n",
    "For a fully connected activation normalized only across examples, a minibatch\n",
    "of size 1 removes all input-dependent signal: after subtracting the mean, every\n",
    "normalized feature is 0. The shift parameter and later biases can still learn,\n",
    "but the normalized feature cannot convey how that example differs from another.\n",
    "As you might guess, since we are devoting a whole section to batch normalization,\n",
    "with large enough minibatches the approach proves effective and stable.\n",
    "One takeaway here is that when applying batch normalization,\n",
    "the choice of batch size affects both the noise in the statistics and the\n",
    "resulting optimization behavior.\n",
    "\n",
    "Denote by $\\mathcal{B}$ a minibatch and let $\\mathbf{x} \\in \\mathcal{B}$ be an input to \n",
    "batch normalization ($\\textrm{BN}$). In this case the batch normalization is defined as follows:\n",
    "\n",
    "$$\\textrm{BN}(\\mathbf{x}) = \\boldsymbol{\\gamma} \\odot \\frac{\\mathbf{x} - \\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}}}{\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}} + \\boldsymbol{\\beta}.$$\n",
    "\n",
    "In the equation,\n",
    "$\\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}}$ is the  sample mean\n",
    "and $\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}$ is the sample standard deviation of the minibatch $\\mathcal{B}$.\n",
    "After applying standardization,\n",
    "the resulting minibatch has zero mean and variance close to one; the added\n",
    "$\\epsilon$ makes the variance slightly smaller than one.\n",
    "The choice of unit variance\n",
    "(rather than some other magic number) is arbitrary. We recover this degree of freedom\n",
    "by including an elementwise\n",
    "*scale parameter* $\\boldsymbol{\\gamma}$ and *shift parameter* $\\boldsymbol{\\beta}$,\n",
    "with one entry per normalized feature (or channel) and broadcasting over the\n",
    "other axes. Both are parameters that\n",
    "need to be learned as part of model training.\n",
    "\n",
    "Before the learned affine transformation, batch normalization keeps the\n",
    "normalized activations on a controlled scale. The final activations are not\n",
    "bounded, since the learned scale $\\boldsymbol{\\gamma}$ can itself grow.\n",
    "Practical experience confirms that, as alluded to when discussing feature rescaling, batch normalization seems to allow for more aggressive learning rates.\n",
    "We calculate $\\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}}$ and ${\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}}$ in the equation as follows:\n",
    "\n",
    "$$\\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}} = \\frac{1}{|\\mathcal{B}|} \\sum_{\\mathbf{x} \\in \\mathcal{B}} \\mathbf{x}\n",
    "\\textrm{ and }\n",
    "\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}^2 = \\frac{1}{|\\mathcal{B}|} \\sum_{\\mathbf{x} \\in \\mathcal{B}} (\\mathbf{x} - \\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}})^2 + \\epsilon.$$\n",
    "\n",
    "Note that we add a small constant $\\epsilon > 0$\n",
    "to the variance estimate\n",
    "to ensure that we never attempt division by zero,\n",
    "even in cases where the empirical variance estimate might be very small or vanish.\n",
    "The estimates $\\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}}$ and ${\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}}$ counteract the scaling issue\n",
    "by using noisy estimates of mean and variance.\n",
    "You might think that this noisiness should be a problem.\n",
    "On the contrary, it is actually beneficial.\n",
    "\n",
    "This turns out to be a recurring theme in deep learning.\n",
    "For reasons that are not yet well-characterized theoretically,\n",
    "various sources of noise in optimization\n",
    "often lead to faster training and less overfitting:\n",
    "this variation appears to act as a form of regularization.\n",
    "@Teye.Azizpour.Smith.2018 and @Luo.Wang.Shao.ea.2018\n",
    "related the properties of batch normalization to Bayesian priors and penalties, respectively. \n",
    "In particular, this sheds some light on the puzzle\n",
    "of why moderate minibatches can regularize more than very large ones. There is\n",
    "no universal best range: the effective sample count also includes spatial\n",
    "positions in a convolution, and distributed implementations may synchronize\n",
    "statistics across devices. Very large batches reduce this source of noise,\n",
    "whereas very small sample counts make the estimates unreliable.\n",
    "\n",
    "Fixing a trained model, you might think\n",
    "that we would prefer using the entire dataset\n",
    "to estimate the mean and variance.\n",
    "Once training is complete, why would we want\n",
    "the same image to be classified differently,\n",
    "depending on the batch in which it happens to reside?\n",
    "During training, such exact calculation is infeasible\n",
    "because the intermediate variables\n",
    "for all data examples\n",
    "change every time we update our model.\n",
    "During training, implementations therefore maintain exponential moving\n",
    "averages of each layer's mean and variance. Those running estimates, rather\n",
    "than exact statistics over the entire dataset, are the standard default for\n",
    "prediction; a separate calibration pass is sometimes used after fine-tuning.\n",
    "Thus batch normalization layers function differently\n",
    "in *training mode* (normalizing by minibatch statistics)\n",
    "than in *prediction mode* (normalizing by running statistics).\n",
    "In this form they closely resemble the behavior of dropout regularization of that section,\n",
    "where noise is only injected during training.\n",
    "\n",
    "\n",
    "## Batch Normalization Layers\n",
    "\n",
    "Batch normalization implementations for fully connected layers\n",
    "and convolutional layers are slightly different.\n",
    "One key difference between batch normalization and other layers\n",
    "is that because the former operates on a full minibatch at a time,\n",
    "we cannot just ignore the batch dimension\n",
    "as we did before when introducing other layers.\n",
    "\n",
    "### Fully Connected Layers\n",
    "\n",
    "When applying batch normalization to fully connected layers,\n",
    "@Ioffe.Szegedy.2015, in their original paper inserted batch normalization after the affine transformation\n",
    "and *before* the nonlinear activation function. Later applications experimented with\n",
    "inserting batch normalization right *after* activation functions.\n",
    "Denoting the input to the fully connected layer by $\\mathbf{x}$,\n",
    "the affine transformation\n",
    "by $\\mathbf{W}\\mathbf{x} + \\mathbf{b}$ (with the weight parameter $\\mathbf{W}$ and the bias parameter $\\mathbf{b}$),\n",
    "and the activation function by $\\phi$,\n",
    "we can express the computation of a batch-normalization-enabled,\n",
    "fully connected layer output $\\mathbf{h}$ as follows:\n",
    "\n",
    "$$\\mathbf{h} = \\phi(\\textrm{BN}(\\mathbf{W}\\mathbf{x} + \\mathbf{b}) ).$$\n",
    "\n",
    "Recall that mean and variance are computed\n",
    "on the *same* minibatch\n",
    "on which the transformation is applied.\n",
    "\n",
    "### Convolutional Layers\n",
    "\n",
    "Similarly, with convolutional layers,\n",
    "we can apply batch normalization after the convolution\n",
    "but before the nonlinear activation function. The key difference from batch normalization\n",
    "in fully connected layers is that we apply the operation on a per-channel basis\n",
    "*across all locations*. Applying the same affine normalization at every\n",
    "location preserves the translation-equivariant form of the convolutional\n",
    "feature map, apart from the boundary and sampling qualifications discussed in\n",
    "that section.\n",
    "\n",
    "Assume that our minibatches contain $m$ examples\n",
    "and that for each channel,\n",
    "the output of the convolution has height $p$ and width $q$.\n",
    "For convolutional layers, we carry out each batch normalization\n",
    "over the $m \\cdot p \\cdot q$ elements per output channel simultaneously.\n",
    "Thus, we collect the values over all spatial locations\n",
    "when computing the mean and variance\n",
    "and consequently\n",
    "apply the same mean and variance\n",
    "within a given channel\n",
    "to normalize the value at each spatial location.\n",
    "Each channel has its own scale and shift parameters,\n",
    "both of which are scalars.\n",
    "\n",
    "### Layer Normalization\n",
    "\n",
    "For convolutional batch normalization, a minibatch of size 1 still supplies\n",
    "spatial values, so its statistics are defined. They may nevertheless be poor\n",
    "estimates, and they couple distant positions in the same image. *Layer\n",
    "normalization* [@Ba.Kiros.Hinton.2016] removes the batch dependence by\n",
    "normalizing features within each example. Which features are grouped depends\n",
    "on the model: transformer and ConvNeXt blocks normalize the channel vector at\n",
    "each position, whereas other uses may include spatial axes. For an\n",
    "$n$-dimensional vector $\\mathbf{x}$,\n",
    "\n",
    "$$\n",
    "\\textrm{LN}(\\mathbf{x})_i =\n",
    "\\gamma_i \\frac{x_i - \\hat{\\mu}}{\\hat\\sigma} + \\beta_i,\n",
    "$$\n",
    "\n",
    "where each coordinate has its own learned gain $\\gamma_i$ and bias $\\beta_i$,\n",
    "and\n",
    "\n",
    "$$\\hat{\\mu} \\stackrel{\\textrm{def}}{=} \\frac{1}{n} \\sum_{i=1}^n x_i \\textrm{ and }\n",
    "\\hat{\\sigma}^2 \\stackrel{\\textrm{def}}{=} \\frac{1}{n} \\sum_{i=1}^n (x_i - \\hat{\\mu})^2 + \\epsilon.$$\n",
    "\n",
    "As before, $\\epsilon > 0$ prevents division by zero. Before the learned affine\n",
    "map and ignoring $\\epsilon$, the normalized vector is invariant to positive\n",
    "rescaling and flips sign under negative rescaling. Layer normalization does not\n",
    "depend on the minibatch size and computes the same function in training and at\n",
    "test time. It controls the scale entering the affine map but does not by itself\n",
    "guarantee that optimization cannot diverge.\n",
    "\n",
    "### Batch Normalization During Prediction\n",
    "\n",
    "As we mentioned earlier, batch normalization typically behaves differently\n",
    "in training mode than in prediction mode.\n",
    "First, the noise in the sample mean and the sample variance\n",
    "arising from estimating each on minibatches\n",
    "is no longer desirable once we have trained the model.\n",
    "Second, we might not have the luxury\n",
    "of computing per-batch normalization statistics.\n",
    "For example,\n",
    "we might need to apply our model to make one prediction at a time.\n",
    "\n",
    "Typically, after training, we use the entire dataset\n",
    "to compute stable estimates of the variable statistics\n",
    "and then fix them at prediction time.\n",
    "Hence, batch normalization behaves differently during training than at test time.\n",
    "Recall that dropout also exhibits this characteristic.\n",
    "\n",
    "## Implementation from Scratch\n",
    "\n",
    "To see how batch normalization works in practice, we implement one from scratch below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-implementation-from-scratch-1"
   },
   "source": [
    "def batch_norm(X, deterministic, gamma, beta, moving_mean, moving_var, eps,\n",
    "               momentum):\n",
    "    # Use `deterministic` to determine whether the current mode is training\n",
    "    # mode or prediction mode\n",
    "    if deterministic:\n",
    "        # In prediction mode, use mean and variance obtained by moving average\n",
    "        X_hat = (X - moving_mean[...]) / jnp.sqrt(moving_var[...] + eps)\n",
    "    else:\n",
    "        assert len(X.shape) in (2, 4)\n",
    "        if len(X.shape) == 2:\n",
    "            # When using a fully connected layer, calculate the mean and\n",
    "            # variance on the feature dimension\n",
    "            mean = X.mean(axis=0)\n",
    "            var = ((X - mean) ** 2).mean(axis=0)\n",
    "        else:\n",
    "            # When using a two-dimensional convolutional layer, calculate the\n",
    "            # mean and variance over batch and spatial dimensions. Here we\n",
    "            # need to maintain the shape of `X`, so that the broadcasting\n",
    "            # operation can be carried out later\n",
    "            mean = X.mean(axis=(0, 1, 2), keepdims=True)\n",
    "            var = ((X - mean) ** 2).mean(axis=(0, 1, 2), keepdims=True)\n",
    "        # In training mode, the current mean and variance are used\n",
    "        X_hat = (X - mean) / jnp.sqrt(var + eps)\n",
    "        # Update the mean and variance using moving average\n",
    "        moving_mean[...] = momentum * moving_mean[...] + (1.0 - momentum) * mean\n",
    "        moving_var[...] = momentum * moving_var[...] + (1.0 - momentum) * var\n",
    "    Y = gamma * X_hat + beta  # Scale and shift\n",
    "    return Y"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-3 fw=all -->\n",
    "\n",
    "We can now create a proper `BatchNorm` layer.\n",
    "Our layer will maintain proper parameters\n",
    "for scale `gamma` and shift `beta`,\n",
    "both of which will be updated in the course of training.\n",
    "Additionally, our layer will maintain\n",
    "moving averages of the means and variances\n",
    "for subsequent use during model prediction.\n",
    "\n",
    "Putting aside the algorithmic details,\n",
    "note the design pattern underlying our implementation of the layer.\n",
    "Typically, we define the mathematics in a separate function, say `batch_norm`.\n",
    "We then integrate this functionality into a custom layer,\n",
    "whose code mostly addresses bookkeeping matters,\n",
    "such as moving data to the right device context,\n",
    "allocating and initializing any required variables,\n",
    "keeping track of moving averages (here for mean and variance), and so on.\n",
    "This pattern enables a clean separation of mathematics from boilerplate code.\n",
    "Also note that for the sake of convenience\n",
    "we did not worry about automatically inferring the input shape here;\n",
    "thus we need to specify the number of features throughout.\n",
    "By now all modern deep learning frameworks offer automatic detection of size and shape in the\n",
    "high-level batch normalization APIs (in practice we will use this instead)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-implementation-from-scratch-2"
   },
   "source": [
    "class BatchNorm(nnx.Module):\n",
    "    deterministic: bool\n",
    "\n",
    "    # `num_features`: the number of outputs for a fully connected layer\n",
    "    # or the number of output channels for a convolutional layer.\n",
    "    # `num_dims`: 2 for a fully connected layer and 4 for a convolutional layer\n",
    "    # Use `deterministic` to determine whether the current mode is training\n",
    "    # mode or prediction mode\n",
    "    def __init__(self, num_features, num_dims, deterministic=False):\n",
    "        self.deterministic = deterministic\n",
    "        if num_dims == 2:\n",
    "            shape = (1, num_features)\n",
    "        else:\n",
    "            shape = (1, 1, 1, num_features)\n",
    "\n",
    "        # The scale parameter and the shift parameter (model parameters) are\n",
    "        # initialized to 1 and 0, respectively\n",
    "        self.gamma = nnx.Param(jnp.ones(shape))\n",
    "        self.beta = nnx.Param(jnp.zeros(shape))\n",
    "\n",
    "        # The variables that are not model parameters are initialized to 0 and\n",
    "        # 1. Save them to the 'batch_stats' collection\n",
    "        self.moving_mean = nnx.BatchStat(jnp.zeros(shape))\n",
    "        self.moving_var = nnx.BatchStat(jnp.ones(shape))\n",
    "\n",
    "    def set_view(self, *, deterministic):\n",
    "        self.deterministic = deterministic\n",
    "\n",
    "    def __call__(self, X):\n",
    "        return batch_norm(X, self.deterministic, self.gamma, self.beta,\n",
    "                          self.moving_mean, self.moving_var,\n",
    "                          eps=1e-5, momentum=0.9)"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-4 fw=all -->\n",
    "\n",
    "We used `momentum` to govern the aggregation over past mean and variance estimates. This is somewhat of a misnomer as it has nothing whatsoever to do with the *momentum* term of optimization. Nonetheless, it is the commonly adopted name for this term and in deference to API naming convention we use the same variable name in our code.\n",
    "\n",
    "## LeNet with Batch Normalization\n",
    "\n",
    "To see how to apply `BatchNorm` in context,\n",
    "below we apply it to a traditional LeNet model (that section).\n",
    "Recall that batch normalization is applied\n",
    "after the convolutional layers or fully connected layers\n",
    "but before the corresponding activation functions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-lenet-with-batch-normalization-1"
   },
   "source": [
    "class BNLeNetScratch(d2l.Classifier):\n",
    "    def __init__(self, lr=0.1, num_classes=10, rngs=None):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters(ignore=['rngs'])\n",
    "        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs\n",
    "        self.net = nnx.Sequential(\n",
    "            nnx.Conv(1, 6, kernel_size=(5, 5), rngs=rngs),\n",
    "            BatchNorm(6, num_dims=4),\n",
    "            nnx.sigmoid,\n",
    "            lambda x: nnx.avg_pool(x, window_shape=(2, 2), strides=(2, 2)),\n",
    "            nnx.Conv(6, 16, kernel_size=(5, 5), rngs=rngs),\n",
    "            BatchNorm(16, num_dims=4),\n",
    "            nnx.sigmoid,\n",
    "            lambda x: nnx.avg_pool(x, window_shape=(2, 2), strides=(2, 2)),\n",
    "            lambda x: x.reshape((x.shape[0], -1)),\n",
    "            nnx.Linear(7 * 7 * 16, 120, rngs=rngs),\n",
    "            BatchNorm(120, num_dims=2), nnx.sigmoid,\n",
    "            nnx.Linear(120, 84, rngs=rngs),\n",
    "            BatchNorm(84, num_dims=2), nnx.sigmoid,\n",
    "            nnx.Linear(84, num_classes, rngs=rngs))"
   ],
   "execution_count": 4,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-5 fw=jax -->\n",
    "\n",
    "NNX stores running means and variances as `BatchStat` variables inside each\n",
    "layer. The training view updates them in place, while the evaluation view sets\n",
    "`deterministic=True` recursively and reads the accumulated statistics."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-6 fw=all -->\n",
    "\n",
    "As before, we will train our network on the Fashion-MNIST dataset.\n",
    "This code is virtually identical to that when we first trained LeNet."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-lenet-with-batch-normalization-3"
   },
   "source": [
    "trainer = d2l.Trainer(max_epochs=10, num_gpus=1)\n",
    "data = d2l.FashionMNIST(batch_size=128)\n",
    "model = BNLeNetScratch(lr=0.1)\n",
    "trainer.fit(model, data)"
   ],
   "execution_count": 5,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"238.965625pt\" height=\"183.35625pt\" viewBox=\"0 0 238.965625 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T14:27:44.948416</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 238.965625 183.35625 \nL 238.965625 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 30.103125 145.8 \nL 225.403125 145.8 \nL 225.403125 7.2 \nL 30.103125 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"m5db0e67d1c\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"30.103125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0 -->\n      <g transform=\"translate(26.921875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"69.163125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(65.981875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"108.223125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 4 -->\n      <g transform=\"translate(105.041875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"147.283125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 6 -->\n      <g transform=\"translate(144.101875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-36\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"186.343125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 8 -->\n      <g transform=\"translate(183.161875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-38\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_6\">\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m5db0e67d1c\" x=\"225.403125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 10 -->\n      <g transform=\"translate(219.040625 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_7\">\n     <!-- epoch -->\n     <g transform=\"translate(112.525 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_7\">\n      <defs>\n       <path id=\"m4f5edbe70b\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m4f5edbe70b\" x=\"30.103125\" y=\"111.319953\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.4 -->\n      <g transform=\"translate(7.2 115.119172) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m4f5edbe70b\" x=\"30.103125\" y=\"74.341223\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.6 -->\n      <g transform=\"translate(7.2 78.140442) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m4f5edbe70b\" x=\"30.103125\" y=\"37.362494\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.8 -->\n      <g transform=\"translate(7.2 41.161712) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_10\">\n    <path d=\"M 34.96476 13.5 \nL 44.72976 81.273525 \nL 54.49476 98.100055 \nL 64.25976 105.320709 \nL 74.02476 111.263527 \nL 83.78976 116.123382 \nL 93.55476 120.330328 \nL 103.31976 121.891878 \nL 113.08476 124.962497 \nL 122.84976 127.134749 \nL 132.61476 128.994799 \nL 142.37976 131.091697 \nL 152.14476 132.657853 \nL 161.90976 133.291319 \nL 171.67476 135.816744 \nL 181.43976 135.432762 \nL 191.20476 137.199957 \nL 200.96976 137.441404 \nL 210.73476 139.5 \nL 220.49976 138.713173 \n\" clip-path=\"url(#pa7e31715ce)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_11\">\n    <path d=\"M 49.633125 33.67998 \nL 69.163125 27.993476 \nL 88.693125 25.963888 \nL 108.223125 32.052652 \nL 127.753125 24.939952 \nL 147.283125 22.727518 \nL 166.813125 20.990483 \nL 186.343125 27.335231 \nL 205.873125 21.33789 \nL 225.403125 19.034033 \n\" clip-path=\"url(#pa7e31715ce)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 49.633125 83.76213 \nL 69.163125 101.206062 \nL 88.693125 111.965349 \nL 108.223125 96.614763 \nL 127.753125 115.954501 \nL 147.283125 122.650084 \nL 166.813125 128.386778 \nL 186.343125 111.098031 \nL 205.873125 126.761295 \nL 225.403125 132.056753 \n\" clip-path=\"url(#pa7e31715ce)\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 30.103125 145.8 \nL 30.103125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 225.403125 145.8 \nL 225.403125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 30.103125 145.8 \nL 225.403125 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 30.103125 7.2 \nL 225.403125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 138.8125 100.434375 \nL 218.403125 100.434375 \nQ 220.403125 100.434375 220.403125 98.434375 \nL 220.403125 54.565625 \nQ 220.403125 52.565625 218.403125 52.565625 \nL 138.8125 52.565625 \nQ 136.8125 52.565625 136.8125 54.565625 \nL 136.8125 98.434375 \nQ 136.8125 100.434375 138.8125 100.434375 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_13\">\n     <path d=\"M 140.8125 60.664063 \nL 150.8125 60.664063 \nL 160.8125 60.664063 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_11\">\n     <!-- train_loss -->\n     <g transform=\"translate(168.8125 64.164063) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \nL 3263 -1509 \nL -63 -1509 \nL -63 -1063 \nL 3263 -1063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-74\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(39.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(80.322266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(141.601562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(169.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(232.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(310.546875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(371.728516 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(423.828125 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_14\">\n     <path d=\"M 140.8125 75.620313 \nL 150.8125 75.620313 \nL 160.8125 75.620313 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_12\">\n     <!-- val_acc -->\n     <g transform=\"translate(168.8125 79.120313) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(259.521484 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(314.501953 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_15\">\n     <path d=\"M 140.8125 90.576563 \nL 150.8125 90.576563 \nL 160.8125 90.576563 \n\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- val_loss -->\n     <g transform=\"translate(168.8125 94.076563) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(226.025391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(287.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(339.306641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pa7e31715ce\">\n   <rect x=\"30.103125\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-7 fw=all -->\n",
    "\n",
    "Let's have a look at the scale parameter `gamma`\n",
    "and the shift parameter `beta` learned\n",
    "from the first batch normalization layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-lenet-with-batch-normalization-4"
   },
   "source": [
    "model.net.layers[1].gamma[...].reshape((-1,)), \\\n",
    "model.net.layers[1].beta[...].reshape((-1,))"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(Array([2.6707244, 1.8966421, 1.8147523, 1.6768903, 1.9702979, 1.7232087],      dtype=float32),\n Array([ 1.2342167 ,  0.5609814 , -0.26910412,  0.81538904,  0.20941882,\n         0.6389893 ], dtype=float32))"
     },
     "metadata": {},
     "execution_count": 6
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-8 fw=all -->\n",
    "\n",
    "## Concise Implementation\n",
    "\n",
    "Compared with the `BatchNorm` class,\n",
    "which we just defined ourselves,\n",
    "we can use the `BatchNorm` class defined in high-level APIs from the deep learning framework directly.\n",
    "The code looks virtually identical\n",
    "to our implementation above, except that we no longer need to provide additional arguments for it to get the dimensions right."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-concise-implementation-1"
   },
   "source": [
    "class BNLeNet(d2l.Classifier):\n",
    "    def __init__(self, lr=0.1, num_classes=10, rngs=None):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters(ignore=['rngs'])\n",
    "        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs\n",
    "        # Flax's default momentum=0.99 decays the OLD running stats; PT/MX use\n",
    "        # momentum=0.1 on the NEW stats, i.e. decay-of-OLD = 0.9. Pass 0.9 to\n",
    "        # match the other tabs.\n",
    "        self.net = nnx.Sequential(\n",
    "            nnx.Conv(1, 6, kernel_size=(5, 5), rngs=rngs),\n",
    "            nnx.BatchNorm(6, momentum=0.9, rngs=rngs), nnx.sigmoid,\n",
    "            lambda x: nnx.avg_pool(x, window_shape=(2, 2), strides=(2, 2)),\n",
    "            nnx.Conv(6, 16, kernel_size=(5, 5), rngs=rngs),\n",
    "            nnx.BatchNorm(16, momentum=0.9, rngs=rngs), nnx.sigmoid,\n",
    "            lambda x: nnx.avg_pool(x, window_shape=(2, 2), strides=(2, 2)),\n",
    "            lambda x: x.reshape((x.shape[0], -1)),\n",
    "            nnx.Linear(7 * 7 * 16, 120, rngs=rngs),\n",
    "            nnx.BatchNorm(120, momentum=0.9, rngs=rngs), nnx.sigmoid,\n",
    "            nnx.Linear(120, 84, rngs=rngs),\n",
    "            nnx.BatchNorm(84, momentum=0.9, rngs=rngs), nnx.sigmoid,\n",
    "            nnx.Linear(84, num_classes, rngs=rngs))"
   ],
   "execution_count": 7,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-9 fw=all -->\n",
    "\n",
    "Below, we use the same hyperparameters to train our model.\n",
    "Note that as usual, the high-level API variant runs much faster\n",
    "because its code has been compiled to C++ or CUDA\n",
    "while our custom implementation must be interpreted by Python."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-concise-implementation-2"
   },
   "source": [
    "trainer = d2l.Trainer(max_epochs=10, num_gpus=1)\n",
    "data = d2l.FashionMNIST(batch_size=128)\n",
    "model = BNLeNet(lr=0.1)\n",
    "trainer.fit(model, data)"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"238.965625pt\" height=\"183.35625pt\" viewBox=\"0 0 238.965625 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T14:28:09.680328</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 238.965625 183.35625 \nL 238.965625 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 30.103125 145.8 \nL 225.403125 145.8 \nL 225.403125 7.2 \nL 30.103125 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"maa20f6c3e6\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"30.103125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0 -->\n      <g transform=\"translate(26.921875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"69.163125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(65.981875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"108.223125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 4 -->\n      <g transform=\"translate(105.041875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"147.283125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 6 -->\n      <g transform=\"translate(144.101875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-36\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"186.343125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 8 -->\n      <g transform=\"translate(183.161875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-38\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_6\">\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#maa20f6c3e6\" x=\"225.403125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 10 -->\n      <g transform=\"translate(219.040625 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_7\">\n     <!-- epoch -->\n     <g transform=\"translate(112.525 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_7\">\n      <defs>\n       <path id=\"mdea1f86b0d\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#mdea1f86b0d\" x=\"30.103125\" y=\"112.834046\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.4 -->\n      <g transform=\"translate(7.2 116.633265) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#mdea1f86b0d\" x=\"30.103125\" y=\"76.672436\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.6 -->\n      <g transform=\"translate(7.2 80.471655) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#mdea1f86b0d\" x=\"30.103125\" y=\"40.510827\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.8 -->\n      <g transform=\"translate(7.2 44.310046) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_10\">\n    <path d=\"M 34.96476 13.5 \nL 44.72976 84.976515 \nL 54.49476 99.95196 \nL 64.25976 108.824821 \nL 74.02476 113.242558 \nL 83.78976 118.545275 \nL 93.55476 122.942395 \nL 103.31976 122.125113 \nL 113.08476 127.003555 \nL 122.84976 126.859914 \nL 132.61476 129.915881 \nL 142.37976 130.796416 \nL 152.14476 132.753216 \nL 161.90976 133.417019 \nL 171.67476 134.501254 \nL 181.43976 136.390834 \nL 191.20476 136.299265 \nL 200.96976 138.389982 \nL 210.73476 138.744717 \nL 220.49976 139.5 \n\" clip-path=\"url(#pfea94007d9)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_11\">\n    <path d=\"M 49.633125 35.997778 \nL 69.163125 32.958086 \nL 88.693125 30.419049 \nL 108.223125 27.951534 \nL 127.753125 25.323094 \nL 147.283125 26.485329 \nL 166.813125 24.947602 \nL 186.343125 26.020435 \nL 205.873125 23.999934 \nL 225.403125 23.731726 \n\" clip-path=\"url(#pfea94007d9)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 49.633125 87.958694 \nL 69.163125 101.635564 \nL 88.693125 113.068118 \nL 108.223125 119.065176 \nL 127.753125 124.857036 \nL 147.283125 123.76433 \nL 166.813125 128.703116 \nL 186.343125 124.23923 \nL 205.873125 129.523392 \nL 225.403125 131.447131 \n\" clip-path=\"url(#pfea94007d9)\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 30.103125 145.8 \nL 30.103125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 225.403125 145.8 \nL 225.403125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 30.103125 145.8 \nL 225.403125 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 30.103125 7.2 \nL 225.403125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 138.8125 100.434375 \nL 218.403125 100.434375 \nQ 220.403125 100.434375 220.403125 98.434375 \nL 220.403125 54.565625 \nQ 220.403125 52.565625 218.403125 52.565625 \nL 138.8125 52.565625 \nQ 136.8125 52.565625 136.8125 54.565625 \nL 136.8125 98.434375 \nQ 136.8125 100.434375 138.8125 100.434375 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_13\">\n     <path d=\"M 140.8125 60.664063 \nL 150.8125 60.664063 \nL 160.8125 60.664063 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_11\">\n     <!-- train_loss -->\n     <g transform=\"translate(168.8125 64.164063) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \nL 3263 -1509 \nL -63 -1509 \nL -63 -1063 \nL 3263 -1063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-74\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(39.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(80.322266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(141.601562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(169.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(232.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(310.546875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(371.728516 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(423.828125 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_14\">\n     <path d=\"M 140.8125 75.620313 \nL 150.8125 75.620313 \nL 160.8125 75.620313 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_12\">\n     <!-- val_acc -->\n     <g transform=\"translate(168.8125 79.120313) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(259.521484 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(314.501953 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_15\">\n     <path d=\"M 140.8125 90.576563 \nL 150.8125 90.576563 \nL 160.8125 90.576563 \n\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- val_loss -->\n     <g transform=\"translate(168.8125 94.076563) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(226.025391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(287.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(339.306641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pfea94007d9\">\n   <rect x=\"30.103125\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-10 fw=all -->\n",
    "\n",
    "## Beyond Batch Normalization\n",
    "\n",
    "Batch normalization is unusual among the layers in this book: its output for one\n",
    "example depends on the other examples in the minibatch. That coupling is where\n",
    "the regularizing noise comes from, and it is also where the practical trouble\n",
    "comes from. Two problems recur.\n",
    "\n",
    "The first is *minibatch coupling*. The estimates $\\hat{\\boldsymbol{\\mu}}_{\\mathcal{B}}$\n",
    "and $\\hat{\\boldsymbol{\\sigma}}_{\\mathcal{B}}$ stand and fall with the batch size:\n",
    "we saw above that a fully connected layer learns nothing at batch size 1\n",
    "and that very small batches make the statistics unreliable.\n",
    "This bites hardest in dense prediction. Object detection and semantic\n",
    "segmentation train on high-resolution images, so memory often limits the batch\n",
    "to one or two images per device, exactly where batch statistics are noisiest.\n",
    "\n",
    "The second is the *train/serve discrepancy*. As discussed above, the layer\n",
    "applies minibatch statistics during training but moving averages at prediction\n",
    "time, so the network computes two different functions depending on the mode.\n",
    "Whenever the moving averages summarize the served data poorly, for instance\n",
    "after fine-tuning on a new domain or when a bug freezes them, accuracy drops in\n",
    "ways that are hard to trace back to a normalization layer.\n",
    "\n",
    "### Group Normalization\n",
    "\n",
    "*Group normalization* [@wu2018groupnorm] removes the batch from the\n",
    "statistics. It divides the $c$ channels into $G$ groups of $c/G$ channels and\n",
    "standardizes each example separately over each group, i.e., over\n",
    "$(c/G) \\cdot p \\cdot q$ elements, again followed by a per-channel scale\n",
    "$\\boldsymbol{\\gamma}$ and shift $\\boldsymbol{\\beta}$ as in the equation.\n",
    "Setting $G=1$ normalizes each example over all channels and positions at once;\n",
    "setting $G=c$ normalizes every channel separately (a variant known as\n",
    "*instance normalization*). Intermediate group counts such as $G=32$ tend to\n",
    "work best: enough elements per group for stable statistics, without forcing\n",
    "unrelated channels to share them.\n",
    "\n",
    "Because no other example enters the statistics, group normalization computes\n",
    "the same function at batch size 1 as at batch size 32, and the same function\n",
    "during training as at prediction time; there are no moving averages to\n",
    "maintain. The code below checks both claims: after group normalization, every\n",
    "(example, group) pair has mean 0 and variance 1, and normalizing an example\n",
    "alone gives the same output as normalizing it inside a batch."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "batch-norm-group-normalization"
   },
   "source": [
    "X = jax.random.normal(jax.random.PRNGKey(0), (32, 8, 8, 16))  # Channels last\n",
    "gn = nnx.GroupNorm(16, num_groups=4, rngs=nnx.Rngs(1))\n",
    "Y = gn(X)\n",
    "# Collect each (example, group) pair's elements\n",
    "G = jnp.transpose(Y, (0, 3, 1, 2)).reshape(32, 4, -1)\n",
    "(jnp.abs(G.mean(axis=2)).max(), G.var(axis=2).mean(),\n",
    " jnp.allclose(gn(X[:1]), Y[:1], atol=1e-6))"
   ],
   "execution_count": 9,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(Array(2.6077032e-08, dtype=float32),\n Array(0.999999, dtype=float32),\n Array(True, dtype=bool))"
     },
     "metadata": {},
     "execution_count": 9
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-11 fw=all -->\n",
    "\n",
    "The trade-off runs in the other direction too: with large batches, batch\n",
    "normalization averages over more elements and keeps a small accuracy edge on\n",
    "ImageNet classification, but as the batch shrinks below roughly eight examples\n",
    "per device its accuracy degrades quickly while group normalization is\n",
    "unaffected [@wu2018groupnorm]. Group normalization is therefore the\n",
    "default in detection and segmentation heads and in diffusion U-Nets, settings\n",
    "where large per-device batches are unaffordable.\n",
    "\n",
    "### Layer Normalization in Convolutional Networks\n",
    "\n",
    "Layer normalization from that section is the\n",
    "other batch-free option, and modern convolutional networks use it in a specific\n",
    "form: at every spatial position, normalize the $c$ channel values at that\n",
    "position, just as a transformer normalizes each token's embedding. This\n",
    "per-position, channels-last layer normalization is the choice made by ConvNeXt,\n",
    "a convolutional architecture we will meet later in this chapter: it replaces\n",
    "every batch normalization in a ResNet-style network with layer normalization,\n",
    "uses fewer normalization layers overall, and loses no accuracy in the process\n",
    "(that section).\n",
    "\n",
    "### Normalizer-Free Networks\n",
    "\n",
    "One can push further and ask whether deep networks need normalization layers at\n",
    "all. Normalizer-free networks (NFNets) [@brock2021nfnet] answer no:\n",
    "combining *weight standardization* (standardizing each convolution's weights\n",
    "rather than its activations) with *adaptive gradient clipping* (clipping a\n",
    "unit's gradient when its norm grows large relative to the corresponding weight\n",
    "norm) trains ResNet-style networks that held the ImageNet state of the art at\n",
    "publication, with no normalization anywhere. Dropping batch normalization\n",
    "eliminates minibatch coupling and the train/serve discrepancy in one stroke,\n",
    "and it removes the cost of computing batch statistics on large activations. We\n",
    "return to normalizer-free networks when we discuss scaling up convolutional\n",
    "networks in that section.\n",
    "\n",
    "## Discussion\n",
    "\n",
    "Intuitively, batch normalization is thought\n",
    "to make the optimization landscape smoother.\n",
    "However, we must be careful to distinguish between\n",
    "speculative intuitions and true explanations\n",
    "for the phenomena that we observe when training deep models.\n",
    "Recall that we do not even know why simpler\n",
    "deep neural networks (MLPs and conventional CNNs)\n",
    "generalize well in the first place.\n",
    "Even with dropout and weight decay,\n",
    "they remain so flexible that their ability to generalize to unseen data\n",
    "likely needs significantly more refined learning-theoretic generalization guarantees.\n",
    "\n",
    "The original paper proposing batch normalization [@Ioffe.Szegedy.2015], in addition to introducing a powerful and useful tool,\n",
    "offered an explanation for why it works:\n",
    "by reducing *internal covariate shift*.\n",
    "Presumably by *internal covariate shift* they\n",
    "meant something like the intuition expressed above---the\n",
    "notion that the distribution of variable values changes\n",
    "over the course of training.\n",
    "However, there were two problems with this explanation:\n",
    "i) This drift is very different from *covariate shift*,\n",
    "rendering the name a misnomer. If anything, it is closer to concept drift. \n",
    "ii) The explanation offers an under-specified intuition\n",
    "but leaves the question of *why precisely this technique works*\n",
    "an open question wanting for a rigorous explanation.\n",
    "Throughout this book, we aim to convey the intuitions that practitioners\n",
    "use to guide their development of deep neural networks.\n",
    "However, we believe that it is important\n",
    "to separate these guiding intuitions\n",
    "from established scientific fact.\n",
    "Eventually, when you master this material\n",
    "and start writing your own research papers\n",
    "you will want to be clear to delineate\n",
    "between technical claims and hunches.\n",
    "\n",
    "Following the success of batch normalization,\n",
    "its explanation in terms of *internal covariate shift*\n",
    "has repeatedly surfaced in debates in the technical literature\n",
    "and broader discourse about how to present machine learning research.\n",
    "In a memorable speech given while accepting a Test of Time Award\n",
    "at the 2017 NeurIPS conference,\n",
    "Ali Rahimi used *internal covariate shift*\n",
    "as a focal point in an argument likening\n",
    "the modern practice of deep learning to alchemy.\n",
    "Subsequently, the example was revisited in detail\n",
    "in a position paper outlining\n",
    "troubling trends in machine learning [@Lipton.Steinhardt.2018].\n",
    "Other authors\n",
    "have proposed alternative explanations for the success of batch normalization,\n",
    "some [@Santurkar.Tsipras.Ilyas.ea.2018]\n",
    "claiming that batch normalization's success comes despite exhibiting behavior\n",
    "that is in some ways opposite to those claimed in the original paper.\n",
    "\n",
    "\n",
    "We note that the *internal covariate shift*\n",
    "is no more worthy of criticism than any of\n",
    "thousands of similarly vague claims\n",
    "made every year in the technical machine learning literature.\n",
    "Likely, its resonance as a focal point of these debates\n",
    "owes to its broad recognizability for the target audience.\n",
    "Batch normalization became a standard component of convolutional classifiers,\n",
    "while GroupNorm, LayerNorm, and normalizer-free networks now cover regimes in\n",
    "which batch statistics are undesirable. The competing explanations remain a\n",
    "useful case study in separating an empirical result from its proposed mechanism.\n",
    "\n",
    "The practical points are:\n",
    "\n",
    "* During model training, batch normalization continuously adjusts the intermediate output of\n",
    "  the network by utilizing the mean and standard deviation of the minibatch, so that the\n",
    "  values of the intermediate output in each layer throughout the neural network are more stable.\n",
    "* Batch normalization is slightly different for fully connected layers than for convolutional layers. In fact,\n",
    "  for convolutional layers, layer normalization can sometimes be used as an alternative.\n",
    "* Like a dropout layer, batch normalization layers have different behaviors\n",
    "  in training mode than in prediction mode.\n",
    "* Batch normalization is useful for regularization and improving convergence in optimization. By contrast,\n",
    "  the original motivation of reducing internal covariate shift seems not to be a valid explanation.\n",
    "* For more robust models that are less sensitive to input perturbations, consider removing batch normalization [@wang2022removing].\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Should we remove the bias parameter from the fully connected layer or the convolutional layer before the batch normalization? Why?\n",
    "1. Compare the learning rates for LeNet with and without batch normalization.\n",
    "    1. Plot the increase in validation accuracy.\n",
    "    1. How large can you make the learning rate before the optimization fails in both cases?\n",
    "1. Do we need batch normalization in every layer? Experiment with it.\n",
    "1. Implement a \"lite\" version of batch normalization that only removes the mean, or alternatively one that\n",
    "   only removes the variance. How does it behave?\n",
    "1. Fix the parameters `beta` and `gamma`. Observe and analyze the results.\n",
    "1. Can you replace dropout by batch normalization? How does the behavior change?\n",
    "1. Research ideas: think of other normalization transforms that you can apply:\n",
    "    1. Can you apply the probability integral transform?\n",
    "    1. Can you use a full-rank covariance estimate? Why should you probably not do that? \n",
    "    1. Can you use other compact matrix variants (block-diagonal, low-displacement rank, Monarch, etc.)?\n",
    "    1. Does a sparsification compression act as a regularizer?\n",
    "    1. Are there other projections (e.g., convex cone, symmetry group-specific transforms) that you can use?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=batch-norm-md-12 fw=jax -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/18005)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-jax",
   "display_name": "d2l (JAX)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
