YOLOv11改进 | 主干/Backbone篇 | 轻量化ConvNeXtV2全卷积掩码自编码器目标检测网络(适配yolov11全系列)

一、本文介绍

本文给大家带来的改进机制是ConvNeXtV2网络, ConvNeXt V2 是一种新型的卷积 神经网络 架构,它融合了 自监督学习 技术和架构改进,特别是加入了 全卷积掩码自编码器框架 全局响应归一化(GRN)层 。我将其替换YOLOv11的特征提取网络,用于提取更有用的特征。经过我的实验该主干网络确实能够涨点在大中小三种物体检测上, 同时该主干网络也提供多种版本 ,大家可以在 源代码 中进行修改版本的使用。 本文通过介绍其主要框架原理,然后教大家如何添加该网络结构到网络模型中。

(本文内容可根据yolov11的N、S、M、L、X进行二次缩放,轻量化更上一层)。


目录

一、本文介绍

二、ConvNeXt V2架构原理

2.1 ConvNeXt V2的基本原理

2.2 架构创新

三、ConvNeXt V2的核心代码

四、手把手教你添加ConvNeXt V2机制

修改一

修改二

修改三

修改四

修改五

修改六

修改七

修改八

五、ConvNeXt V2的yaml文件

六、成功运行记录

七、本文总结


二、ConvNeXt V2架构原理

论文地址: 官方论文地址

代码地址: 官方代码地址


2.1 ConvNeXt V2的基本原理

ConvNeXt V2 是一种新型的 卷积神经网络 架构,它融合了自监督学习技术和架构改进,特别是加入了 全卷积掩码自编码器框架 全局响应归一化(GRN)层 。这些创新显著提升了纯ConvNet在多个识别基准测试上的性能,如ImageNet分类、COCO检测和ADE20K分割。ConvNeXt V2还包括从效率型的3.7M参数Atto模型到650M参数的Huge模型的多个版本,覆盖了从轻量级到高性能的各种应用需求。

ConvNeXt V2的核心要点包括:

1. 架构创新: 融合全卷积掩码自编码器框架和全局响应归一化(GRN)层,优化了原有ConvNeXt架构。
2. 自监督学习: 利用自监督学习技术提高了模型的泛化能力和效率。

下图为大家 比较了ConvNeXt V1和ConvNeXt V2两个版本中的块设计

在ConvNeXt V2块中,新增加了 全局响应归一化(GRN)层 ,并且由于GRN层的引入,原先的LayerScale层变得多余,因此在V2版本中被去除。这些变化旨在优化网络的特征表示和提高模型的学习效率。


2.2 架构创新

ConvNeXt V2 架构创新 主要体现在以下几个方面:

1. 全卷积掩码自动编码器(FCMAE): 采用全卷积方法处理图像,特别适合处理带有掩码的图像数据。

2. 全局响应归一化(GRN)层: 在卷积块中引入GRN层,增强了模型处理信息时的通道间竞争,提高特征表达的质量。

3. 去除LayerScale层: 因为GRN层的加入,原来的LayerScale层变得多余,在V2架构中被移除,简化了模型结构。

这张图展示了 ConvNeXt V2中提出的全卷积掩码自动编码器(FCMAE)框架

在这张图中,ConvNeXt V2的FCMAE框架采用了 稀疏卷积技术 作为其编码器的核心,这是为了有效地处理输入图像中的非掩蔽(可见)像素。 编码器结构层次化 ,有助于捕获不同层级的特征信息。解码器相对简单,使用轻量级的ConvNeXt块,目的是重构图像,但仅限于目标(即被掩蔽的)区域。这种不对称设计允许模型在预训练时专注于关键区域,这对于图像的自监督学习特别有效。 损失函数 的计算仅在掩蔽的区域进行,进一步强化了模型对于目标区域的学习和重构能力。


三、ConvNeXt V2的核心代码

使用方式看章节四

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from timm.models.layers import trunc_normal_, DropPath
  5. __all__ = ['convnextv2_atto', 'convnextv2_femto', 'convnext_pico', 'convnextv2_nano', 'convnextv2_tiny', 'convnextv2_base', 'convnextv2_large', 'convnextv2_huge']
  6. class LayerNorm(nn.Module):
  7. """ LayerNorm that supports two data formats: channels_last (default) or channels_first.
  8. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  9. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  10. with shape (batch_size, channels, height, width).
  11. """
  12. def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
  13. super().__init__()
  14. self.weight = nn.Parameter(torch.ones(normalized_shape))
  15. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  16. self.eps = eps
  17. self.data_format = data_format
  18. if self.data_format not in ["channels_last", "channels_first"]:
  19. raise NotImplementedError
  20. self.normalized_shape = (normalized_shape,)
  21. def forward(self, x):
  22. if self.data_format == "channels_last":
  23. return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
  24. elif self.data_format == "channels_first":
  25. u = x.mean(1, keepdim=True)
  26. s = (x - u).pow(2).mean(1, keepdim=True)
  27. x = (x - u) / torch.sqrt(s + self.eps)
  28. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  29. return x
  30. class GRN(nn.Module):
  31. """ GRN (Global Response Normalization) layer
  32. """
  33. def __init__(self, dim):
  34. super().__init__()
  35. self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
  36. self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
  37. def forward(self, x):
  38. Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
  39. Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
  40. return self.gamma * (x * Nx) + self.beta + x
  41. class Block(nn.Module):
  42. """ ConvNeXtV2 Block.
  43. Args:
  44. dim (int): Number of input channels.
  45. drop_path (float): Stochastic depth rate. Default: 0.0
  46. """
  47. def __init__(self, dim, drop_path=0.):
  48. super().__init__()
  49. self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
  50. self.norm = LayerNorm(dim, eps=1e-6)
  51. self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
  52. self.act = nn.GELU()
  53. self.grn = GRN(4 * dim)
  54. self.pwconv2 = nn.Linear(4 * dim, dim)
  55. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  56. def forward(self, x):
  57. input = x
  58. x = self.dwconv(x)
  59. x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
  60. x = self.norm(x)
  61. x = self.pwconv1(x)
  62. x = self.act(x)
  63. x = self.grn(x)
  64. x = self.pwconv2(x)
  65. x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
  66. x = input + self.drop_path(x)
  67. return x
  68. class ConvNeXtV2(nn.Module):
  69. """ ConvNeXt V2
  70. Args:
  71. in_chans (int): Number of input image channels. Default: 3
  72. num_classes (int): Number of classes for classification head. Default: 1000
  73. depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
  74. dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
  75. drop_path_rate (float): Stochastic depth rate. Default: 0.
  76. head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
  77. """
  78. def __init__(self, factor, in_chans=3, num_classes=1000,
  79. depths=[3, 3, 9, 3], dims=[96, 192, 384, 768],
  80. drop_path_rate=0., head_init_scale=1.
  81. ):
  82. super().__init__()
  83. dims = [int(dim * factor) for dim in dims]
  84. self.depths = depths
  85. self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers
  86. stem = nn.Sequential(
  87. nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
  88. LayerNorm(dims[0], eps=1e-6, data_format="channels_first")
  89. )
  90. self.downsample_layers.append(stem)
  91. for i in range(3):
  92. downsample_layer = nn.Sequential(
  93. LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
  94. nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2),
  95. )
  96. self.downsample_layers.append(downsample_layer)
  97. self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
  98. dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
  99. cur = 0
  100. for i in range(4):
  101. stage = nn.Sequential(
  102. *[Block(dim=dims[i], drop_path=dp_rates[cur + j]) for j in range(depths[i])]
  103. )
  104. self.stages.append(stage)
  105. cur += depths[i]
  106. self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
  107. self.head = nn.Linear(dims[-1], num_classes)
  108. self.apply(self._init_weights)
  109. self.head.weight.data.mul_(head_init_scale)
  110. self.head.bias.data.mul_(head_init_scale)
  111. self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
  112. def _init_weights(self, m):
  113. if isinstance(m, (nn.Conv2d, nn.Linear)):
  114. trunc_normal_(m.weight, std=.02)
  115. nn.init.constant_(m.bias, 0)
  116. def forward(self, x):
  117. results = []
  118. for i in range(4):
  119. x = self.downsample_layers[i](x)
  120. x = self.stages[i](x)
  121. results.append(x)
  122. return results # global average pooling, (N, C, H, W) -> (N, C)
  123. def convnextv2_atto(factor):
  124. model = ConvNeXtV2(factor=factor, depths=[2, 2, 6, 2], dims=[40, 80, 160, 320])
  125. return model
  126. def convnextv2_femto(factor):
  127. model = ConvNeXtV2(factor=factor, depths=[2, 2, 6, 2], dims=[48, 96, 192, 384])
  128. return model
  129. def convnext_pico(factor):
  130. model = ConvNeXtV2(factor=factor, depths=[2, 2, 6, 2], dims=[64, 128, 256, 512])
  131. return model
  132. def convnextv2_nano(factor):
  133. model = ConvNeXtV2(factor=factor, depths=[2, 2, 8, 2], dims=[80, 160, 320, 640])
  134. return model
  135. def convnextv2_tiny(factor):
  136. model = ConvNeXtV2(factor=factor, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768])
  137. return model
  138. def convnextv2_base(factor):
  139. model = ConvNeXtV2(factor=factor, depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024])
  140. return model
  141. def convnextv2_large(factor):
  142. model = ConvNeXtV2(factor=factor, depths=[3, 3, 27, 3], dims=[192, 384, 768, 1536])
  143. return model
  144. def convnextv2_huge(factor):
  145. model = ConvNeXtV2(factor=factor, depths=[3, 3, 27, 3], dims=[352, 704, 1408, 2816])
  146. return model
  147. if __name__ == "__main__":
  148. model = convnextv2_atto(factor=0.5)
  149. inputs = torch.randn((1, 3, 640, 640))
  150. for i in model(inputs):
  151. print(i.size())


四、手把手教你添加ConvNeXt V2机制

4.1 修改一

第一步还是建立文件,我们找到如下ultralytics/nn文件夹下建立一个目录名字呢就是'Addmodules'文件夹( !然后在其内部建立一个新的py文件将核心代码复制粘贴进去即可


4.2 修改二

第二步我们在该目录下创建一个新的py文件名字为'__init__.py'( ,然后在其内部导入我们的检测头如下图所示。


4.3 修改三

第三步我门中到如下文件'ultralytics/nn/tasks.py'进行导入和注册我们的模块( !


4.4 修改四

添加如下两行代码!!!


4.5 修改五

找到七百多行大概把具体看图片,按照图片来修改就行,添加红框内的部分,注意没有()只是 函数 名。

  1. elif m in {convnextv2_atto, convnextv2_femto, convnext_pico, convnextv2_nano, convnextv2_tiny, convnextv2_base, convnextv2_large, convnextv2_huge}:
  2. m = m(*args)
  3. c2 = m.width_list # 返回通道列表
  4. backbone = True


4.6 修改六

下面的两个红框内都是需要改动的。

  1. if isinstance(c2, list):
  2. m_ = m
  3. m_.backbone = True
  4. else:
  5. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  6. t = str(m)[8:-2].replace('__main__.', '') # module type
  7. m.np = sum(x.numel() for x in m_.parameters()) # number params
  8. m_.i, m_.f, m_.type = i + 4 if backbone else i, f, t # attach index, 'from' index, type


4.7 修改七

如下的也需要修改,全部按照我的来。

代码如下把原先的代码替换了即可。

  1. if verbose:
  2. LOGGER.info(f'{i:>3}{str(f):>20}{n_:>3}{m.np:10.0f} {t:<45}{str(args):<30}') # print
  3. save.extend(x % (i + 4 if backbone else i) for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  4. layers.append(m_)
  5. if i == 0:
  6. ch = []
  7. if isinstance(c2, list):
  8. ch.extend(c2)
  9. if len(c2) != 5:
  10. ch.insert(0, 0)
  11. else:
  12. ch.append(c2)


4.8 修改八

修改八和前面的都不太一样,需要修改前向传播中的一个部分, 已经离开了parse_model方法了。

可以在图片中开代码行数,没有离开task.py文件都是同一个文件。 同时这个部分有好几个前向传播都很相似,大家不要看错了, 是70多行左右的!!!,同时我后面提供了代码,大家直接复制粘贴即可,有时间我针对这里会出一个视频。

​​

代码如下->

  1. def _predict_once(self, x, profile=False, visualize=False, embed=None):
  2. """
  3. Perform a forward pass through the network.
  4. Args:
  5. x (torch.Tensor): The input tensor to the model.
  6. profile (bool): Print the computation time of each layer if True, defaults to False.
  7. visualize (bool): Save the feature maps of the model if True, defaults to False.
  8. embed (list, optional): A list of feature vectors/embeddings to return.
  9. Returns:
  10. (torch.Tensor): The last output of the model.
  11. """
  12. y, dt, embeddings = [], [], [] # outputs
  13. for m in self.model:
  14. if m.f != -1: # if not from previous layer
  15. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  16. if profile:
  17. self._profile_one_layer(m, x, dt)
  18. if hasattr(m, 'backbone'):
  19. x = m(x)
  20. if len(x) != 5: # 0 - 5
  21. x.insert(0, None)
  22. for index, i in enumerate(x):
  23. if index in self.save:
  24. y.append(i)
  25. else:
  26. y.append(None)
  27. x = x[-1] # 最后一个输出传给下一层
  28. else:
  29. x = m(x) # run
  30. y.append(x if m.i in self.save else None) # save output
  31. if visualize:
  32. feature_visualization(x, m.type, m.i, save_dir=visualize)
  33. if embed and m.i in embed:
  34. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  35. if m.i == max(embed):
  36. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  37. return x

到这里就完成了修改部分,但是这里面细节很多,大家千万要注意不要替换多余的代码,导致报错,也不要拉下任何一部,都会导致运行失败,而且报错很难排查!!!很难排查!!!


注意!!! 额外的修改!

关注我的其实都知道,我大部分的修改都是一样的,这个网络需要额外的修改一步,就是s一个参数,将下面的s改为640!!!即可完美运行!!


打印计算量问题解决方案

我们找到如下文件'ultralytics/utils/torch_utils.py'按照如下的图片进行修改,否则容易打印不出来计算量。


注意事项!!!

如果大家在验证的时候报错形状不匹配的错误可以固定验证集的图片尺寸,方法如下 ->

找到下面这个文件ultralytics/ models /yolo/detect/train.py然后其中有一个类是DetectionTrainer class中的build_dataset函数中的一个参数rect=mode == 'val'改为rect=False


五、 Convnextv2 的yaml文件

5.1 Convnextv2 的yaml文件

训练信息:YOLO11-ConvNeXtV2 summary: 325 layers, 2,597,387 parameters, 2,597,371 gradients, 5.9 GFLOP

使用说明:#使用说明:# 下面 [-1, 1, convnextv2_atto, [0.25]] 参数位置的0.25是通道放缩的系数, YOLOv11N是0.25 YOLOv11S是0.5 YOLOv11M是1. YOLOv11l是1 YOLOv11是1.5大家根据自己训练的YOLO版本设定即可.
# 本文支持版本有 'convnextv2_atto', 'convnextv2_femto', 'convnext_pico', 'convnextv2_nano', 'convnextv2_tiny', 'convnextv2_base', 'convnextv2_large', 'convnextv2_huge'

  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
  3. # Parameters
  4. nc: 80 # number of classes
  5. scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
  6. # [depth, width, max_channels]
  7. n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
  8. s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
  9. m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
  10. l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
  11. x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
  12. # 下面 [-1, 1, convnextv2_atto, [0.25]] 参数位置的0.25是通道放缩的系数, YOLOv11N是0.25 YOLOv11S是0.5 YOLOv11M是1. YOLOv11l是1 YOLOv111.5大家根据自己训练的YOLO版本设定即可.
  13. # 本文支持版本有 'convnextv2_atto', 'convnextv2_femto', 'convnext_pico', 'convnextv2_nano', 'convnextv2_tiny', 'convnextv2_base', 'convnextv2_large', 'convnextv2_huge'
  14. # YOLO11n backbone
  15. backbone:
  16. # [from, repeats, module, args]
  17. - [-1, 1, convnextv2_atto, [0.5]] # 0-4 P1/2 这里是四层大家不要被yaml文件限制住了思维.
  18. - [-1, 1, SPPF, [1024, 5]] # 5
  19. - [-1, 2, C2PSA, [1024]] # 6
  20. # YOLO11n head
  21. head:
  22. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  23. - [[-1, 3], 1, Concat, [1]] # cat backbone P4
  24. - [-1, 2, C3k2, [512, False]] # 9
  25. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  26. - [[-1, 2], 1, Concat, [1]] # cat backbone P3
  27. - [-1, 2, C3k2, [256, False]] # 12 (P3/8-small)
  28. - [-1, 1, Conv, [256, 3, 2]]
  29. - [[-1, 9], 1, Concat, [1]] # cat head P4
  30. - [-1, 2, C3k2, [512, False]] # 15 (P4/16-medium)
  31. - [-1, 1, Conv, [512, 3, 2]]
  32. - [[-1, 6], 1, Concat, [1]] # cat head P5
  33. - [-1, 2, C3k2, [1024, True]] # 18 (P5/32-large)
  34. - [[12, 15, 18], 1, Detect, [nc]] # Detect(P3, P4, P5)


5.2 训练文件的代码

可以复制我的运行文件进行运行。

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO('yolov8-MLLA.yaml')
  6. # 如何切换模型版本, 上面的ymal文件可以改为 yolov8s.yaml就是使用的v8s,
  7. # 类似某个改进的yaml文件名称为yolov8-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov8l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
  8. # model.load('yolov8n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
  9. model.train(data=r"C:\Users\Administrator\PycharmProjects\yolov5-master\yolov5-master\Construction Site Safety.v30-raw-images_latestversion.yolov8\data.yaml",
  10. # 如果大家任务是其它的'ultralytics/cfg/default.yaml'找到这里修改task可以改成detect, segment, classify, pose
  11. cache=False,
  12. imgsz=640,
  13. epochs=150,
  14. single_cls=False, # 是否是单类别检测
  15. batch=16,
  16. close_mosaic=0,
  17. workers=0,
  18. device='0',
  19. optimizer='SGD', # using SGD
  20. # resume='runs/train/exp21/weights/last.pt', # 如过想续训就设置last.pt的地址
  21. amp=True, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


六、成功运行记录

下面是成功运行的截图,已经完成了有1个epochs的训练,图片太大截不全第2个epochs了。


七、本文总结

到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充 如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~