MCPcopy Create free account
hub / github.com/alinlab/SelfPatch / Patch_Attention

Class Patch_Attention

selfpatch_vision_transformer.py:141–173  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

139 return x_cls
140
141class Patch_Attention(nn.Module):
142 # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
143 # with slight modifications to do CA
144 def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
145 super().__init__()
146 self.num_heads = num_heads
147 head_dim = dim // num_heads
148 self.scale = qk_scale or head_dim ** -0.5
149
150 self.q = nn.Linear(dim, dim, bias=qkv_bias)
151 self.k = nn.Linear(dim, dim, bias=qkv_bias)
152 self.v = nn.Linear(dim, dim, bias=qkv_bias)
153 self.attn_drop = nn.Dropout(attn_drop)
154 self.proj = nn.Linear(dim, dim)
155 self.proj_drop = nn.Dropout(proj_drop)
156
157 def forward(self, x):
158 B, N, C = x.shape
159 q = self.q(x[:,1:]).unsqueeze(1).reshape(B, N-1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
160 k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
161
162 q = q * self.scale
163 v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
164
165 attn = (q @ k.transpose(-2, -1))
166 attn = attn.softmax(dim=-1)
167 attn = self.attn_drop(attn)
168
169 x_cls = (attn @ v).transpose(1, 2).reshape(B, N-1, C)
170 x_cls = self.proj(x_cls)
171 x_cls = self.proj_drop(x_cls)
172
173 return x_cls, attn
174
175class Patch_Block(nn.Module):
176 def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected