1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
| """ Vision Transformer for Driver Distraction Detection 基于ViT的多任务分心检测网络 """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple import math
class PatchEmbedding(nn.Module): """ 图像Patch嵌入 将图像分割为patches并线性投影 """ def __init__( self, image_size: int = 224, patch_size: int = 16, in_channels: int = 3, embed_dim: int = 768 ): super().__init__() self.image_size = image_size self.patch_size = patch_size self.num_patches = (image_size // patch_size) ** 2 self.proj = nn.Conv2d( in_channels, embed_dim, kernel_size=patch_size, stride=patch_size ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (batch, channels, height, width) Returns: embeddings: (batch, num_patches, embed_dim) """ x = self.proj(x) x = x.flatten(2).transpose(1, 2) return x
class MultiHeadAttention(nn.Module): """ 多头自注意力机制 """ def __init__( self, embed_dim: int = 768, num_heads: int = 12, dropout: float = 0.0 ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == embed_dim self.qkv = nn.Linear(embed_dim, embed_dim * 3) self.proj = nn.Linear(embed_dim, embed_dim) self.dropout = nn.Dropout(dropout) self.scale = self.head_dim ** -0.5 def forward( self, x: torch.Tensor, mask: Optional[torch.Tensor] = None ) -> torch.Tensor: """ Args: x: (batch, seq_len, embed_dim) mask: attention mask Returns: output: (batch, seq_len, embed_dim) """ B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim) qkv = qkv.permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = (q @ k.transpose(-2, -1)) * self.scale if mask is not None: attn = attn.masked_fill(mask == 0, float('-inf')) attn = attn.softmax(dim=-1) attn = self.dropout(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) return x
class TransformerBlock(nn.Module): """ Transformer编码器块 """ def __init__( self, embed_dim: int = 768, num_heads: int = 12, mlp_ratio: float = 4.0, dropout: float = 0.0 ): super().__init__() self.norm1 = nn.LayerNorm(embed_dim) self.norm2 = nn.LayerNorm(embed_dim) self.attn = MultiHeadAttention( embed_dim=embed_dim, num_heads=num_heads, dropout=dropout ) mlp_hidden_dim = int(embed_dim * mlp_ratio) self.mlp = nn.Sequential( nn.Linear(embed_dim, mlp_hidden_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(mlp_hidden_dim, embed_dim), nn.Dropout(dropout) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (batch, seq_len, embed_dim) Returns: output: (batch, seq_len, embed_dim) """ x = x + self.attn(self.norm1(x)) x = x + self.mlp(self.norm2(x)) return x
class VisionTransformer(nn.Module): """ Vision Transformer骨干网络 """ def __init__( self, image_size: int = 224, patch_size: int = 16, in_channels: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, dropout: float = 0.1 ): super().__init__() self.patch_embed = PatchEmbedding( image_size=image_size, patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim ) num_patches = self.patch_embed.num_patches 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(dropout) self.blocks = nn.ModuleList([ TransformerBlock( embed_dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, dropout=dropout ) for _ in range(depth) ]) self.norm = nn.LayerNorm(embed_dim) nn.init.trunc_normal_(self.cls_token, std=0.02) nn.init.trunc_normal_(self.pos_embed, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (batch, channels, height, width) Returns: features: (batch, embed_dim) CLS token特征 """ B = x.size(0) x = self.patch_embed(x) cls_tokens = self.cls_token.expand(B, -1, -1) x = torch.cat([cls_tokens, x], dim=1) x = x + self.pos_embed x = self.pos_drop(x) for block in self.blocks: x = block(x) x = self.norm(x) return x[:, 0]
|