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

Method forward

diff2flow/models/unet/openaimodel.py:391–409  ·  view source on GitHub ↗

Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention.

(self, qkv)

Source from the content-addressed store, hash-verified

389 self.n_heads = n_heads
390
391 def forward(self, qkv):
392 """
393 Apply QKV attention.
394 :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
395 :return: an [N x (H * C) x T] tensor after attention.
396 """
397 bs, width, length = qkv.shape
398 assert width % (3 * self.n_heads) == 0
399 ch = width // (3 * self.n_heads)
400 q, k, v = qkv.chunk(3, dim=1)
401 scale = 1 / math.sqrt(math.sqrt(ch))
402 weight = th.einsum(
403 "bct,bcs->bts",
404 (q * scale).view(bs * self.n_heads, ch, length),
405 (k * scale).view(bs * self.n_heads, ch, length),
406 ) # More stable with f16 than dividing afterwards
407 weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
408 a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
409 return a.reshape(bs, -1, length)
410
411 @staticmethod
412 def count_flops(model, _x, y):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected