MCPcopy Create free account
hub / github.com/CompVis/diff2flow / SpatialSelfAttention

Class SpatialSelfAttention

diff2flow/models/unet/attention.py:90–140  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

88
89
90class SpatialSelfAttention(nn.Module):
91 def __init__(self, in_channels):
92 super().__init__()
93 self.in_channels = in_channels
94
95 self.norm = Normalize(in_channels)
96 self.q = torch.nn.Conv2d(in_channels,
97 in_channels,
98 kernel_size=1,
99 stride=1,
100 padding=0)
101 self.k = torch.nn.Conv2d(in_channels,
102 in_channels,
103 kernel_size=1,
104 stride=1,
105 padding=0)
106 self.v = torch.nn.Conv2d(in_channels,
107 in_channels,
108 kernel_size=1,
109 stride=1,
110 padding=0)
111 self.proj_out = torch.nn.Conv2d(in_channels,
112 in_channels,
113 kernel_size=1,
114 stride=1,
115 padding=0)
116
117 def forward(self, x):
118 h_ = x
119 h_ = self.norm(h_)
120 q = self.q(h_)
121 k = self.k(h_)
122 v = self.v(h_)
123
124 # compute attention
125 b,c,h,w = q.shape
126 q = rearrange(q, 'b c h w -> b (h w) c')
127 k = rearrange(k, 'b c h w -> b c (h w)')
128 w_ = torch.einsum('bij,bjk->bik', q, k)
129
130 w_ = w_ * (int(c)**(-0.5))
131 w_ = torch.nn.functional.softmax(w_, dim=2)
132
133 # attend to values
134 v = rearrange(v, 'b c h w -> b c (h w)')
135 w_ = rearrange(w_, 'b i j -> b j i')
136 h_ = torch.einsum('bij,bjk->bik', v, w_)
137 h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
138 h_ = self.proj_out(h_)
139
140 return x+h_
141
142
143class CrossAttention(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected