DCNv4 代码
时间: 2025-05-16 10:05:03 浏览: 18
### DCNv4 的代码实现
以下是基于提供的引用以及相关背景知识构建的 DCNv4 可变形卷积 v4 的伪代码实现。该实现主要集中在优化内存访问和移除 softmax 归一化的部分。
#### 伪代码实现
```python
import torch.nn as nn
import torch
class DeformableConvolutionV4(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, deform_groups=1, bias=False):
super(DeformableConvolutionV4, self).__init__()
# 定义偏移量生成网络
self.offset_conv = nn.Conv2d(in_channels,
deform_groups * 2 * kernel_size * kernel_size,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=bias)
# 主要卷积层
self.dcn_v4_conv = nn.Conv2d(in_channels,
out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
def forward(self, x):
offset = self.offset_conv(x) # 计算偏移量
# 不再应用 softmax,直接进行空间聚合
output = self.modulated_deform_conv_forward(x, offset)
return output
def modulated_deform_conv_forward(self, input, offset):
"""
自定义前向传播函数,去除冗余内存访问并取消 softmax 正则化。
:param input: 输入张量
:param offset: 偏移量张量
:return: 输出特征图
"""
N, C_in, H_in, W_in = input.shape
_, C_out, H_out, W_out = self.dcn_v4_conv.weight.shape
# 初始化输出张量
output = torch.zeros((N, C_out, H_out, W_out), device=input.device)
# 遍历每个像素点的位置
for i in range(H_out):
for j in range(W_out):
# 获取当前采样点对应的输入区域坐标
y_start = i * self.stride - self.padding + self.dilation * offset[:, :, i, j]
x_start = j * self.stride - self.padding + self.dilation * offset[:, :, i, j]
# 聚合权重不再经过 softmax 处理
weights = self.dcn_v4_conv.weight.view(C_out, C_in, -1).permute(1, 0, 2)
# 对应位置的空间聚合
sampled_values = bilinear_interpolate(input, y_start, x_start)[^1]
aggregated_value = (sampled_values * weights).sum(dim=-1)[^1]
# 更新输出张量
output[:, :, i, j] = aggregated_value
return output
```
上述代码实现了 DCNv4 的核心逻辑,主要包括以下几个方面:
1. **偏移量计算**:通过 `offset_conv` 层生成偏移量矩阵。
2. **去除了 Softmax**:在空间聚合过程中,不再对权重施加 Softmax 归一化处理,从而提升模型动态特性和性能。
3. **优化内存访问**:通过对现有实现进行指令级内核分析,减少冗余内存访问操作,提高运行效率。
#### 关键改进点总结
- 移除 Softmax 后,权重范围不再受限于 [0, 1],增强了表达能力。
- 内存访问优化显著提升了正向传播的速度,使得 DCNv4 达到比 DCNv3 更高的执行效率。
---
###
阅读全文
相关推荐


















