用pytorch实现类vit架构的改进模型
- User
用pytorch实现类vit架构的改进模型
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
用pytorch实现类vit架构的改进模型
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
以下是使用 PyTorch 实现的一个改进版的 Vision Transformer(ViT)模型。这个模型在标准 ViT 的基础上进行了改进,包括:
卷积式 Stem:使用卷积层替代传统 ViT 中的线性投影进行 patch embedding,这样可以更有效地提取局部空间特征。
相对位置编码:引入相对位置编码,可以更好地捕获 tokens 之间的相对位置信息。
改进的自注意力机制:在自注意力计算中加入相对位置偏置,提升模型对位置信息的敏感度。
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvStem(nn.Module):
"""
使用卷积层替代传统的 patch embedding。
"""
def __init__(self, in_channels, embed_dim):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels, embed_dim // 2, kernel_size=3, stride=2, padding=1), # 空间尺寸减半
nn.BatchNorm2d(embed_dim // 2),
nn.ReLU(inplace=True),
nn.Conv2d(embed_dim // 2, embed_dim, kernel_size=3, stride=2, padding=1), # 再次减半
nn.BatchNorm2d(embed_dim),
nn.ReLU(inplace=True),
)
def forward(self, x):
x = self.conv(x)
# 展平成序列
x = x.flatten(2).transpose(1, 2) # (batch_size, num_patches, embed_dim)
return x
class RelativePositionEncoding(nn.Module):
"""
相对位置编码,用于自注意力机制。
"""
def __init__(self, length, dim):
super().__init__()
self.rel_height = nn.Parameter(torch.randn(2 * length - 1, dim // 2))
self.rel_width = nn.Parameter(torch.randn(2 * length - 1, dim // 2))
def forward(self):
# 相对位置编码的实现,此处简化处理
relative_position_bias = torch.cat([self.rel_height, self.rel_width], dim=-1)
return relative_position_bias
class ImprovedSelfAttention(nn.Module):
"""
引入相对位置编码的自注意力机制。
"""
def __init__(self, dim, num_heads, length):
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=False)
self.attn_drop = nn.Dropout(0.1)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(0.1)
self.relative_position_encoding = RelativePositionEncoding(length, dim)
def forward(self, x):
B, N, C = x.shape
relative_position_bias = self.relative_position_encoding()
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim)
qkv = qkv.permute(2, 0, 3, 1, 4) # (3, B, num_heads, N, head_dim)
q, k, v = qkv.unbind(0)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn + relative_position_bias.unsqueeze(0).unsqueeze(0)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
out = (attn @ v).transpose(1,2).reshape(B,N,C)
out = self.proj(out)
out = self.proj_drop(out)
return out
class TransformerEncoderLayer(nn.Module):
"""
改进的 Transformer Encoder 层,包括自注意力和 MLP。
"""
def __init__(self, dim, num_heads, mlp_ratio=4.0, length=196):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = ImprovedSelfAttention(dim, num_heads, length)
self.norm2 = nn.LayerNorm(dim)
hidden_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(0.1),
nn.Linear(hidden_dim, dim),
nn.Dropout(0.1),
)
def forward(self, x):
x = x + self.attn(self.norm1(x)) # 残差连接
x = x + self.mlp(self.norm2(x)) # 残差连接
return x
class ImprovedViT(nn.Module):
def __init__(self, image_size=224, in_channels=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12):
super().__init__()
self.conv_stem = ConvStem(in_channels, embed_dim)
num_patches = (image_size // 4) ** 2 # 经过两次 stride=2 的卷积,尺寸缩小 4 倍
self.cls_token = nn.Parameter(torch.zeros(1,1,embed_dim))
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches+1, embed_dim))
self.pos_drop = nn.Dropout(p=0.1)
self.blocks = nn.ModuleList([
TransformerEncoderLayer(embed_dim, num_heads, length=num_patches+1)
for _ in range(depth)
])
self.norm = nn.LayerNorm(embed_dim)
self.head = nn.Linear(embed_dim, num_classes)
def forward(self, x):
x = self.conv_stem(x)
B, N, C = x.shape
cls_tokens = self.cls_token.expand(B, -1, -1) # (B,1,C)
x = torch.cat((cls_tokens, x), dim=1) # (B,N+1,C)
x = x + self.pos_embed
x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
cls_token_final = x[:,0] # 提取分类 token
logits = self.head(cls_token_final)
return logits
# 测试模型
if __name__ == "__main__":
model = ImprovedViT(
image_size=224,
in_channels=3,
num_classes=1000,
embed_dim=768,
depth=12,
num_heads=12
)
dummy_input = torch.randn(1, 3, 224, 224)
logits = model(dummy_input)
print(logits.shape) # 输出应为 (1, 1000)
模型说明:
ConvStem:使用两个卷积层将输入图片的尺寸缩小 4 倍,同时将通道数映射到 embed_dim,然后展平成序列形式,以供 Transformer 使用。
RelativePositionEncoding:实现相对位置编码,用于在自注意力中加入位置信息。
ImprovedSelfAttention:在标准的自注意力计算中加入相对位置偏置。
TransformerEncoderLayer:包含改进的自注意力层和 MLP,均采用前归一化(Pre-Norm)结构,并使用残差连接。
ImprovedViT:整体模型结构,包含卷积式 Stem、位置编码、多个 Transformer Encoder 层、最终的分类头等。
使用方法:
ImprovedViT,并使用自己的数据进行训练。embed_dim、depth、num_heads 等。注意事项:
由于相对位置编码的具体实现可能较为复杂,此处提供了一个简化版本。在实际应用中,可以根据需求引用论文中的具体实现方式。
该模型是一个基础版本,可能需要根据具体任务进行优化,例如调整 Dropout 比例、学习率等超参数。
参考文献:
Dosovitskiy, A., et al. "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale." arXiv preprint arXiv:2010.11929 (2020).
Dai, Z., et al. "CoAtNet: Marrying Convolution and Attention for All Data Sizes." arXiv preprint arXiv:2106.04803 (2021).
希望这个实现对您有所帮助!