MCPcopy Create free account
hub / github.com/QWTforGithub/T2LDM / forward

Method forward

timm/models/layers/lambda_layer.py:109–133  ·  view source on GitHub ↗
(self, x)

Source from the content-addressed store, hash-verified

107 trunc_normal_(self.pos_emb, std=.02)
108
109 def forward(self, x):
110 B, C, H, W = x.shape
111 M = H * W
112 qkv = self.qkv(x)
113 q, k, v = torch.split(qkv, [
114 self.num_heads * self.dim_qk, self.dim_qk, self.dim_v], dim=1)
115 q = self.norm_q(q).reshape(B, self.num_heads, self.dim_qk, M).transpose(-1, -2) # B, num_heads, M, K
116 v = self.norm_v(v).reshape(B, self.dim_v, M).transpose(-1, -2) # B, M, V
117 k = F.softmax(k.reshape(B, self.dim_qk, M), dim=-1) # B, K, M
118
119 content_lam = k @ v # B, K, V
120 content_out = q @ content_lam.unsqueeze(1) # B, num_heads, M, V
121
122 if self.pos_emb is None:
123 position_lam = self.conv_lambda(v.reshape(B, 1, H, W, self.dim_v)) # B, H, W, V, K
124 position_lam = position_lam.reshape(B, 1, self.dim_qk, H * W, self.dim_v).transpose(2, 3) # B, 1, M, K, V
125 else:
126 # FIXME relative pos embedding path not fully verified
127 pos_emb = self.pos_emb[self.rel_pos_indices[0], self.rel_pos_indices[1]].expand(B, -1, -1, -1)
128 position_lam = (pos_emb.transpose(-1, -2) @ v.unsqueeze(1)).unsqueeze(1) # B, 1, M, K, V
129 position_out = (q.unsqueeze(-2) @ position_lam).squeeze(-2) # B, num_heads, M, V
130
131 out = (content_out + position_out).transpose(-1, -2).reshape(B, C, H, W) # B, C (num_heads * V), H, W
132 out = self.pool(out)
133 return out

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected