[Algorithm] BEVformer 源码细节学习&&ubuntu20.04下的情况配置&&目标跑起 ...

打印 上一主题 下一主题

主题 554|帖子 554|积分 1662

写在前面

筹划从源码和先跑起来入手,随后分模块逐步学习。期间分享自己的狐疑,风趣高效的语法征象。
之前学习了机器学习和神经网络(RNN) pytorch利用等相关知识,举行了两个demo的实战
如果对安装不感兴趣,欢迎大佬们阅读第二步交换辅导。
学习资源 (不断更新)



  • 深蓝学院
  • 好老哥的解读论文
  • bilibili小哥论文学习视频,有点乱
  • 事后瞥见的复现老哥早瞥见就抄作业了,22下安装太折腾了
  • 解读1
  • 解读2
第一步目标把开源代码跑起来

情况预备

https://zhuanlan.zhihu.com/p/424817205
可以按照以上内容先安装号显卡驱动、Cuda和配置路径。
显卡驱动安装后 我用smi表现不出来显卡信息。

我显着在自带的software中心中的driver选择了驱动,但是smi下令找不到显卡信息,末了通过gpt查询,原来显卡驱动不停没有加载。因为我开起来secure boot的签名验证。关闭secure boot 就好了。

BEV 相关情况预备

首先 conda 和pip换源操纵可以参考:https://blog.csdn.net/h904798869/article/details/131719404
大概单用
  1. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple +包名
复制代码
阿里云镜像:https://mirrors.aliyun.com/pypi/simple/
清华大学镜像:https://pypi.tuna.tsinghua.edu.cn/simple/
安装建议严格按照文档阐明来,其中mmdection的内容建议按照maptr的来
BEVFormer
MapTR
其中:


  • Building wheel for mmcv-full (setup.py) … / 这一步很慢,安心等待
  • mmdection 用maptr的方法安装
  • https://github.com/zhiqi-li/storage/releases 这里我是用Windows的梯直接去仓库拿的,贼快
  • 包罗预练习参数也可以直接挂梯子作者仓库去拿download
  • 安装cuda,cuda是系统级的东西不会在自己conda假造情况下,安装完成后别忘记添加路径,同时如果驱动安装好了就不必安装cuda自带的驱动,这里都有写明白https://blog.csdn.net/h904798869/article/details/131719404

记载我安装的几个问题 :

第一个大报错 是mmdetection编译报错,
查询了很久 发现根源是我的系统找不到有用的cuda
这里贴两个帖子,他们在讲解 pytorch cuda 和显卡驱动的 辩证关系
基本就是在排查 GPU驱动 Cuda版本 Pytorch版本之间的问题
https://zhuanlan.zhihu.com/p/658800083
https://zhuanlan.zhihu.com/p/91334380 我以为这个讲的最好
https://blog.csdn.net/qq_41094058/article/details/116207333
各人也可以利用我下面的代码验证以下
驱动安装阐明
用nvcc -v可以看到cuda版本
在conda list中确认其他库的版本
lspci | grep -i nvidia 检察显卡型号
  1. import torch
  2. print('CUDA 可用:', torch.cuda.is_available())
  3. if torch.cuda.is_available():
  4.     print('可用的 CUDA 设备数:', torch.cuda.device_count())
  5.     print('当前 CUDA 设备索引:', torch.cuda.current_device())
  6.     print('当前 CUDA 设备名称:', torch.cuda.get_device_name(torch.cuda.current_device()))
  7. else:
  8.     print('CUDA 不可用')
  9. import torch, torchvision
  10. print(torch.__version__, torch.cuda.is_available())
  11. # Pytorch 实际使用的运行时的 cuda 目录
  12. import torch.utils.cpp_extension
  13. print(torch.utils.cpp_extension.CUDA_HOME)
  14. # 编译该 Pytorch release 版本时使用的 cuda 版本
  15. import torch
  16. print(torch.version.cuda )
复制代码
如果pytorch成功导入了,但是出现false 则阐明cuda设备不可用,可以去NVidia官网自动查找对应驱动https://www.nvidia.com/Download/index.aspx
以下是cuda的安装地址
https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=22.04&target_type=runfile_local
此外也可以利用ubantu系统自己查到的驱动
大概也可以利用
如此我可以利用上面的代码打印出内容了

我的nvidia-smi下令也可以正常输出了
但依然有报错
我cuda toolkit和 nvidia driver是版本是可以匹配的,但cuda版本太高了我去
然后重新严格安装配情况教程安装了cuda,不寻求自己研究了


  • 第二个大报错 安装 Detectron2
  1. python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
复制代码
长时间等待而后报错
  1. git clone git@github.com:facebookresearch/detectron2.git
复制代码
然后本地安装
  1. pip install .
复制代码
第一次接触的库的条记:
mmcv-full是一个针对盘算机视觉任务的开源工具库
MMDetection(Masked Object Detection)是一个开源盘算机视觉库,用于目标检测任务。它提供了丰富的目标检测算法和模型,包罗 Faster R-CNN、Mask R-CNN 等
MMsegmentation(Image Segmentation)是一个开源盘算机视觉库,用于图像分割任务。它包罗了多种图像分割算法和模型,如 U-Net、DeepLabV3 等。
Detectron2 是由Facebook AI Research(FAIR)开辟的开源目标检测库。它是原始 Detectron 库的继任者,为构建盘算机视觉模型提供了机动和模块化的框架,特别实用于目标检测和实例分割等任务
数据集下载

下载车身can数据、车辆位姿数据、地图场景数据、Camera Lidar传感器数据
把map解压后的三个文件放入到mini的maps文件夹中
展示结构如下

将data放入beformer下,然后
  1. python tools/create_data.py nuscenes --root-path ./data/nuscenes --out-dir ./data/nuscenes --extra-tag nuscenes --version v1.0-mini --canbus ./data
复制代码
在其后按照提示和教程缺啥补啥

报错就把这里将所有的data.converter 前面的tools去掉
练习 测试 画图

BEV复现教程 结果如下,看起来还不太正确。
情况和数据整理完毕后,按照教程举行,我的显卡可以跑small 和Tiny,把base更换成一位上即可。

第二步开始论文具体阅读和代码解读
第二步论文阅读

论文初步阅读


两个留意力机制为代码和文章重点解读部分

论文细节阅读

代码结构

模型结构利用config管理参数的方式,在bevformer_XXX.py中是参数,具体的模型搭建其着实bevformer_head.py中 组件在modules中可以找到

再次整理细节重点学习 (全代码阅读 TSA SCA MSD,后面两节按照实行顺序总结的代码整理较乱,日后缓慢更新 )

重点是Encoder中的 BEVFormerLayer,有作者提出的Temporalsellfattention SpatialCrossAttention 和可变形留意力
由于代码利用了注册器,不太好直接探求跳转链路,可以利用断点的方式按照顺序阅读。这里不做顺序阅读,而是将multi_scale_deformable_attn_function.py、spatial_cross_attention.py、temporal_self_attention.py的内容,有代价的每一句做注释解读,贴在下面。拓展语法和概念等则写于本章末了面。
temporal_self_attention.py 的解读

  1. # ---------------------------------------------
  2. # Copyright (c) OpenMMLab. All rights reserved.
  3. # ---------------------------------------------
  4. #  Modified by Zhiqi Li
  5. # ---------------------------------------------
  6. from projects.mmdet3d_plugin.models.utils.bricks import run_time
  7. from .multi_scale_deformable_attn_function import MultiScaleDeformableAttnFunction_fp32
  8. from mmcv.ops.multi_scale_deform_attn import multi_scale_deformable_attn_pytorch
  9. import warnings
  10. import torch
  11. import torch.nn as nn
  12. from mmcv.cnn import xavier_init, constant_init
  13. from mmcv.cnn.bricks.registry import ATTENTION
  14. import math
  15. from mmcv.runner.base_module import BaseModule, ModuleList, Sequential
  16. from mmcv.utils import (ConfigDict, build_from_cfg, deprecated_api_warning,
  17.                         to_2tuple)
  18. from mmcv.utils import ext_loader
  19. ext_module = ext_loader.load_ext(
  20.     '_ext', ['ms_deform_attn_backward', 'ms_deform_attn_forward'])
  21. @ATTENTION.register_module()
  22. class TemporalSelfAttention(BaseModule):
  23.     """An attention module used in BEVFormer based on Deformable-Detr.
  24.     `Deformable DETR: Deformable Transformers for End-to-End Object Detection.
  25.     <https://arxiv.org/pdf/2010.04159.pdf>`_.
  26.     Args:
  27.         embed_dims (int): The embedding dimension of Attention.
  28.             Default: 256.
  29.         num_heads (int): Parallel attention heads. Default: 64.
  30.         num_levels (int): The number of feature map used in
  31.             Attention. Default: 4.
  32.         num_points (int): The number of sampling points for
  33.             each query in each head. Default: 4.
  34.         im2col_step (int): The step used in image_to_column.
  35.             Default: 64.
  36.         dropout (float): A Dropout layer on `inp_identity`.
  37.             Default: 0.1.
  38.         batch_first (bool): Key, Query and Value are shape of
  39.             (batch, n, embed_dim)
  40.             or (n, batch, embed_dim). Default to True.
  41.         norm_cfg (dict): Config dict for normalization layer.
  42.             Default: None.
  43.         init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
  44.             Default: None.
  45.         num_bev_queue (int): In this version, we only use one history BEV and one currenct BEV.
  46.          the length of BEV queue is 2.
  47.     """
  48. # embed_dims (int): 注意力机制的嵌入维度。
  49. # num_heads (int): 注意力机制中并行的注意头数。
  50. # num_levels (int): 使用的特征图的数量。
  51. # num_points (int): 每个注意头中每个查询点的采样点数。
  52. # im2col_step (int): 在图像到列矩阵转换中使用的步长。
  53. # dropout (float): 应用于 inp_identity 的 Dropout 层的丢弃率。
  54. # batch_first (bool): Key、Query 和 Value 的形状是否为 (batch, n, embed_dim) 或 (n, batch, embed_dim)。
  55. # norm_cfg (dict): 用于规范化层的配置字典。
  56. # init_cfg (obj: mmcv.ConfigDict): 用于初始化的配置对象。
  57. # num_bev_queue (int): 在这个版本中,我们只使用一个历史 Bird's Eye View(BEV)和一个当前 BEV。BEV 队列的长度为 2。
  58.     def __init__(self,
  59.                  embed_dims=256,
  60.                  num_heads=8,
  61.                  num_levels=4,
  62.                  num_points=4,
  63.                  num_bev_queue=2,
  64.                  im2col_step=64,
  65.                  dropout=0.1,
  66.                  batch_first=True,
  67.                  norm_cfg=None,
  68.                  init_cfg=None):
  69.         super().__init__(init_cfg)
  70.         if embed_dims % num_heads != 0:#检查 embed_dims 特征维度是否可以被 num_heads 多头数量 整除,否则引发错误。
  71.             raise ValueError(f'embed_dims must be divisible by num_heads, '
  72.                              f'but got {embed_dims} and {num_heads}')
  73.         dim_per_head = embed_dims // num_heads # 多头注意力量 划分特征
  74.         self.norm_cfg = norm_cfg
  75.         self.dropout = nn.Dropout(dropout)
  76.         self.batch_first = batch_first
  77.         self.fp16_enabled = False
  78.         # you'd better set dim_per_head to a power of 2
  79.         # which is more efficient in the CUDA implementation
  80.         def _is_power_of_2(n):
  81.             if (not isinstance(n, int)) or (n < 0):
  82.                 raise ValueError(
  83.                     'invalid input for _is_power_of_2: {} (type: {})'.format(
  84.                         n, type(n)))
  85.             return (n & (n - 1) == 0) and n != 0
  86.         if not _is_power_of_2(dim_per_head):
  87.             warnings.warn(
  88.                 "You'd better set embed_dims in "
  89.                 'MultiScaleDeformAttention to make '
  90.                 'the dimension of each attention head a power of 2 '
  91.                 'which is more efficient in our CUDA implementation.')
  92.         self.im2col_step = im2col_step
  93.         self.embed_dims = embed_dims
  94.         self.num_levels = num_levels
  95.         self.num_heads = num_heads
  96.         self.num_points = num_points
  97.         self.num_bev_queue = num_bev_queue
  98.         # 用于生成采样偏移的线性层。
  99.         self.sampling_offsets = nn.Linear(
  100.             embed_dims*self.num_bev_queue, num_bev_queue*num_heads * num_levels * num_points * 2)
  101.         # 用于生成注意力权重的线性层
  102.         self.attention_weights = nn.Linear(embed_dims*self.num_bev_queue,                                 
  103.          num_bev_queue*num_heads * num_levels * num_points)
  104.                  #: 用于投影值的线性层。
  105.         self.value_proj = nn.Linear(embed_dims, embed_dims)
  106.         #用于输出投影的线性层。
  107.         self.output_proj = nn.Linear(embed_dims, embed_dims)
  108.         self.init_weights()
  109.     def init_weights(self):
  110.         """Default initialization for Parameters of Module."""
  111.         constant_init(self.sampling_offsets, 0.)
  112.         thetas = torch.arange(
  113.             self.num_heads,
  114.             dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
  115.         grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
  116.         grid_init = (grid_init /
  117.                      grid_init.abs().max(-1, keepdim=True)[0]).view(
  118.             self.num_heads, 1, 1,
  119.             2).repeat(1, self.num_levels*self.num_bev_queue, self.num_points, 1)
  120.         for i in range(self.num_points):
  121.             grid_init[:, :, i, :] *= i + 1
  122.         self.sampling_offsets.bias.data = grid_init.view(-1)
  123.         #用于将参数初始化为常量值。
  124.         constant_init(self.attention_weights, val=0., bias=0.)
  125.         #用于使用 Xavier 初始化参数
  126.         xavier_init(self.value_proj, distribution='uniform', bias=0.)
  127.         xavier_init(self.output_proj, distribution='uniform', bias=0.)
  128.         self._is_init = True
  129.     def forward(self,
  130.                 query,
  131.                 key=None,
  132.                 value=None,
  133.                 identity=None,
  134.                 query_pos=None,
  135.                 key_padding_mask=None,
  136.                 reference_points=None,
  137.                 spatial_shapes=None,
  138.                 level_start_index=None,
  139.                 flag='decoder',
  140.                 **kwargs):
  141.         """Forward Function of MultiScaleDeformAttention.
  142.         Args:
  143.             query (Tensor): Query of Transformer with shape
  144.                 (num_query, bs, embed_dims).
  145.             key (Tensor): The key tensor with shape
  146.                 `(num_key, bs, embed_dims)`.
  147.             value (Tensor): The value tensor with shape
  148.                 `(num_key, bs, embed_dims)`.
  149.             identity (Tensor): The tensor used for addition, with the
  150.                 same shape as `query`. Default None. If None,
  151.                 `query` will be used.
  152.             query_pos (Tensor): The positional encoding for `query`.
  153.                 Default: None.
  154.             key_pos (Tensor): The positional encoding for `key`. Default
  155.                 None.
  156.             reference_points (Tensor):  The normalized reference
  157.                 points with shape (bs, num_query, num_levels, 2),
  158.                 all elements is range in [0, 1], top-left (0,0),
  159.                 bottom-right (1, 1), including padding area.
  160.                 or (N, Length_{query}, num_levels, 4), add
  161.                 additional two dimensions is (w, h) to
  162.                 form reference boxes.
  163.             key_padding_mask (Tensor): ByteTensor for `query`, with
  164.                 shape [bs, num_key].
  165.             spatial_shapes (Tensor): Spatial shape of features in
  166.                 different levels. With shape (num_levels, 2),
  167.                 last dimension represents (h, w).
  168.             level_start_index (Tensor): The start index of each level.
  169.                 A tensor has shape ``(num_levels, )`` and can be represented
  170.                 as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
  171.         Returns:
  172.              Tensor: forwarded results with shape [num_query, bs, embed_dims].
  173.         """
  174. # 输入参数:
  175. # query (Tensor): Transformer 的查询张量,形状为 (num_query, bs, embed_dims)。
  176. # key (Tensor): 键张量,形状为 (num_key, bs, embed_dims)。
  177. # value (Tensor): 值张量,形状为 (num_key, bs, embed_dims)。
  178. # identity (Tensor): 用于加法的张量,与 query 形状相同。如果为None,将使用 query。
  179. # query_pos (Tensor): 用于 query 的位置编码。
  180. # key_padding_mask (Tensor): 用于 query 的 ByteTensor,形状为 [bs, num_key]。
  181. # reference_points (Tensor): 归一化的参考点,形状为 (bs, num_query, num_levels, 2),或 (N, Length_{query}, num_levels, 4)。这用于变形注意力。
  182. # spatial_shapes (Tensor): 不同层级中特征的空间形状,形状为 (num_levels, 2),其中最后一个维度表示 (h, w)。
  183. # level_start_index (Tensor): 每个层级的起始索引,形状为 (num_levels,)。
  184. # 输出:
  185. # 返回值: 形状为 [num_query, bs, embed_dims] 的张量,表示前向传播的结果。
  186. # flag: 一个字符串参数,可能用于指定这个操作是在编码器(encoder)还是解码器(decoder)中。
  187.         if value is None:
  188.             assert self.batch_first
  189.             bs, len_bev, c = query.shape # (num_query, bs, embed_dims)
  190.             value = torch.stack([query, query], 1).reshape(bs*2, len_bev, c)
  191.         #获取 query 张量的形状信息,并利用 torch.stack 和 reshape 函数将其复制为 value 张量
  192.             # value = torch.cat([query, query], 0)
  193.         if identity is None:
  194.             identity = query
  195.         if query_pos is not None:
  196.             query = query + query_pos
  197.             # 将位置编码加入到q中
  198.         if not self.batch_first:
  199.             # change to (bs, num_query ,embed_dims)
  200.             query = query.permute(1, 0, 2)
  201.             value = value.permute(1, 0, 2)
  202.             #按照惯例整理顺序
  203.         bs,  num_query, embed_dims = query.shape
  204.         _, num_value, _ = value.shape# (num_key, bs, embed_dims)
  205.         assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
  206.         # (num_levels, 2),其中最后一个维度表示 (h, w) ???没看懂
  207.         assert self.num_bev_queue == 2
  208.         query = torch.cat([value[:bs], query], -1)
  209.         value = self.value_proj(value)
  210. #将 query 连接到 value 的前部分,并对 value 应用 self.value_proj
  211. # 我的理解,由于value是上一时刻和上上bev的信息,如此增加模型在进行自注意力计算时对上下文的理解,而线性变换
  212. #将输入数据映射到一个更高维度的空间,以便提高模型的表示能力
  213. #gpt说如果一个查询需要依赖较远的位置的信息,通过将值信息添加到查询前面,
  214. # 可以使得模型更容易捕捉到这些长距离的依赖关系,提高了模型对整个序列的建模能力。
  215.         if key_padding_mask is not None:
  216.             value = value.masked_fill(key_padding_mask[..., None], 0.0)
  217. #如果存在 key_padding_mask,则使用 masked_fill 将 value 进行填充
  218.         value = value.reshape(bs*self.num_bev_queue,
  219.                               num_value, self.num_heads, -1)
  220.         sampling_offsets = self.sampling_offsets(query)
  221.         sampling_offsets = sampling_offsets.view(
  222.             bs, num_query, self.num_heads,  self.num_bev_queue, self.num_levels, self.num_points, 2)
  223.         attention_weights = self.attention_weights(query).view(
  224.             bs, num_query,  self.num_heads, self.num_bev_queue, self.num_levels * self.num_points)
  225.         attention_weights = attention_weights.softmax(-1)
  226. # 利用线性层计算采样offset和权重,并且把权重归一化
  227.         attention_weights = attention_weights.view(bs, num_query,
  228.                                                    self.num_heads,
  229.                                                    self.num_bev_queue,
  230.                                                    self.num_levels,
  231.                                                    self.num_points)
  232.         attention_weights = attention_weights.permute(0, 3, 1, 2, 4, 5)\
  233.             .reshape(bs*self.num_bev_queue, num_query, self.num_heads, self.num_levels, self.num_points).contiguous()
  234.         sampling_offsets = sampling_offsets.permute(0, 3, 1, 2, 4, 5, 6)\
  235.             .reshape(bs*self.num_bev_queue, num_query, self.num_heads, self.num_levels, self.num_points, 2)
  236. #根据 reference_points 的形状不同(2 或 4),计算 sampling_locations
  237.         if reference_points.shape[-1] == 2:
  238.             offset_normalizer = torch.stack(
  239.                 [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
  240.             sampling_locations = reference_points[:, :, None, :, None, :] \
  241.                 + sampling_offsets \
  242.                 / offset_normalizer[None, None, None, :, None, :]
  243.             #NONE插入维度
  244. #将采样偏移 sampling_offsets 转化为相对于输入空间的实际位置。
  245.         elif reference_points.shape[-1] == 4:
  246.             sampling_locations = reference_points[:, :, None, :, None, :2] \
  247.                 + sampling_offsets / self.num_points \
  248.                 * reference_points[:, :, None, :, None, 2:] \
  249.                 * 0.5
  250.         else:
  251.             raise ValueError(
  252.                 f'Last dim of reference_points must be'
  253.                 f' 2 or 4, but get {reference_points.shape[-1]} instead.')
  254.         if torch.cuda.is_available() and value.is_cuda:
  255.             # using fp16 deformable attention is unstable because it performs many sum operations
  256.             if value.dtype == torch.float16:
  257.                 MultiScaleDeformableAttnFunction = MultiScaleDeformableAttnFunction_fp32
  258.             else:
  259.                 MultiScaleDeformableAttnFunction = MultiScaleDeformableAttnFunction_fp32
  260.             output = MultiScaleDeformableAttnFunction.apply(
  261.                 value, spatial_shapes, level_start_index, sampling_locations,
  262.                 attention_weights, self.im2col_step)
  263.         else:
  264.             output = multi_scale_deformable_attn_pytorch(
  265.                 value, spatial_shapes, sampling_locations, attention_weights)
  266.         # output shape (bs*num_bev_queue, num_query, embed_dims)
  267.         # (bs*num_bev_queue, num_query, embed_dims)-> (num_query, embed_dims, bs*num_bev_queue)
  268.         output = output.permute(1, 2, 0)
  269.         # fuse history value and current value
  270.         # (num_query, embed_dims, bs*num_bev_queue)-> (num_query, embed_dims, bs, num_bev_queue)
  271.         output = output.view(num_query, embed_dims, bs, self.num_bev_queue)
  272.         output = output.mean(-1)
  273. #计算 output 张量中每个元素在最后一个维度上的均值
  274.         # (num_query, embed_dims, bs)-> (bs, num_query, embed_dims)
  275.         output = output.permute(2, 0, 1)
  276.         output = self.output_proj(output)
  277.         # out再整一次变换
  278.         if not self.batch_first:
  279.             output = output.permute(1, 0, 2)
  280.         return self.dropout(output) + identity
  281.     # 加一次dropout防止过拟合,同时引入残差连接或者跳跃连接,从而帮助梯度传播以及加速模型的训练
复制代码
SCA

  1. # ---------------------------------------------
  2. # Copyright (c) OpenMMLab. All rights reserved.
  3. # ---------------------------------------------
  4. #  Modified by Zhiqi Li
  5. # ---------------------------------------------
  6. from mmcv.ops.multi_scale_deform_attn import multi_scale_deformable_attn_pytorch
  7. import warnings
  8. import torch
  9. import torch.nn as nn
  10. import torch.nn.functional as F
  11. from mmcv.cnn import xavier_init, constant_init
  12. from mmcv.cnn.bricks.registry import (ATTENTION,
  13.                                       TRANSFORMER_LAYER,
  14.                                       TRANSFORMER_LAYER_SEQUENCE)
  15. from mmcv.cnn.bricks.transformer import build_attention
  16. import math
  17. from mmcv.runner import force_fp32, auto_fp16
  18. from mmcv.runner.base_module import BaseModule, ModuleList, Sequential
  19. from mmcv.utils import ext_loader
  20. from .multi_scale_deformable_attn_function import MultiScaleDeformableAttnFunction_fp32, \
  21.     MultiScaleDeformableAttnFunction_fp16
  22. from projects.mmdet3d_plugin.models.utils.bricks import run_time
  23. ext_module = ext_loader.load_ext(
  24.     '_ext', ['ms_deform_attn_backward', 'ms_deform_attn_forward'])
  25. @ATTENTION.register_module()
  26. class SpatialCrossAttention(BaseModule):
  27.     """An attention module used in BEVFormer.
  28.     Args:
  29.         embed_dims (int): The embedding dimension of Attention.
  30.             Default: 256. 是bev线性变换后注意里特征数量
  31.         num_cams (int): The number of cameras 摄像头的数量
  32.         dropout (float): A Dropout layer on `inp_residual`.
  33.             Default: 0.. 为了防止过拟合dropout层参数
  34.         init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
  35.             Default: None. 初始化参数
  36.         deformable_attention: (dict): The config for the deformable attention used in SCA. SCA的可变性注意力参数
  37.     """
  38.    
  39.     def __init__(self,
  40.                  embed_dims=256,
  41.                  num_cams=6,
  42.                  pc_range=None,
  43.                  dropout=0.1,
  44.                  init_cfg=None,
  45.                  batch_first=False,
  46.                  deformable_attention=dict(
  47.                      type='MSDeformableAttention3D',
  48.                      embed_dims=256,
  49.                      num_levels=4),
  50.                  **kwargs
  51.                  ):
  52.         super(SpatialCrossAttention, self).__init__(init_cfg)
  53.         self.init_cfg = init_cfg
  54.         self.dropout = nn.Dropout(dropout)
  55.         self.pc_range = pc_range
  56.         self.fp16_enabled = False
  57.         self.deformable_attention = build_attention(deformable_attention)
  58.         self.embed_dims = embed_dims
  59.         self.num_cams = num_cams
  60.         self.output_proj = nn.Linear(embed_dims, embed_dims)
  61.         self.batch_first = batch_first
  62.         self.init_weight()
  63.     def init_weight(self):
  64.         """Default initialization for Parameters of Module."""
  65.         xavier_init(self.output_proj, distribution='uniform', bias=0.)
  66.         #以上初始化和TSA基本一致,没有笔记内容
  67.    
  68.     @force_fp32(apply_to=('query', 'key', 'value', 'query_pos', 'reference_points_cam'))
  69.     def forward(self,
  70.                 query,
  71.                 key,
  72.                 value,
  73.                 residual=None,
  74.                 query_pos=None,
  75.                 key_padding_mask=None,
  76.                 reference_points=None,
  77.                 spatial_shapes=None,
  78.                 reference_points_cam=None,
  79.                 bev_mask=None,
  80.                 level_start_index=None,
  81.                 flag='encoder',
  82.                 **kwargs):
  83.         """Forward Function of Detr3DCrossAtten.
  84.         Args:
  85.             query (Tensor): Query of Transformer with shape
  86.                 (num_query, bs, embed_dims).
  87.                 #Q
  88.                 #网上解释num_query类似于 DETR里面的 object_queries,也就是最多预测多少个目标
  89.             key (Tensor): The key tensor with shape
  90.                 `(num_key, bs, embed_dims)`.
  91.                 # k
  92.             value (Tensor): The value tensor with shape
  93.                 `(num_key, bs, embed_dims)`. (B, N, C, H, W)
  94.             residual (Tensor): The tensor used for addition, with the
  95.                 same shape as `x`. Default None. If None, `x` will be used.
  96.            #残差
  97.              query_pos (Tensor): The positional encoding for `query`.
  98.                 Default: None.
  99.             key_pos (Tensor): The positional encoding for  `key`. Default
  100.                 None.
  101.                 # q 和 k的位置编码
  102.             reference_points (Tensor):  The normalized reference
  103.                 points with shape (bs, num_query, 4),
  104.                 all elements is range in [0, 1], top-left (0,0),
  105.                 bottom-right (1, 1), including padding area.
  106.                 or (N, Length_{query}, num_levels, 4), add
  107.                 additional two dimensions is (w, h) to
  108.                 form reference boxes.
  109.                 # 参考点归一化
  110.                 数据标准化( Standardization )是将数据转换为均值为0,方差为1的数据,也就是将数据按比例缩放,
  111.                 使得其分布具有标准正态分布。 数据归一化( Normalization )
  112.                 是将数据转换为满足0≤x≤1的数据,也就是将数据缩放到 [0,1]区间。
  113.                 #num_levels:The number of feature map used in
  114.             Attention 被用于注意力的特征地图的数量
  115.             key_padding_mask (Tensor): ByteTensor for `query`, with
  116.                 shape [bs, num_key].
  117.                 #k 注意力掩码
  118.             spatial_shapes (Tensor): Spatial shape of features in
  119.                 different level. With shape  (num_levels, 2),
  120.                 last dimension represent (h, w).
  121.                 #空间形状,在不同level的特征的空间形状,最后一个维度2是(h,w)
  122.             level_start_index (Tensor): The start index of each level.
  123.                 A tensor has shape (num_levels) and can be represented
  124.                 as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
  125.                 # 开始遍历的index
  126.         Returns:
  127.              Tensor: forwarded results with shape [num_query, bs, embed_dims].
  128.              # 返回查询数量 批次 特征数量
  129.         """
  130.         if key is None:
  131.             key = query
  132.         if value is None:
  133.             value = key
  134.         if residual is None:
  135.             inp_residual = query
  136.             # 残差链接网络传输值被初始化为query
  137.             slots = torch.zeros_like(query)
  138.             # 以 query的shape初始化 slot
  139.         if query_pos is not None:
  140.             query = query + query_pos
  141.             # 同样地把线性层学习到的query位置编码和query叠加到一起
  142.         bs, num_query, _ = query.size()#(num_query, bs, embed_dims)
  143.         #这里是不是错了? 在input地方的备注维度顺序不同?
  144.         D = reference_points_cam.size(3)
  145.         indexes = []
  146.         for i, mask_per_img in enumerate(bev_mask):
  147.             index_query_per_img = mask_per_img[0].sum(-1).nonzero().squeeze(-1)
  148.             indexes.append(index_query_per_img)
  149.         max_len = max([len(each) for each in indexes])
  150.         # 每个特征点对应一个mask点,特征点的值为false,就可以将其在注意力中抛弃
  151.         # 举例子说明:如果mask_per_img =m torch.tensor([[1, 0, 1, 0],[1, 1, 0, 1]])      
  152.         # sum_per_img = mask_per_img.sum(-1) 得到tensor[2,3]
  153.         # nonzero_indices = sum_per_img.nonzero() 得到tensor [[0],[1]]
  154.         # index_query_per_img = nonzero_indices.squeeze(-1)去除上一步操作后多出来的维度
  155.         # 得到[0,1]
  156.         # 最后用indexes 储存计算好的indices
  157.         # each camera only interacts with its corresponding BEV queries. This step can  greatly save GPU memory.
  158.         queries_rebatch = query.new_zeros(
  159.             [bs, self.num_cams, max_len, self.embed_dims])
  160.         reference_points_rebatch = reference_points_cam.new_zeros(
  161.             [bs, self.num_cams, max_len, D, 2])
  162.         
  163.         for j in range(bs):
  164.             for i, reference_points_per_img in enumerate(reference_points_cam):   
  165.                 index_query_per_img = indexes[i]
  166.                 queries_rebatch[j, i, :len(index_query_per_img)] = query[j, index_query_per_img]
  167.                 reference_points_rebatch[j, i, :len(index_query_per_img)] = reference_points_per_img[j, index_query_per_img]
  168.         #重新计算q和reference point 根据上一步计算的index
  169.         num_cams, l, bs, embed_dims = key.shape
  170.         key = key.permute(2, 0, 1, 3).reshape(
  171.             bs * self.num_cams, l, self.embed_dims)
  172.         value = value.permute(2, 0, 1, 3).reshape(
  173.             bs * self.num_cams, l, self.embed_dims)
  174.         queries = self.deformable_attention(query=queries_rebatch.view(bs*self.num_cams, max_len, self.embed_dims), key=key, value=value,
  175.                                             reference_points=reference_points_rebatch.view(bs*self.num_cams, max_len, D, 2), spatial_shapes=spatial_shapes,
  176.                                             level_start_index=level_start_index).view(bs, self.num_cams, max_len, self.embed_dims)
  177.         # 使用可变形注意力
  178.         for j in range(bs):
  179.             for i, index_query_per_img in enumerate(indexes):
  180.                 slots[j, index_query_per_img] += queries[j, i, :len(index_query_per_img)]
  181. # 用计算好的 queries和indexed更新slots
  182.         count = bev_mask.sum(-1) > 0
  183. # 将bev_mask 按照最后一个维度相加 判断是否大于0 结果储存在count中
  184.         count = count.permute(1, 2, 0).sum(-1)
  185.         count = torch.clamp(count, min=1.0) # 将count的元素的 最小值设为1
  186.         slots = slots / count[..., None]
  187.         slots = self.output_proj(slots)
  188.         return self.dropout(slots) + inp_residual # [num_query, bs, embed_dims].
  189. @ATTENTION.register_module()
  190. class MSDeformableAttention3D(BaseModule):
  191.     """An attention module used in BEVFormer based on Deformable-Detr.
  192.     `Deformable DETR: Deformable Transformers for End-to-End Object Detection.
  193.     <https://arxiv.org/pdf/2010.04159.pdf>`_.
  194.     Args:
  195.         embed_dims (int): The embedding dimension of Attention.
  196.             Default: 256.
  197.         num_heads (int): Parallel attention heads. Default: 64.
  198.         num_levels (int): The number of feature map used in
  199.             Attention. Default: 4.
  200.         num_points (int): The number of sampling points for
  201.             each query in each head. Default: 4.
  202.         im2col_step (int): The step used in image_to_column.
  203.             Default: 64.
  204.         dropout (float): A Dropout layer on `inp_identity`.
  205.             Default: 0.1.
  206.         batch_first (bool): Key, Query and Value are shape of
  207.             (batch, n, embed_dim)
  208.             or (n, batch, embed_dim). Default to False.
  209.         norm_cfg (dict): Config dict for normalization layer.
  210.             Default: None.
  211.         init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
  212.             Default: None.
  213.     """
  214. # embed_dims(嵌入维度):注意力机制中的嵌入维度。默认为256,影响了注意力机制中的向量表示维度。
  215. # num_heads(注意力头数):并行的注意力头数。默认为64,控制了注意力机制中多头注意力的并行数量。
  216. # num_levels(特征图数量):注意力中使用的特征图数量。默认为4,影响了注意力机制中特征图的层级数。
  217. # num_points(采样点数):每个注意力头中每个查询点的采样点数。默认为4,决定了每个头部的注意力机制对查询点进行采样的数量。
  218. # im2col_step(image_to_column 步长):在 image_to_column 操作中使用的步长。
  219. # dropout(丢弃率):应用于 inp_identity 的 Dropout 层的丢弃率。默认为0.1,用于在训练中随机丢弃输入张量中的一部分元素,以防止过拟合。
  220. # batch_first(批次优先):用于指定输入张量的维度顺序。如果为 True,表示输入张量的形状是(batch, n, embed_dim),否则为 (n, batch, embed_dim)。默认为 False。
  221. # norm_cfg(归一化层配置):用于归一化层的配置字典。默认为 None,
  222. # init_cfg(初始化配置):初始化配置的配置对象。
  223.     def __init__(self,
  224.                  embed_dims=256,
  225.                  num_heads=8,
  226.                  num_levels=4,
  227.                  num_points=8,
  228.                  im2col_step=64,
  229.                  dropout=0.1,
  230.                  batch_first=True,
  231.                  norm_cfg=None,
  232.                  init_cfg=None):
  233.         super().__init__(init_cfg)
  234.         if embed_dims % num_heads != 0:
  235.             raise ValueError(f'embed_dims must be divisible by num_heads, '
  236.                              f'but got {embed_dims} and {num_heads}')
  237.         dim_per_head = embed_dims // num_heads # 每一个头的特征数量
  238.         self.norm_cfg = norm_cfg
  239.         self.batch_first = batch_first
  240.         self.output_proj = None
  241.         self.fp16_enabled = False
  242.         # you'd better set dim_per_head to a power of 2
  243.         # which is more efficient in the CUDA implementation
  244.         def _is_power_of_2(n):
  245.             if (not isinstance(n, int)) or (n < 0):
  246.                 raise ValueError(
  247.                     'invalid input for _is_power_of_2: {} (type: {})'.format(
  248.                         n, type(n)))
  249.             return (n & (n - 1) == 0) and n != 0
  250.         if not _is_power_of_2(dim_per_head):
  251.             warnings.warn(
  252.                 "You'd better set embed_dims in "
  253.                 'MultiScaleDeformAttention to make '
  254.                 'the dimension of each attention head a power of 2 '
  255.                 'which is more efficient in our CUDA implementation.')
  256.         self.im2col_step = im2col_step
  257.         self.embed_dims = embed_dims
  258.         self.num_levels = num_levels
  259.         self.num_heads = num_heads
  260.         self.num_points = num_points
  261.         self.sampling_offsets = nn.Linear(
  262.             embed_dims, num_heads * num_levels * num_points * 2)
  263.         self.attention_weights = nn.Linear(embed_dims,
  264.                                            num_heads * num_levels * num_points)
  265.         self.value_proj = nn.Linear(embed_dims, embed_dims)
  266. # 同 TSA的注意力
  267.         self.init_weights()
  268.     def init_weights(self):
  269.         """Default initialization for Parameters of Module."""
  270.         constant_init(self.sampling_offsets, 0.)
  271.         #极坐标网格构建
  272.         # 创建一个0到2pi 等分为8分的tensor
  273.         thetas = torch.arange(
  274.             self.num_heads,
  275.             dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
  276.         # 初始化grid
  277.         #利用三角函数计算每个角度对应的余弦和正弦值,然后通过torch.stack在最后一个维度
  278.         #将这两个值堆叠在一起形成一个形状为(num_heads, 2)的张量。
  279.         # 这个张量的每一行表示一个角度对应的极坐标中的(x, y)坐标,
  280.         # 使用grid_init.abs().max(-1, keepdim=True)[0]计算每个行向量的绝对值中的最大值,
  281.         # 并在最后一个维度上保持维度。然后,将grid_init除以这个最大值,实现归一化。
  282.         # 最后,通过view函数将结果变形成形状为(num_heads, 1, 1, 2)的张量
  283.         #最终的输出是一个形状为(num_heads, 1, 1, 2)的张量,
  284.         # 表示了num_heads个头部的极坐标网格。每个头部的网格用一个(x, y)坐标表示,
  285.         # 这个坐标在单位圆上,且在整个num_heads中均匀分布
  286.         grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
  287.         grid_init = (grid_init /
  288.                      grid_init.abs().max(-1, keepdim=True)[0]).view(
  289.             self.num_heads, 1, 1,
  290.             2).repeat(1, self.num_levels, self.num_points, 1)
  291. ## 遍历第二个维度上,通过这种方式记录是第几个采样点的极坐标        
  292.         for i in range(self.num_points):
  293.             grid_init[:, :, i, :] *= i + 1
  294. #grid_init.view(-1) 将 grid_init 张量展平为一个一维张量
  295.         self.sampling_offsets.bias.data = grid_init.view(-1)
  296.         constant_init(self.attention_weights, val=0., bias=0.)
  297.         xavier_init(self.value_proj, distribution='uniform', bias=0.)
  298.         xavier_init(self.output_proj, distribution='uniform', bias=0.)
  299.         self._is_init = True
  300.     def forward(self,
  301.                 query,
  302.                 key=None,
  303.                 value=None,
  304.                 identity=None,
  305.                 query_pos=None,
  306.                 key_padding_mask=None,
  307.                 reference_points=None,
  308.                 spatial_shapes=None,
  309.                 level_start_index=None,
  310.                 **kwargs):
  311.         """Forward Function of MultiScaleDeformAttention.
  312.         Args:
  313.             query (Tensor): Query of Transformer with shape
  314.                 ( bs, num_query, embed_dims).
  315.             key (Tensor): The key tensor with shape
  316.                 `(bs, num_key,  embed_dims)`.
  317.             value (Tensor): The value tensor with shape
  318.                 `(bs, num_key,  embed_dims)`.
  319.             identity (Tensor): The tensor used for addition, with the
  320.                 same shape as `query`. Default None. If None,
  321.                 `query` will be used.
  322.             query_pos (Tensor): The positional encoding for `query`.
  323.                 Default: None.
  324.             key_pos (Tensor): The positional encoding for `key`. Default
  325.                 None.
  326.             reference_points (Tensor):  The normalized reference
  327.                 points with shape (bs, num_query, num_levels, 2),
  328.                 all elements is range in [0, 1], top-left (0,0),
  329.                 bottom-right (1, 1), including padding area.
  330.                 or (N, Length_{query}, num_levels, 4), add
  331.                 additional two dimensions is (w, h) to
  332.                 form reference boxes.
  333.             key_padding_mask (Tensor): ByteTensor for `query`, with
  334.                 shape [bs, num_key].
  335.             spatial_shapes (Tensor): Spatial shape of features in
  336.                 different levels. With shape (num_levels, 2),
  337.                 last dimension represents (h, w).
  338.             level_start_index (Tensor): The start index of each level.
  339.                 A tensor has shape ``(num_levels, )`` and can be represented
  340.                 as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
  341.         Returns:
  342.              Tensor: forwarded results with shape [num_query, bs, embed_dims].
  343.         """
  344.         if value is None:
  345.             value = query
  346.         if identity is None:
  347.             identity = query
  348.         if query_pos is not None:
  349.             query = query + query_pos
  350.         if not self.batch_first:
  351.             # change to (bs, num_query ,embed_dims)
  352.             query = query.permute(1, 0, 2)
  353.             value = value.permute(1, 0, 2)
  354.         bs, num_query, _ = query.shape
  355.         bs, num_value, _ = value.shape
  356.         assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
  357.         value = self.value_proj(value)
  358.         if key_padding_mask is not None:
  359.             value = value.masked_fill(key_padding_mask[..., None], 0.0)
  360.         value = value.view(bs, num_value, self.num_heads, -1)
  361.         sampling_offsets = self.sampling_offsets(query).view(
  362.             bs, num_query, self.num_heads, self.num_levels, self.num_points, 2)
  363.         attention_weights = self.attention_weights(query).view(
  364.             bs, num_query, self.num_heads, self.num_levels * self.num_points)
  365.         attention_weights = attention_weights.softmax(-1)
  366.         attention_weights = attention_weights.view(bs, num_query,
  367.                                                    self.num_heads,
  368.                                                    self.num_levels,
  369.                                                    self.num_points)
  370.         if reference_points.shape[-1] == 2:
  371.             """
  372.             For each BEV query, it owns `num_Z_anchors` in 3D space that having different heights.
  373.             After proejcting, each BEV query has `num_Z_anchors` reference points in each 2D image.
  374.             For each referent point, we sample `num_points` sampling points.
  375.             For `num_Z_anchors` reference points,  it has overall `num_points * num_Z_anchors` sampling points.
  376.             """
  377.             offset_normalizer = torch.stack(
  378.                 [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
  379.             bs, num_query, num_Z_anchors, xy = reference_points.shape
  380.             reference_points = reference_points[:, :, None, None, None, :, :]
  381.             sampling_offsets = sampling_offsets / \
  382.                 offset_normalizer[None, None, None, :, None, :]
  383.             bs, num_query, num_heads, num_levels, num_all_points, xy = sampling_offsets.shape
  384.             sampling_offsets = sampling_offsets.view(
  385.                 bs, num_query, num_heads, num_levels, num_all_points // num_Z_anchors, num_Z_anchors, xy)
  386.             sampling_locations = reference_points + sampling_offsets
  387.             bs, num_query, num_heads, num_levels, num_points, num_Z_anchors, xy = sampling_locations.shape
  388.             assert num_all_points == num_points * num_Z_anchors
  389.             sampling_locations = sampling_locations.view(
  390.                 bs, num_query, num_heads, num_levels, num_all_points, xy)
  391.         elif reference_points.shape[-1] == 4:
  392.             assert False
  393.         else:
  394.             raise ValueError(
  395.                 f'Last dim of reference_points must be'
  396.                 f' 2 or 4, but get {reference_points.shape[-1]} instead.')
  397.         #  sampling_locations.shape: bs, num_query, num_heads, num_levels, num_all_points, 2
  398.         #  attention_weights.shape: bs, num_query, num_heads, num_levels, num_all_points
  399.         #准备步骤基本可TSA相同
  400.         if torch.cuda.is_available() and value.is_cuda:
  401.             if value.dtype == torch.float16:
  402.                 MultiScaleDeformableAttnFunction = MultiScaleDeformableAttnFunction_fp32
  403.             else:
  404.                 MultiScaleDeformableAttnFunction = MultiScaleDeformableAttnFunction_fp32
  405.             output = MultiScaleDeformableAttnFunction.apply(
  406.                 value, spatial_shapes, level_start_index, sampling_locations,
  407.                 attention_weights, self.im2col_step)
  408.         else:
  409.             output = multi_scale_deformable_attn_pytorch(
  410.                 value, spatial_shapes, sampling_locations, attention_weights)
  411.         if not self.batch_first:
  412.             output = output.permute(1, 0, 2)
  413.         return output
复制代码
拓展

关于embedding

embedding层的作用
我的理解,在之前NLP的学习中,一个词语放入到语义中可以利用一个多维度的向量在超空间里分解他的寄义,然后这个向量(坐标亦或位置),表现出来这个字和差异维度轴的相关程度,从而阐明了这个词语的寄义。
gpt表明:
Embedding 层在深度学习中主要用于将高维的离散数据映射到低维的一连空间
Embedding 层将输入的离散数据,比如单词、类别标签等,映射到一个固定维度的实数向量。这使得模型可以大概更好地理解和处理这些数据,因为一连向量包罗了更多的信息
Embedding 层会根据模型的练习数据学习出适合任务的特征表示。这意味着相似的类别或单词在嵌入空间中会有相似的表示,这有助于进步模型的泛化本领
Embedding 层可以将高维的离散数据映射到低维的一连空间。这有助于减少模型的参数数量,进步练习和推理效率
与独热编码等稀疏表示相比,Embedding 层提供了密集的表示,其中每个维度都包罗信息。这可以减少存储需求,并更有用地传达模型学到的知识
其中:
• 一连的向量: 意味着向量的每个元素都可以是任意实数,而不仅仅是整数。在嵌入层中,这通常是为了获得更机动、更具表达力的表示。
• 低维向量: 意味着向量的维度相对较低。在嵌入的上下文中,这有助于减少模型参数的数量,同时保留重要的特征。低维度的表示通常更容易被模型学习和泛化。
gpt举例:
一个emmeding的简朴利用
  1. import torch
  2. import torch.nn as nn
  3. # 假设我们有一个词汇表的大小为10,每个词的嵌入维度为3
  4. vocab_size = 10
  5. embedding_dim = 3
  6. # 创建一个 Embedding 层
  7. embedding_layer = nn.Embedding(vocab_size, embedding_dim)
  8. # 定义一个输入,包含三个词的索引
  9. input_indices = torch.tensor([1, 5, 9], dtype=torch.long)
  10. # 将输入传递给嵌入层,得到嵌入向量
  11. embedded_vector = embedding_layer(input_indices)
  12. # 输出嵌入向量
  13. print(embedded_vector)
复制代码
  1. tensor([[-2.8465,  0.1365, -0.4851],
  2.         [ 0.4402, -0.3163, -0.8770],
  3.         [-0.4027, -0.1626,  0.3808]], grad_fn=<EmbeddingBackward0>)
复制代码
“每个词的嵌入维度为3” 意味着在嵌入层中为每个词分配的嵌入向量的维度是3。嵌入向量是一个实数向量,用于表示模型学习到的词汇表中每个词的语义信息。
在这个特定的例子中,每个词都被映射到一个包罗3个实数值的向量。这三个值构成了嵌入向量的三个维度。这种表示是通过练习神经网络从数据中学习得到的,网络通过反向传播算法来调解嵌入向量的权重,以最好地适应练习数据。
通常,嵌入维度的选择是一个超参数,可以根据具体任务和数据的性质举行调解。较大的嵌入维度可以提供更丰富的语义信息,但也需要更多的盘算资源。一样寻常而言,在实际应用中,嵌入维度的选择可能会在试验和验证中举行调解,以找到适合特定任务的最佳值。
关于xavier

对于网络的每一层初始化权重时,使得输入和输出的方差相等。这有助于制止在网络的前向传播和反向传播中引入梯度爆炸或梯度消失的问题。
权重初始化表明聚集
摘读如下
   Xavier初始化,也称为Glorot初始化,是一种常用的参数初始化方法,旨在有用地初始化神经网络中的权重。它的筹划思想是根据前一层和后一层的神经元数量来设置权重的初始值,以保持信号在前向传播过程中的适当范围;其焦点思想是,保持输入信号和梯度的方差在差异层之间大致相等,制止在深层网络中产生梯度消失或梯度爆炸的问题。这种初始化方法有助于提供符合的梯度范围,促进网络的稳固练习和收敛。。具体而言,对于具有线性激活函数(如sigmoid和tanh)的网络层,Xavier初始化将权重初始化为匀称分布或高斯分布,其方差取决于前一层神经元数量n和后一层神经元数量m。
  对于匀称分布的Xavier初始化(匀称版):
  从匀称分布中随机初始化权重矩阵W,范围为[-a, a],其中a = sqrt(6 / (n + m))。
对于高斯分布的Xavier初始化(高斯版):
  从高斯分布中随机初始化权重矩阵W,均值为0,方差为variance,其中variance = 2 / (n + m)。 焦点筹划思想表明
当我们练习深度神经网络时,梯度的传播黑白常关键的。如果梯度在每一层传播时渐渐消失,即梯度靠近于零,那么底层的参数将很难更新,导致网络难以学习有用的表示。相反,如果梯度在每一层传播时渐渐增大,即梯度爆炸,那么参数更新的幅度会非常大,导致练习不稳固甚至无法收敛。因此,要保持输入信号和梯度的方差在差异层之间大致相等,以确保在前向传播和反向传播过程中,信号和梯度可以大概保持符合的范围,从而促进网络的稳固练习和收敛。
  怎样保证输入信号和梯度的方差在差异层之间大致相等呢?在Xavier初始化中,存在递归的思想,其盘算方式是递归的,即权重的初始范围是根据前一层和后一层的神经元数量举行盘算的。
  好的,让我们来看一个具有5层的神经网络的例子,以表明Xavier初始化是怎样工作的。假设我们有一个具有以下结构的神经网络:输入层(100个神经元)
  

  • 隐藏层1(80个神经元) - 隐藏层2(60个神经元) - 隐藏层3(40个神经元) - 输出层(10个神经元)。现在,我们将利用Xavier初始化来初始化每一层的权重。
  对于隐藏层1,我们需要盘算它的权重初始范围。根据Xavier初始化的公式,我们需要知道前一层和后一层的神经元数量。在这种情况下,前一层是输入层,有100个神经元,后一层是隐藏层1自己,有80个神经元。根据公式,我们可以盘算权重初始范围a:a
= sqrt(6 / (100 + 80)) ≈ 0.136。现在,我们可以从匀称分布[-0.136, 0.136]中随机初始化隐藏层1的权重矩阵。
  接下来,我们继续盘算隐藏层2的权重初始范围。前一层是隐藏层1,有80个神经元,后一层是隐藏层2自己,有60个神经元。我们利用相同的公式来盘算权重初始范围a:a
= sqrt(6 / (80 + 60)) ≈ 0.153。然后,我们从匀称分布[-0.153, 0.153]中随机初始化隐藏层2的权重矩阵。
  类似地,我们可以盘算隐藏层3和输出层的权重初始范围,并举行相应的初始化。
  通过如许的递归盘算和初始化过程,Xavier初始化确保了每一层的权重都与前一层和后一层的神经元数量相关联。这有助于平衡信号和梯度的传播,制止梯度消失或梯度爆炸问题,从而进步神经网络的练习稳固性和收敛性能。
  关于stack 和 reshape和permute和cat和view和NONE的用法

  1. tmp_prev_bev = prev_bev[:, i].reshape(
  2.                         bev_h, bev_w, -1).permute(2, 0, 1)
复制代码
有我不熟悉的语法 gpt查询如下:
A:
prev_bev[:, i]:表示选择 prev_bev 张量中的所有行 (

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户云卷云舒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表