{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-1 fw=all -->\n",
    "\n",
    "# Efficient ConvNets: Depthwise Separability, Mobile Architectures, and Re-parameterization\n",
    "\n",
    "The architectures of this chapter so far were designed to win accuracy\n",
    "benchmarks on datacenter GPUs. Many deployment settings instead involve\n",
    "phones, cameras, cars, or embedded boards, where latency, memory, and power\n",
    "matter directly. Efficient convolutional architectures organize this regime\n",
    "around three ideas. First, *factorize*: replace dense convolutions with the\n",
    "depthwise-separable convolutions of that section.\n",
    "Second, *scale and search*: once the block is fixed, let optimization allocate\n",
    "widths, depths, and resolutions. Third, *re-parameterize*: train a multi-branch\n",
    "network, then deploy an algebraically identical single-branch one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-imports"
   },
   "source": [
    "from d2l import mxnet as d2l\n",
    "from mxnet import autograd, init, np, npx\n",
    "from mxnet.gluon import nn\n",
    "npx.set_np()"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-2 fw=all -->\n",
    "\n",
    "## Depthwise-Separable Networks\n",
    "\n",
    "### MobileNet\n",
    "\n",
    "Recall from that section that a depthwise-separable convolution factorizes a dense $k \\times k$ convolution into a per-channel spatial filter followed by a $1 \\times 1$ channel mixture, cutting parameters and operations to a fraction $1/c_\\textrm{o} + 1/k^2$ of the dense cost (the equation), roughly $1/9$ for $3 \\times 3$ kernels. In that section this was a layer-level observation. MobileNet [@howard2017mobilenet] made it an architecture: the entire network is a stack of the block shown in the figure, a depthwise $3 \\times 3$ convolution and a pointwise $1 \\times 1$ convolution, each followed by batch normalization and a ReLU. Downsampling happens inside the block by giving the depthwise convolution a stride of 2, so there are no pooling layers, and a global average pooling head replaces fully connected layers, following NiN (that section). The result matched the ImageNet accuracy of VGG-16 to within a percentage point using roughly $27\\times$ fewer operations and $33\\times$ fewer parameters. A single *width multiplier* $\\alpha$ scales every channel count in the network, trading accuracy against cost along a smooth curve, so MobileNet is a family in the same sense that VGG is (that section).\n",
    "\n",
    "![A depthwise-separable block. The depthwise $3 \\times 3$ convolution filters each channel spatially, the pointwise $1 \\times 1$ convolution mixes channels, and batch normalization plus a ReLU follow each of the two convolutions.](../img/arch-dws-block.svg)\n",
    "\n",
    "### The Inverted Bottleneck\n",
    "\n",
    "The bottleneck blocks of ResNet and ResNeXt (that section) compress: a $1 \\times 1$ convolution reduces a wide representation, the $3 \\times 3$ convolution works in the narrow space, and a final $1 \\times 1$ convolution expands it back. This is the right trade when the $3 \\times 3$ convolution is dense and therefore expensive. Once the spatial convolution is depthwise, however, it is cheap even on wide tensors, and the economics reverse. MobileNetV2 [@sandler2018mobilenetv2] therefore *inverts* the bottleneck: the residual stream stays thin, a $1 \\times 1$ convolution expands it (by a factor of 6 in the paper), the depthwise $3 \\times 3$ convolution operates in the wide expanded space, and a $1 \\times 1$ projection returns to the thin stream. The projection is *linear*: no ReLU follows it, because a ReLU acting on a low-dimensional representation discards information that cannot be recovered, which the paper demonstrates by ablation. The residual connection joins the thin ends, so the tensors that must be kept in memory across blocks are the small ones. That matters on a phone, where activation memory rather than parameter storage is often the binding constraint.\n",
    "\n",
    "The inverted bottleneck outlived its mobile origins: ConvNeXt (that section) adopted the same shape for its blocks, with the depthwise convolution enlarged to $7 \\times 7$ and moved to the front [@liu2022convnet]. We will meet it again when we discuss design spaces in that section.\n",
    "\n",
    "### A Mini-MobileNet\n",
    "\n",
    "Let's build a small MobileNetV1-style network for Fashion-MNIST. We use the original block rather than the inverted bottleneck: it is the clearest expression of the factorization, and at Fashion-MNIST scale the difference is negligible. Real mobile networks since MobileNetV2 use inverted bottlenecks throughout. The block below is the pair from the figure; a stride of 2 downsamples."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-a-mini-mobilenet-1"
   },
   "source": [
    "def dws_block(in_channels, out_channels, strides=1):\n",
    "    \"\"\"Depthwise 3x3 and pointwise 1x1 convolutions, each with BN and ReLU.\"\"\"\n",
    "    blk = nn.Sequential()\n",
    "    blk.add(nn.Conv2D(in_channels, kernel_size=3, strides=strides, padding=1,\n",
    "                      groups=in_channels, use_bias=False),\n",
    "            nn.BatchNorm(), nn.Activation('relu'),\n",
    "            nn.Conv2D(out_channels, kernel_size=1, use_bias=False),\n",
    "            nn.BatchNorm(), nn.Activation('relu'))\n",
    "    return blk"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-3 fw=all -->\n",
    "\n",
    "Like VGG (that section), the whole network is a list of block parameters, here (channels, stride) pairs. A small convolutional stem lifts the grayscale input to 32 channels at half resolution; seven depthwise-separable blocks double the channels while shrinking the feature map; global average pooling and a linear layer produce the class scores."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-a-mini-mobilenet-2"
   },
   "source": [
    "class MiniMobileNet(d2l.Classifier):\n",
    "    def __init__(self, arch=((64, 1), (128, 2), (128, 1), (256, 2), (256, 1),\n",
    "                             (512, 2), (512, 1)),\n",
    "                 lr=0.1, num_classes=10):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters()\n",
    "        self.net = nn.Sequential()\n",
    "        self.net.add(nn.Conv2D(32, kernel_size=3, strides=2, padding=1,\n",
    "                               use_bias=False),\n",
    "                     nn.BatchNorm(), nn.Activation('relu'))\n",
    "        c = 32\n",
    "        for c_out, strides in arch:\n",
    "            self.net.add(dws_block(c, c_out, strides))\n",
    "            c = c_out\n",
    "        self.net.add(nn.GlobalAvgPool2D(), nn.Dense(num_classes))\n",
    "        self.net.initialize(init.Xavier())"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-4 fw=all -->\n",
    "\n",
    "Before training, let's verify the arithmetic that motivates the design. The network below has 542,474 trainable parameters. A twin with each depthwise-separable pair replaced by one dense $3 \\times 3$ convolution at the same widths would need $9 \\sum_l c_{\\textrm{i},l}\\, c_{\\textrm{o},l} \\approx 4.7$ million parameters in its body, about $8.8\\times$ more, matching the prediction of the equation for these channel counts."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-a-mini-mobilenet-3"
   },
   "source": [
    "model = MiniMobileNet()\n",
    "X = d2l.normal(0, 1, (1, 1, 96, 96))\n",
    "assert model.net(X).shape == (1, 10)\n",
    "sum(p.data().size for p in model.collect_params().values()\n",
    "    if p.grad_req != 'null')"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "542474"
     },
     "metadata": {},
     "execution_count": 4
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-5 fw=all -->\n",
    "\n",
    "### Training and Comparison\n",
    "\n",
    "Parameter counts alone do not settle whether the factorization gives anything\n",
    "up, so we train the mini-MobileNet against a plain VGG-style network\n",
    "(that section) at the *same parameter budget*. Dense $3 \\times 3$\n",
    "convolutions spend parameters roughly nine times faster per pair of channel\n",
    "counts, so the dense network stops at 128 channels where the separable one\n",
    "reaches 512. Both use batch normalization and an identical\n",
    "global-average-pooling head. The comparison matches parameter count, input\n",
    "resolution, optimizer, and training budget; the separable block and the wider\n",
    "channel allocation it permits change together."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-6 fw=mxnet -->\n",
    "\n",
    "The MXNet path implements and verifies the MobileNet blocks and the RepVGG\n",
    "fusion algebra. It omits this comparative training run, which the other\n",
    "three frameworks each execute independently."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-7 fw=all -->\n",
    "\n",
    "We train both for 10 epochs on Fashion-MNIST at $96 \\times 96$ resolution, with the same trainer and data pipeline we used for ResNet-18 in that section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-8 fw=all -->\n",
    "\n",
    "The table reports one seeded run per framework; accuracies are rounded to\n",
    "the half point, which is about the level at which they are reproducible\n",
    "from run to run.\n",
    "\n",
    "| Model | Parameters | Multiply-adds | PyTorch | JAX | TensorFlow |\n",
    "|---|---:|---:|---:|---:|---:|\n",
    "| Mini-MobileNet | 542,474 | 50.3 million | ≈91% | ≈91% | ≈91.5% |\n",
    "| VGG-style control | 583,594 | 384.9 million | ≈89.5% | ≈89.5% | ≈92.5% |\n",
    "\n",
    "The two models have comparable accuracy in this small experiment: every run\n",
    "of both architectures lands in a band of roughly 89–93%, and which of the\n",
    "two comes out ahead varies with the framework and the seed — a difference\n",
    "within run-to-run noise, on which no conclusion should be built. The stable\n",
    "result is computational. At this parameter budget the separable network\n",
    "performs about $7.7\\times$ fewer multiply-adds, and its epochs run roughly\n",
    "$2$–$3\\times$ faster (in this PyTorch run, about 7 versus 18 seconds). The\n",
    "speedup is far smaller than the operation-count ratio: depthwise\n",
    "convolutions perform little arithmetic per byte of memory, so operation\n",
    "count and wall-clock time diverge. We return to this systems constraint\n",
    "below and in the exercises.\n",
    "\n",
    "## Scaling and Searching\n",
    "\n",
    "MobileNet fixes a block and picks channel counts by hand. Two further questions remain: how should a network grow when more compute is available, and who chooses the per-stage hyperparameters? EfficientNet [@tan2019efficientnet] answered the first with *compound scaling*. Depth, width, and input resolution all improve accuracy with diminishing returns when scaled alone, so EfficientNet scales them together, multiplying depth by $\\alpha^\\phi$, width by $\\beta^\\phi$, and resolution by $\\gamma^\\phi$ for a single budget knob $\\phi$, with constants fitted once on a small grid subject to $\\alpha \\beta^2 \\gamma^2 \\approx 2$, so that each increment of $\\phi$ doubles the cost. The base network itself was found by neural architecture search over inverted-bottleneck blocks, an automated version of the design-space exploration we study in that section.\n",
    "\n",
    "EfficientNetV2 [@tan2021efficientnetv2] revised both halves with training cost in the objective. The search rewards training speed alongside inference speed, and the resulting models replace the depthwise blocks in early, high-resolution stages with dense fused blocks: exactly where depthwise convolutions do too little arithmetic per byte of memory traffic to keep an accelerator busy. Training uses *progressive resizing*, starting on small images with weak regularization and growing both together, which shortens training severalfold at equal accuracy. FLOP counts favor depthwise convolutions everywhere; measured throughput does not, and the search follows the measurement.\n",
    "\n",
    "MobileNetV4 [@qin2024mobilenetv4] pushed the same logic across hardware. Its *universal inverted bottleneck* generalizes the MobileNetV2 block with two optional depthwise convolutions, before the expansion and between expansion and projection; the choices recover the classic inverted bottleneck, a ConvNeXt-like block, a pure feedforward layer, and a new extra-depthwise variant as corners of one searchable space. Searched jointly with a mobile-friendly attention variant, the resulting family is close to Pareto-optimal not on one device but across phone CPUs, DSPs, GPUs, and neural accelerators, whose preferred operations differ. The design lesson of a decade of mobile convnets is that the *block* is a human insight, but the *allocation*, of width, depth, resolution, and block variant per stage, is better treated as an optimization problem against measured latency.\n",
    "\n",
    "## Structural Re-parameterization\n",
    "\n",
    "### The RepVGG Block\n",
    "\n",
    "Multi-branch architectures train better than plain ones; that was the lesson of that section. At inference time, however, every branch must be computed and its output held in memory until the join, and the many small operations of a branchy block leave accelerator kernels underutilized. A plain stack of $3 \\times 3$ convolutions, VGG-style, is the shape inference hardware likes best: one big, regular operation per layer, one activation tensor alive at a time. RepVGG [@ding2021repvgg] obtains both. During training, each layer is a three-branch block, a $3 \\times 3$ convolution, a $1 \\times 1$ convolution, and an identity path, each with its own batch normalization, summed before the ReLU (the figure). For deployment, the three branches are *fused into a single $3 \\times 3$ convolution* whose output is identical, not approximately but exactly, because everything involved is linear. The train-time network enjoys residual-style optimization; the deployed network is a plain convolution stack.\n",
    "\n",
    "![Structural re-parameterization. At training time each RepVGG layer sums three branches, a $3 \\times 3$ convolution, a $1 \\times 1$ convolution, and an identity, each with batch normalization. For inference the branches are folded into one $3 \\times 3$ convolution with a bias; the two networks compute the same function.](../img/arch-repvgg-reparam.svg)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-the-repvgg-block"
   },
   "source": [
    "class RepVGGBlock(nn.Block):\n",
    "    \"\"\"Train-time block: 3x3, 1x1, and identity branches, each with BN.\"\"\"\n",
    "    def __init__(self, num_channels):\n",
    "        super().__init__()\n",
    "        self.conv3 = nn.Conv2D(num_channels, kernel_size=3, padding=1,\n",
    "                               use_bias=False)\n",
    "        self.conv1 = nn.Conv2D(num_channels, kernel_size=1, use_bias=False)\n",
    "        self.bn3, self.bn1, self.bn0 = (nn.BatchNorm() for _ in range(3))\n",
    "\n",
    "    def forward(self, X):\n",
    "        return npx.relu(self.bn3(self.conv3(X)) + self.bn1(self.conv1(X))\n",
    "                        + self.bn0(X))"
   ],
   "execution_count": 5,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-9 fw=all -->\n",
    "\n",
    "### Fusing the Branches\n",
    "\n",
    "The fusion is three small pieces of weight algebra. At inference time, batch normalization is a fixed affine map per channel: it subtracts the running mean $\\mu_o$, divides by $\\sqrt{\\sigma_o^2 + \\epsilon}$, scales by $\\gamma_o$, and shifts by $\\beta_o$. Applied to the output of a convolution with kernel $\\mathbf{W}$ and bias $b_o$, it can be absorbed into a new kernel and bias,\n",
    "\n",
    "$$\n",
    "\\hat{\\mathbf{W}}_o = \\frac{\\gamma_o}{\\sqrt{\\sigma_o^2 + \\epsilon}}\\, \\mathbf{W}_o,\n",
    "\\qquad\n",
    "\\hat{b}_o = \\beta_o + \\frac{\\gamma_o(b_o-\\mu_o)}{\\sqrt{\\sigma_o^2 + \\epsilon}},\n",
    "$$\n",
    "\n",
    "where the index $o$ runs over output channels. The RepVGG convolutions below\n",
    "set $b_o=0$, giving the shorter expression implemented in `fuse_bn`.\n",
    "Conv--BN folding is a standard inference optimization for such layer pairs.\n",
    "Next, the two remaining branches are convolutions in disguise. A $1 \\times 1$\n",
    "kernel is a $3 \\times 3$ kernel that is zero everywhere except at the center,\n",
    "so padding it with a ring of zeros changes nothing. The identity map is a\n",
    "convolution with the kernel $\\mathbf{W}^{\\textrm{id}}_{o,i}$ that is 1 at the\n",
    "center position when $i = o$ and 0 otherwise. Finally, convolution is linear\n",
    "in its kernel: the sum of three convolutions applied to the same input equals\n",
    "one convolution with the summed kernels, and likewise for the biases. Folding\n",
    "each branch by the equation, padding the $1 \\times 1$ kernel, and\n",
    "summing gives the single fused layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-fusing-the-branches-1"
   },
   "source": [
    "def fuse_bn(W, bn, eps=1e-5):\n",
    "    scale = bn.gamma.data() / np.sqrt(bn.running_var.data() + eps)\n",
    "    return (W * scale.reshape(-1, 1, 1, 1),\n",
    "            bn.beta.data() - bn.running_mean.data() * scale)\n",
    "\n",
    "def fuse_block(blk):\n",
    "    c = blk.conv3.weight.shape[0]\n",
    "    W1 = np.zeros((c, c, 3, 3))\n",
    "    W1[:, :, 1, 1] = blk.conv1.weight.data().reshape(c, c)\n",
    "    I = np.zeros((c, c, 3, 3))\n",
    "    I[:, :, 1, 1] = np.eye(c)\n",
    "    W3, b3 = fuse_bn(blk.conv3.weight.data(), blk.bn3)\n",
    "    W1, b1 = fuse_bn(W1, blk.bn1)\n",
    "    W0, b0 = fuse_bn(I, blk.bn0)\n",
    "    fused = nn.Conv2D(c, kernel_size=3, padding=1)\n",
    "    fused.initialize()\n",
    "    fused(np.zeros((1, c, 3, 3)))  # materialize the deferred parameters\n",
    "    fused.weight.data()[:] = W3 + W1 + W0\n",
    "    fused.bias.data()[:] = b3 + b1 + b0\n",
    "    return fused"
   ],
   "execution_count": 6,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-10 fw=all -->\n",
    "\n",
    "Fusion uses the *running* statistics, the same ones inference uses, so before checking equivalence we push a few batches through the block in training mode to move those statistics away from their initialization. The check itself feeds fresh data to the train-time block in inference mode and to the fused convolution, and compares."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "efficient-convnets-fusing-the-branches-2"
   },
   "source": [
    "blk = RepVGGBlock(8)\n",
    "blk.initialize()\n",
    "for _ in range(4):  # populate the BN running statistics\n",
    "    with autograd.train_mode():\n",
    "        blk(np.random.normal(size=(32, 8, 16, 16)))\n",
    "fused = fuse_block(blk)\n",
    "X = np.random.normal(size=(32, 8, 16, 16))\n",
    "float(np.abs(blk(X) - npx.relu(fused(X))).max())"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "1.9073486328125e-06"
     },
     "metadata": {},
     "execution_count": 7
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=efficient-convnets-md-11 fw=all -->\n",
    "\n",
    "The maximum difference is on the order of $10^{-6}$, single-precision roundoff: the fused convolution is the same function. The parameter saving is modest, about a tenth. The real change is execution shape: one convolution kernel instead of three plus three normalizations and two additions, one live activation tensor instead of three, and no batch normalization at all at inference time.\n",
    "\n",
    "### From Paper to Product\n",
    "\n",
    "Deployment adds a constraint that the fusion algebra does not model. The fused kernel is a *sum* of branches whose scales, after folding batch normalization into them by the equation, can differ by orders of magnitude, so the summed weights and the activations they produce have wide, poorly centered distributions. Naive post-training INT8 quantization, which represents each tensor with 256 evenly spaced values, collapses on such distributions: a fused RepVGG drops from 75.1% to 40.2% top-1 accuracy on ImageNet, where a plain ResNet loses a fraction of a point. Quantization-aware re-parameterization variants restore the lost accuracy by constraining the branch statistics during training [@chu2024qarepvgg]. The episode is a useful corrective to reading papers too literally: \"mathematically identical\" holds in FP32, and the real world quantizes.\n",
    "\n",
    "The idea has since appeared in deployment-oriented architectures. MobileOne\n",
    "[@vasu2023mobileone] applies train-time over-parameterization to\n",
    "depthwise-separable blocks and reports sub-millisecond backbone latency on a\n",
    "phone. FastViT [@vasu2023fastvit] combines re-parameterized convolutional\n",
    "stages with attention after resolution reduction. Training-time auxiliary\n",
    "branches that fold away also appear in large-kernel and hybrid architectures.\n",
    "\n",
    "## Summary and Discussion\n",
    "\n",
    "Efficiency turned out to be a design axis of its own, with its own architectures and its own failure modes. Depthwise separability cuts the cost of convolution by roughly $k^2$ at small accuracy cost; the inverted bottleneck arranges the factorized operations so that the expensive tensors are also the transient ones; compound scaling and architecture search allocate a budget across width, depth, and resolution better than manual choice; and structural re-parameterization separates the network you train from the network you ship, connected by exact weight algebra. Twice in this section the correct accounting was memory traffic rather than arithmetic: EfficientNetV2 removed depthwise convolutions from early stages because they starve the accelerator, and RepVGG's whole premise is that fewer, larger operations beat more, smaller ones at equal FLOPs. Operation counts are a proxy, and hardware keeps score in its own currency.\n",
    "\n",
    "As of 2026, deployment sorts by that currency. On the cheapest tier,\n",
    "microcontrollers and entry phones, plain depthwise convnets of the MobileNet\n",
    "lineage remain the only thing that fits. Flagship phones run\n",
    "convolution-attention hybrids such as FastViT and MobileNetV4 variants, using\n",
    "convolutions at high resolution and attention where the feature maps are\n",
    "small. Pure vision transformers appear where a dedicated neural accelerator\n",
    "and its memory budget can be assumed, and in the datacenter. Convnets did not\n",
    "lose the efficiency race; they are its incumbent, and the hybrid designs\n",
    "concede exactly as much of the network to attention as the hardware can\n",
    "afford. How to navigate such trade-offs systematically, rather than\n",
    "architecture by architecture, is the subject of that section.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Fold a Conv-BN pair by hand: take a single convolution followed by batch normalization, apply the equation to obtain one biased convolution, and verify with `allclose` that the two agree in inference mode. Why must the running statistics, not the batch statistics, be used?\n",
    "1. Derive the cost ratio of the equation for $5 \\times 5$ kernels. For which output-channel counts is the pointwise term the dominant cost? What does this imply for architectures that enlarge depthwise kernels, such as ConvNeXt?\n",
    "1. The mini-MobileNet performs about $7.7\\times$ fewer multiply-adds than its VGG-style twin, yet its epochs are not $7.7\\times$ faster. Measure the forward-pass time of both networks on a batch of $128$ images. Explain the gap in terms of arithmetic intensity: how many operations does a depthwise convolution perform per weight and per activation it touches, compared to a dense convolution? Relate your answer to EfficientNetV2's fused early stages.\n",
    "1. If the fused RepVGG layer computes the same function, why not train the plain $3 \\times 3$ stack directly? Build a small network from `RepVGGBlock` layers and an otherwise identical one from plain convolutions, train both on Fashion-MNIST, and compare training curves.\n",
    "1. Add a width multiplier $\\alpha$ to `MiniMobileNet` that scales every channel count. How do the parameter count and the number of multiply-adds scale with $\\alpha$? Verify your prediction at $\\alpha = 0.5$."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-mxnet",
   "display_name": "d2l (MXNet)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
