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

Class MemoryEfficientCrossAttention

ldm/modules/attention.py:197–243  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

195
196
197class MemoryEfficientCrossAttention(nn.Module):
198 # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
199 def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
200 super().__init__()
201 print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
202 f"{heads} heads.")
203 inner_dim = dim_head * heads
204 context_dim = default(context_dim, query_dim)
205
206 self.heads = heads
207 self.dim_head = dim_head
208
209 self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
210 self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
211 self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
212
213 self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
214 self.attention_op: Optional[Any] = None
215
216 def forward(self, x, context=None, mask=None):
217 q = self.to_q(x)
218 context = default(context, x)
219 k = self.to_k(context)
220 v = self.to_v(context)
221
222 b, _, _ = q.shape
223 q, k, v = map(
224 lambda t: t.unsqueeze(3)
225 .reshape(b, t.shape[1], self.heads, self.dim_head)
226 .permute(0, 2, 1, 3)
227 .reshape(b * self.heads, t.shape[1], self.dim_head)
228 .contiguous(),
229 (q, k, v),
230 )
231
232 # actually compute the attention, what we cannot get enough of
233 out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
234
235 if exists(mask):
236 raise NotImplementedError
237 out = (
238 out.unsqueeze(0)
239 .reshape(b, self.heads, out.shape[1], self.dim_head)
240 .permute(0, 2, 1, 3)
241 .reshape(b, out.shape[1], self.heads * self.dim_head)
242 )
243 return self.to_out(out)
244
245
246class BasicTransformerBlock(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected