{"notes":[{"id":"lightweight/mobilenet-v2","category":"lightweight","legacyPath":"lightweight/1801-mobilenet-v2","legacySlug":"1801-mobilenet-v2","legacyPaths":[],"title":"MobileNet-V2","subtitle":"瓶颈内的淬炼","author":"Z. Yuan","paperDate":"2018-01-13","publishedOn":"2024-06-27","paperTitle":"MobileNetV2: Inverted Residuals and Linear Bottlenecks","paperUrl":"https://arxiv.org/abs/1801.04381","bibliography":{"title":"MobileNetV2: Inverted Residuals and Linear Bottlenecks","authors":["Mark Sandler","Andrew Howard","Menglong Zhu","Andrey Zhmoginov","Liang-Chieh Chen"],"url":"https://arxiv.org/abs/1801.04381","pdfUrl":"https://arxiv.org/pdf/1801.04381","codeUrl":null,"preprint":{"id":"1801.04381","submittedOn":"2018-01-13","url":"https://arxiv.org/abs/1801.04381"},"publication":{"venue":"CVPR","year":2018,"kind":"conference","url":"https://arxiv.org/abs/1801.04381"},"citation":"@misc{lightweightmobilenetv22018,\n  title = {{MobileNetV2: Inverted Residuals and Linear Bottlenecks}},\n  author = {Mark Sandler and Andrew Howard and Menglong Zhu and Andrey Zhmoginov and Liang-Chieh Chen},\n  year = {2018},\n  eprint = {1801.04381},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1801.04381}\n}\n","citationPath":"/content/papers/citations/lightweight/mobilenet-v2.a882707cbaa2.bib"},"thumbnail":{"src":"/content/papers/assets/e6bbfb346bb449f83897d76b69c3711d2e9937d40320a7aab0f3843653a688c0.jpg","width":2332,"height":1324},"locale":"zh-hans","path":"/content/papers/zh-hans/lightweight/mobilenet-v2.3cc14e69626b.md","headings":[{"id":"定义问题","text":"定义问题","depth":2},{"id":"线性瓶颈","text":"线性瓶颈","depth":3},{"id":"残差网络","text":"残差网络","depth":3},{"id":"解决问题","text":"解决问题","depth":2},{"id":"反转残差","text":"反转残差","depth":3},{"id":"扩张瓶颈论文附录-a","text":"扩张瓶颈（论文附录 A）","depth":3},{"id":"模型架构","text":"模型架构","depth":3},{"id":"讨论","text":"讨论","depth":2},{"id":"图像分类性能","text":"图像分类性能","depth":3},{"id":"结论","text":"结论","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"lightweight/mobilenet-v1","relation":"background","topic":"移动设备上的高效卷积"},{"id":"lightweight/mobilenet-v3","relation":"next","topic":"移动设备上的高效卷积"}]},{"id":"lightweight/mobilenet-v1","category":"lightweight","legacyPath":"lightweight/1704-mobilenet-v1","legacySlug":"1704-mobilenet-v1","legacyPaths":[],"title":"MobileNet-V1","subtitle":"深度可分离卷积的发扬者","author":"Z. Yuan","paperDate":"2017-04-17","publishedOn":"2024-06-25","paperTitle":"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications","paperUrl":"https://arxiv.org/abs/1704.04861","bibliography":{"title":"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications","authors":["Andrew G. Howard","Menglong Zhu","Bo Chen","Dmitry Kalenichenko","Weijun Wang","Tobias Weyand","Marco Andreetto","Hartwig Adam"],"url":"https://arxiv.org/abs/1704.04861","pdfUrl":"https://arxiv.org/pdf/1704.04861","codeUrl":null,"preprint":{"id":"1704.04861","submittedOn":"2017-04-17","url":"https://arxiv.org/abs/1704.04861"},"publication":null,"citation":"@misc{lightweightmobilenetv12017,\n  title = {{MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications}},\n  author = {Andrew G. Howard and Menglong Zhu and Bo Chen and Dmitry Kalenichenko and Weijun Wang and Tobias Weyand and Marco Andreetto and Hartwig Adam},\n  year = {2017},\n  eprint = {1704.04861},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1704.04861}\n}\n","citationPath":"/content/papers/citations/lightweight/mobilenet-v1.e9c4c525fed4.bib"},"thumbnail":{"src":"/content/papers/assets/b8390bd8e0f21f1b1eaa6b2a5d4a1b0d9eba36e2fe5dd0878830d757839d30f1.jpg","width":1064,"height":1080},"locale":"zh-hans","path":"/content/papers/zh-hans/lightweight/mobilenet-v1.aef841466ce6.md","headings":[{"id":"定义问题","text":"定义问题","depth":2},{"id":"解决问题","text":"解决问题","depth":2},{"id":"深度可分离卷积","text":"深度可分离卷积","depth":3},{"id":"网络架构","text":"网络架构","depth":2},{"id":"训练技巧","text":"训练技巧","depth":2},{"id":"讨论","text":"讨论","depth":2},{"id":"深度可分离卷积的性能","text":"深度可分离卷积的性能","depth":3},{"id":"要深度还是要宽度","text":"要深度还是要宽度？","depth":3},{"id":"和其他模型比较","text":"和其他模型比较","depth":3},{"id":"结论","text":"结论","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"lightweight/mobilenet-v2","relation":"next","topic":"移动设备上的高效卷积"}]},{"id":"lightweight/mobilenet-v3","category":"lightweight","legacyPath":"lightweight/1905-mobilenet-v3","legacySlug":"1905-mobilenet-v3","legacyPaths":[],"title":"MobileNet-V3","subtitle":"定制化搜索架构","author":"Z. Yuan","paperDate":"2019-05-06","publishedOn":"2024-06-29","paperTitle":"Searching for MobileNetV3","paperUrl":"https://arxiv.org/abs/1905.02244","bibliography":{"title":"Searching for MobileNetV3","authors":["Andrew Howard","Mark Sandler","Grace Chu","Liang-Chieh Chen","Bo Chen","Mingxing Tan","Weijun Wang","Yukun Zhu","Ruoming Pang","Vijay Vasudevan","Quoc V. Le","Hartwig Adam"],"url":"https://arxiv.org/abs/1905.02244","pdfUrl":"https://arxiv.org/pdf/1905.02244","codeUrl":null,"preprint":{"id":"1905.02244","submittedOn":"2019-05-06","url":"https://arxiv.org/abs/1905.02244"},"publication":{"venue":"ICCV","year":2019,"kind":"conference","url":"https://arxiv.org/abs/1905.02244"},"citation":"@misc{lightweightmobilenetv32019,\n  title = {{Searching for MobileNetV3}},\n  author = {Andrew Howard and Mark Sandler and Grace Chu and Liang-Chieh Chen and Bo Chen and Mingxing Tan and Weijun Wang and Yukun Zhu and Ruoming Pang and Vijay Vasudevan and Quoc V. Le and Hartwig Adam},\n  year = {2019},\n  eprint = {1905.02244},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1905.02244}\n}\n","citationPath":"/content/papers/citations/lightweight/mobilenet-v3.78d376f40aa4.bib"},"thumbnail":{"src":"/content/papers/assets/09d4bf8776407cb2ac13bc206505f30314b21d2459add8129ffcb929d11ec1bf.jpg","width":1552,"height":588},"locale":"zh-hans","path":"/content/papers/zh-hans/lightweight/mobilenet-v3.abffd356ec13.md","headings":[{"id":"定义问题","text":"定义问题","depth":2},{"id":"解决问题","text":"解决问题","depth":2},{"id":"mobilenet-v2-模块","text":"MobileNet-V2 模块","depth":3},{"id":"mobilenet-v3-模块","text":"MobileNet-V3 模块","depth":3},{"id":"网络架构搜索","text":"网络架构搜索","depth":3},{"id":"网络结尾变更","text":"网络结尾变更","depth":3},{"id":"缩减初始滤波器","text":"缩减初始滤波器","depth":3},{"id":"非线性激活函数","text":"非线性激活函数","depth":3},{"id":"网络架构大","text":"网络架构（大）","depth":3},{"id":"网络架构小","text":"网络架构（小）","depth":3},{"id":"讨论","text":"讨论","depth":2},{"id":"imagenet-实验结果","text":"ImageNet 实验结果","depth":3},{"id":"移动设备评估","text":"移动设备评估","depth":3},{"id":"优化纪录","text":"优化纪录","depth":3},{"id":"结论","text":"结论","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"lightweight/mobilenet-v2","relation":"background","topic":"移动设备上的高效卷积"},{"id":"lightweight/mobilenet-v4","relation":"next","topic":"移动设备上的高效卷积"},{"id":"lightweight/senet","relation":"comparison","topic":"轻量网络里的通道注意力"}]}],"text":"MobileNet 是一个轻量级深度学习网络，旨在移动设备上实现高效的图像识别。\n\n在第一代 MobileNet 中，作者使用深度可分离卷积（Depthwise Separable Convolution），以减少参数量和计算量。\n\n在这篇论文中，作者延续了这个思路，并尝试找到提升性能的新方法。\n\n\n> [!TIP]\n> \n> 如果你是第一次看到这篇论文，你可能会被那些喷涌而出的名词所淹没。\n> \n> 因此，这篇论文我们首要推荐看代码实现。\n> \n> 不过既然你已经点进来了，那我们就一起看一下吧。\n\n\n## 定义问题\n\n### 线性瓶颈\n\n作者想讨论的第一个问题是线性瓶颈。\n\n假设我们有一个用于图像识别的深度卷积神经网络。每个卷积层都会产生一个三维的激活张量（高度 × 宽度 × 深度），其中包含了图像的特征。\n\n例如，第一层可能会识别边缘和颜色变化，而更深的层可能会识别更复杂的形状或对象部分。\n\n在神经网络的每一层中，激活张量可以视为存在于一个高维空间中。这个空间中的有意义数据结构（在论文内称为「兴趣流形」(manifold of interest)），理论上可以被映射到一个低维子空间中，而不丢失重要信息。这是因为虽然数据在原始空间中是高维的，但它们往往围绕某些低维结构分布。\n\n\n> [!TIP]\n> \n> 举个例子：如果 128 维特征本来就位于二维子空间，且投影在这个子空间上保留了区分不同点的信息，我们才可能从二维表示还原原有特征；任意 128 维数据不能无损压成二维。\n\n\n为了有效利用这一性质，网络设计可以引入线性瓶颈层来降低数据的维度，这种方式在 MobileNetV1 中得到了成功应用。\n\n然而，当引入非线性操作，如 ReLU（修正线性单元）时，情况会变得更复杂。\n\nReLU 的效果是对每个元素进行线性阈值处理，将所有负值设为零，这会改变数据的分布，从而产生新的几何结构（如射线和分段线性曲线）。\n\n\n> [!TIP]\n> \n> 延续刚才的例子：若先投影到二维，再对结果使用 ReLU，负值会变成零。原本不同的点可能落在同一位置，此后即使用线性变换也无法恢复这些差异。\n\n\n而避免这种情况的方式，是提供足够的维度，以便在非线性变换后仍然保留足够的信息，如下图所示：\n\n\n\n![Linear Bottleneck](/content/papers/assets/fa9960be3fd190fa1e6d1ebd0b00627a733a63b5276603aa9a880b62e851fc25.jpg)\n\n\n\n在图中，最左边的是输入，对于投影到不同的维度上，且经过 ReLU 运算后，右边的分布就会有所不同。\n\n可以看到当我们选用的维度不够时，经过 ReLU 运算后，原本的分布就会被破坏，有一部分的信息将永远丢失。\n\n### 残差网络\n\n先看一下什么叫做残差网络，这里引入 ResNet 论文内提供的图片：\n\n\n\n![ResNet](/content/papers/assets/a582ed00a15da709c6839e653f84f694e1170cc83d0846fa897c62d1819e986c.jpg)\n\n\n\n一般的残差网络，首先经过一个 1x1 卷积层降维，然后是 3x3 卷积层汇集信息，最后再经过一个 1x1 卷积层升维，最后再加上原始输入。\n\n根据刚才提到的线性瓶颈，这个残差模块在降维的过程中又引入了 ReLU 非线性运算，这样可能丢失信息。\n\n信息丢多了会怎样？\n\n如果信息丢得太多，深层网络的残差分支还能有效表达什么？这会削弱它的作用，白白耗费计算资源。\n\n## 解决问题\n\n为了解决问题，作者修改了原本的残差模块，将压缩维度改成膨胀维度，并将深度可分离卷积引入其中。\n\n这个新的残差模块被作者称为「带有线性瓶颈的反转残差」（Inverted residual with linear bottleneck.）。\n\n### 反转残差\n\n![Inverted Residual](/content/papers/assets/e6bbfb346bb449f83897d76b69c3711d2e9937d40320a7aab0f3843653a688c0.jpg)\n\n整个残差模块的修改如上图所示。\n\n1. 把原本 ResNet 中压缩维度的 1x1 卷积层换成了扩展维度的 1x1 卷积层。\n2. 把原本 3x3 卷积层换成了 3x3 深度卷积，并用最后的 1x1 逐点卷积投影回较窄的通道数。\n3. 扩展层与深度卷积后使用 ReLU6；最后的投影层保持线性，残差相加后也不再接 ReLU。\n\n图中也可以看到，步长为 1 且通道数相同时才加入捷径；步长为 2 的单元没有这条捷径。\n\n### 扩张瓶颈（论文附录 A）\n\n瓶颈变换涉及两个核心操作：线性变换和 ReLU 激活函数，这一过程可以表示为 $ A \\text{ReLU}(Bx) $：\n\n1. **线性变换 $Bx$：** 在此，$x \\in \\mathbb{R}^n$ 代表一个 n 维的向量，可以是代表图像中的像素点的向量或是任何其他类型的数据。$B$ 是一个 $m \\times n$ 的矩阵，负责将原始的 n 维向量 $x$ 变换到 m 维空间。这一步的目的是在不同的维度上重组输入数据的特征，可能是为了降维（如果 $m < n$）、升维（如果 $m > n$）、或是转换到另一个同维度的空间（如果 $m = n$）。\n\n2. **非线性激活函数 ReLU：** ReLU 函数，即修正线性单元（Rectified Linear Unit），作用于 $Bx$ 的结果。这个函数的数学表示是 $\\text{ReLU}(z) = \\max(0, z)$，其中 $z$ 可以是一个数字或一个向量。对于向量，ReLU 函数对每一元素独立作用。这一步引入了非线性特性，有助于增加模型的表达能力，因为线性模型无法捕捉到复杂的数据结构和模式。\n\n3. **第二层线性变换 A：** 经过 ReLU 激活后的结果再次被一个 $n \\times m$ 的矩阵 $A$ 变换。这一步可以进一步调整特征，使其适合于后续的神经网络层或最终的输出要求。\n\n在分析瓶颈变换的效果时，首先要考虑 m（输出维度）和 n（输入维度）的关系：\n\n- **当 m ≤ n 时**：此类变换可能在保持非线性的同时，会有信息损失。因为当输出维度小于或等于输入维度时，一些输入信息在经过转换后无法完全恢复。\n- **当 n < m 时**：这种变换不仅能表达强烈的非线性，而且在论文的矩阵与初始化假设下，$\\text{ReLU}(Bx)$ 有较高概率保留足够信息以恢复原始输入；并非只要扩张维度就一定可逆。\n\n最后，作者指出扩展层的瓶颈结构不仅能防止流形崩塌（即信息丧失），还能帮助网络表示更复杂的函数。\n\n### 模型架构\n\n最后就是整个模型的架构。相比于 MobileNetV1，MobileNetV2 在通道数与步长允许时加入残差连接。\n\n以下还有一点篇幅，我们直接来实现一下吧。\n\n```python\nimport torch.nn as nn\n\n\nclass InvertResidual(nn.Module):\n\n    def __init__(self, inp, oup, stride, expand_ratio):\n        super(InvertResidual, self).__init__()\n        self.stride = stride\n        self.is_shortcut = stride == 1 and inp == oup\n        hidden_dim = int(inp * expand_ratio)\n\n        layers = []\n        if expand_ratio != 1:\n            layers.extend([\n                nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),\n                nn.BatchNorm2d(hidden_dim),\n                nn.ReLU6(),\n            ])\n        layers.extend([\n            # dw\n            nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n            nn.BatchNorm2d(hidden_dim),\n            nn.ReLU6(),\n            # pw-linear\n            nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n            nn.BatchNorm2d(oup),\n        ])\n        self.conv = nn.Sequential(*layers)\n\n    def forward(self, x):\n        if self.is_shortcut:\n            return x + self.conv(x)\n        else:\n            return self.conv(x)\n```\n\n做完模块，再来就是把模型串起来。\n\n先参考一下论文的配置：\n\n\n\n![Model Config](/content/papers/assets/9912ae0c832611f178c3354b7ca40a50fb1ad77813e6742739e7976b23521bc4.jpg)\n\n\n\n输入图片大小为 224x224，输出类别数为 1000......\n\n呃，这里先不处理这些参数；我们只实现特征提取主体。\n\n论文中有提到需要缩放模型，因此我们需要有个可以缩放模型宽度的参数 `width_mult`。\n\n这里我们撇开最后的输出层，只实现模型的主体部分，也就是特征提取部分。\n\n```python\nimport torch.nn as nn\n\nclass MobileNetV2(nn.Module):\n\n    def __init__(self, width_mult=1.):\n        super(MobileNetV2, self).__init__()\n\n        # setting of inverted residual blocks\n        self.settings = [\n            # t, c, n, s\n            [1, 16, 1, 1],\n            [6, 24, 2, 2],\n            [6, 32, 3, 2],\n            [6, 64, 4, 2],\n            [6, 96, 3, 1],\n            [6, 160, 3, 2],\n            [6, 320, 1, 1],\n        ]\n\n        # building first layer\n        input_channel = int(32 * width_mult)\n        self.first_layer = nn.Sequential(\n            nn.Conv2d(3, input_channel, 3, 2, 1, bias=False),\n            nn.BatchNorm2d(input_channel),\n            nn.ReLU6()\n        )\n\n        # building inverted residual blocks\n        layers = []\n        for t, c, n, s in self.settings:\n            output_channel = int(c * width_mult)\n            for i in range(n):\n                layers.append(\n                    InvertResidual(\n                        input_channel,\n                        output_channel,\n                        stride=s if i == 0 else 1,\n                        expand_ratio=t\n                    )\n                )\n                input_channel = output_channel\n        self.layers = nn.Sequential(*layers)\n\n        # building last several layers\n        last_channel = int(1280 * width_mult) if width_mult > 1.0 else 1280\n        self.last_layer = nn.Sequential(\n            nn.Conv2d(input_channel, last_channel, 1, 1, 0, bias=False),\n            nn.BatchNorm2d(last_channel),\n            nn.ReLU6()\n        )\n\n    def forward(self, x):\n        x = self.first_layer(x)\n        x = self.layers(x)\n        x = self.last_layer(x)\n        return x\n```\n\n\n> [!TIP]\n> \n> **为什么 nn.Conv2d 的 bias 设为 False？**\n> \n> 因为我们在 `Batch Normalization` 中已经有了偏移项，因此不需要再在 Conv2d 中加入偏移项。\n\n\n## 讨论\n\n### 图像分类性能\n\n\n\n![ImageNet Performance](/content/papers/assets/e815ff29a16e2d442671792e9bb137ca24e052e380d8c20ba3c737eb30b4db8c.jpg)\n\n\n\n从上表可以看到，MobileNetV2 在 ImageNet 上的表现比 MobileNetV1 有所提升。\n\n在乘加运算量从 575M 降至 300M 的同时，MobileNetV2 的 top-1 准确率比 MobileNetV1 高了 1.4 个百分点；表中的 Pixel 1 单核心推论时间也从 113 ms 降至 75 ms。\n\n- 在约 300M 乘加运算的量级上，MobileNetV2 的 top-1 准确率为 72.0%，高于表中 ShuffleNet 1.5× 的 71.5%；表中没有 ShuffleNet 的 CPU 时间。\n- 在约 600M 乘加运算的量级上，MobileNetV2 1.4× 的 top-1 准确率为 74.7%，高于 NASNet-A 的 74.0%；表中的 Pixel 1 单核心推论时间分别为 143 ms 与 183 ms。\n\n## 结论\n\n在这篇研究中，作者展示了 MobileNetV2 如何应对移动设备对准确率和低计算量的需求。\n\n线性瓶颈层和反转残差模块的使用，允许模型在保持轻量级的同时，有效地管理信息流，减少信息在传递过程中的损失。\n\n这种设计理念不仅提高了模型对输入数据的表达能力，也提升了在移动设备上的性能表现。\n\n未来的工作将继续探索这一架构的潜力，寻求在保持模型轻量化的同时，进一步提升性能和泛化能力。\n","imageSizes":{"/content/papers/assets/fa9960be3fd190fa1e6d1ebd0b00627a733a63b5276603aa9a880b62e851fc25.jpg":{"width":1588,"height":268},"/content/papers/assets/a582ed00a15da709c6839e653f84f694e1170cc83d0846fa897c62d1819e986c.jpg":{"width":730,"height":574},"/content/papers/assets/e6bbfb346bb449f83897d76b69c3711d2e9937d40320a7aab0f3843653a688c0.jpg":{"width":2332,"height":1324},"/content/papers/assets/9912ae0c832611f178c3354b7ca40a50fb1ad77813e6742739e7976b23521bc4.jpg":{"width":1032,"height":784},"/content/papers/assets/e815ff29a16e2d442671792e9bb137ca24e052e380d8c20ba3c737eb30b4db8c.jpg":{"width":1156,"height":496}}}
