MCPcopy Index your code
hub / github.com/VisionXLab/OF-Diff / QKVAttentionLegacy

Class QKVAttentionLegacy

ldm/modules/diffusionmodules/openaimodel.py:348–377  ·  view source on GitHub ↗

A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping

Source from the content-addressed store, hash-verified

346
347
348class QKVAttentionLegacy(nn.Module):
349 """
350 A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
351 """
352
353 def __init__(self, n_heads):
354 super().__init__()
355 self.n_heads = n_heads
356
357 def forward(self, qkv):
358 """
359 Apply QKV attention.
360 :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
361 :return: an [N x (H * C) x T] tensor after attention.
362 """
363 bs, width, length = qkv.shape
364 assert width % (3 * self.n_heads) == 0
365 ch = width // (3 * self.n_heads)
366 q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
367 scale = 1 / math.sqrt(math.sqrt(ch))
368 weight = th.einsum(
369 "bct,bcs->bts", q * scale, k * scale
370 ) # More stable with f16 than dividing afterwards
371 weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
372 a = th.einsum("bts,bcs->bct", weight, v)
373 return a.reshape(bs, -1, length)
374
375 @staticmethod
376 def count_flops(model, _x, y):
377 return count_flops_attn(model, _x, y)
378
379
380class QKVAttention(nn.Module):

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected