Download vae_attention.py from k17hawk/VAE: direct link, hf CLI and curl.
- Browser
- Download file 1.6 kB
-
https://huggingface.co/k17hawk/VAE/resolve/main/vae_attention.py
- Command line
-
hf download hf://k17hawk/VAE/vae_attention.py
-
curl -L -o vae_attention.py https://huggingface.co/k17hawk/VAE/resolve/main/vae_attention.py
1.6 kB
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| import math | |
| from self_attention import SelfAttention | |
| class VAE_AttentionBlock(nn.Module): | |
| def __init__(self, channels): | |
| super().__init__() | |
| self.groupnorm = nn.GroupNorm(32, channels) | |
| self.attention = SelfAttention(1, channels) | |
| def forward(self, x): | |
| # x: (Batch_Size, Features, Height, Width) | |
| residue = x | |
| # (Batch_Size, Features, Height, Width) -> (Batch_Size, Features, Height, Width) | |
| x = self.groupnorm(x) | |
| n, c, h, w = x.shape | |
| # (Batch_Size, Features, Height, Width) -> (Batch_Size, Features, Height * Width) | |
| x = x.view((n, c, h * w)) | |
| # (Batch_Size, Features, Height * Width) -> (Batch_Size, Height * Width, Features). Each pixel becomes a feature of size "Features", the sequence length is "Height * Width". | |
| x = x.transpose(-1, -2) | |
| # Perform self-attention WITHOUT mask | |
| # (Batch_Size, Height * Width, Features) -> (Batch_Size, Height * Width, Features) | |
| x = self.attention(x) | |
| # (Batch_Size, Height * Width, Features) -> (Batch_Size, Features, Height * Width) | |
| x = x.transpose(-1, -2) | |
| # (Batch_Size, Features, Height * Width) -> (Batch_Size, Features, Height, Width) | |
| x = x.view((n, c, h, w)) | |
| # (Batch_Size, Features, Height, Width) + (Batch_Size, Features, Height, Width) -> (Batch_Size, Features, Height, Width) | |
| x += residue | |
| # (Batch_Size, Features, Height, Width) | |
| return x |