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

Method forward

selfpatch_vision_transformer.py:89–112  ·  view source on GitHub ↗
(self, x, attention=False, mask=None)

Source from the content-addressed store, hash-verified

87
88
89 def forward(self, x, attention=False, mask=None):
90
91 B, N, C = x.shape
92 q = self.q(x[:,0]).unsqueeze(1).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
93 k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
94
95 q = q * self.scale
96 v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
97
98 attn = (q @ k.transpose(-2, -1))
99 if mask is not None:
100 mask_temp = torch.cat([torch.ones(B,1).bool().cuda(), mask],dim=1).unsqueeze(1).unsqueeze(1).expand(-1,self.num_heads,-1,-1)
101 attn = attn.masked_fill_(~mask_temp.bool(), float("-inf"))
102 attn = attn.softmax(dim=-1)
103 attn = self.attn_drop(attn)
104
105 x_cls = (attn @ v).transpose(1, 2).reshape(B, 1, C)
106 x_cls = self.proj(x_cls)
107 x_cls = self.proj_drop(x_cls)
108
109 if attention:
110 return x_cls, attn
111 else:
112 return x_cls
113
114
115class LayerScale_Block_CA(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected