MCPcopy Create free account
hub / github.com/VisionXLab/OF-Diff / SpatialSelfAttention

Class SpatialSelfAttention

ldm/modules/attention.py:92–142  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected