| 1 | from enum import Enum |
| 2 | |
| 3 | import torch |
| 4 | |
| 5 | from ltx_core.model.common.normalization import NormType, build_normalization_layer |
| 6 | |
| 7 | |
| 8 | class AttentionType(Enum): |
| 9 | """Enum for specifying the attention mechanism type.""" |
| 10 | |
| 11 | VANILLA = "vanilla" |
| 12 | LINEAR = "linear" |
| 13 | NONE = "none" |
| 14 | |
| 15 | |
| 16 | class AttnBlock(torch.nn.Module): |
| 17 | def __init__( |
| 18 | self, |
| 19 | in_channels: int, |
| 20 | norm_type: NormType = NormType.GROUP, |
| 21 | ) -> None: |
| 22 | super().__init__() |
| 23 | self.in_channels = in_channels |
| 24 | |
| 25 | self.norm = build_normalization_layer(in_channels, normtype=norm_type) |
| 26 | self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 27 | self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 28 | self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 29 | self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 30 | |
| 31 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 32 | h_ = x |
| 33 | h_ = self.norm(h_) |
| 34 | q = self.q(h_) |
| 35 | k = self.k(h_) |
| 36 | v = self.v(h_) |
| 37 | |
| 38 | # compute attention |
| 39 | b, c, h, w = q.shape |
| 40 | q = q.reshape(b, c, h * w).contiguous() |
| 41 | q = q.permute(0, 2, 1).contiguous() # b,hw,c |
| 42 | k = k.reshape(b, c, h * w).contiguous() # b,c,hw |
| 43 | w_ = torch.bmm(q, k).contiguous() # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] |
| 44 | w_ = w_ * (int(c) ** (-0.5)) |
| 45 | w_ = torch.nn.functional.softmax(w_, dim=2) |
| 46 | |
| 47 | # attend to values |
| 48 | v = v.reshape(b, c, h * w).contiguous() |
| 49 | w_ = w_.permute(0, 2, 1).contiguous() # b,hw,hw (first hw of k, second of q) |
| 50 | h_ = torch.bmm(v, w_).contiguous() # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] |
| 51 | h_ = h_.reshape(b, c, h, w).contiguous() |
| 52 | |
| 53 | h_ = self.proj_out(h_) |
| 54 | |
| 55 | return x + h_ |
| 56 | |
| 57 | |
| 58 | def make_attn( |
| 59 | in_channels: int, |
| 60 | attn_type: AttentionType = AttentionType.VANILLA, |
| 61 | norm_type: NormType = NormType.GROUP, |
| 62 | ) -> torch.nn.Module: |
| 63 | match attn_type: |
| 64 | case AttentionType.VANILLA: |
| 65 | return AttnBlock(in_channels, norm_type=norm_type) |
| 66 | case AttentionType.NONE: |
| 67 | return torch.nn.Identity() |
| 68 | case AttentionType.LINEAR: |
| 69 | raise NotImplementedError(f"Attention type {attn_type.value} is not supported yet.") |
| 70 | case _: |
| 71 | raise ValueError(f"Unknown attention type: {attn_type}") |
| 72 |