Backup / VideoX-Fun /videox_fun /models /h3_autoencoder.py
YFanwang's picture
Upload VideoX-Fun batch 1/62 (5000 files)
a386871 verified
Raw History Blame Contribute Delete
78.2 kB
import json
import os
from typing import List, Tuple, Union, Optional
from functools import lru_cache
import random
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from diffusers import ConfigMixin, ModelMixin
from diffusers.configuration_utils import register_to_config
from diffusers.utils.torch_utils import maybe_allow_in_graph
from diffusers.models.autoencoders.vae import (
DiagonalGaussianDistribution,
)
from dataclasses import dataclass
import numbers
# from diffusers.models.modeling_outputs import AutoencoderKLOutput
from diffusers.utils import BaseOutput
from diffusers.models.attention import FeedForward
from diffusers.models.attention_processor import Attention
from torch.nn.attention.flex_attention import (
_DEFAULT_SPARSE_BLOCK_SIZE,
create_block_mask,
create_mask,
flex_attention,
)
@dataclass
class EncoderOutput(BaseOutput):
r"""
Output of encoding method.
Args:
latent (`torch.Tensor` of shape `(batch_size, num_channels, latent_height, latent_width)`):
The encoded latent.
"""
latent: torch.Tensor
@dataclass
class DecoderOutput(BaseOutput):
r"""
Output of decoding method.
Args:
sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
The decoded output sample from the last layer of the model.
"""
sample: torch.Tensor
commit_loss: Optional[torch.FloatTensor] = None
features: Optional = None
@dataclass
class AutoencoderKLOutput(BaseOutput):
"""
Output of AutoencoderKL encoding method.
Args:
latent_dist (`DiagonalGaussianDistribution`):
Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
`DiagonalGaussianDistribution` allows for sampling latents from the distribution.
"""
latent_dist: "DiagonalGaussianDistribution" # noqa: F821
features: Optional = None
def our_drop(z, p=0.5):
b, c, t, h, w = z.shape
mask = torch.arange(0, c, device=z.device).unsqueeze(0).repeat(b, 1)
idx = torch.randint(c // 4, c, (b, 1), device=z.device).repeat(1, c)
mask = (mask <= idx).float()
return z * mask[:, :, None, None, None]
def pad_at_dim(t, pad, dim=-1):
dims_from_right = (-dim - 1) if dim < 0 else (t.ndim - dim - 1)
zeros = (0, 0) * dims_from_right
return F.pad(t, (*zeros, *pad), mode="constant")
def cast_tuple(t, length=1):
return t if isinstance(t, tuple) else ((t,) * length)
# from ltx_video.models.transformers.attention import BasicTransformerBlock
class FeatureFusion(nn.Module):
def __init__(self, channels, conv_fn):
super().__init__()
# self.layer = conv_fn(channels * 2, channels, kernel_size=(3, 3, 3), bias=True)
def forward(self, x: torch.FloatTensor, res_feature: torch.FloatTensor, feature_weight) -> torch.FloatTensor:
# pad_feature = torch.cat((res_feature, res_feature.repeat(1, 1, x.shape[2] - 1, 1, 1) * 0.), dim=2)
pad_feature = torch.cat((res_feature, x[:, :, 1:]), dim=2)
return x * (1. - feature_weight) + pad_feature * feature_weight
# return self.layer(torch.cat((x, pad_feature), dim=1)) + x
class RMSNorm(nn.Module):
r"""
RMS Norm as introduced in https://arxiv.org/abs/1910.07467 by Zhang et al.
Args:
dim (`int`): Number of dimensions to use for `weights`. Only effective when `elementwise_affine` is True.
eps (`float`): Small value to use when calculating the reciprocal of the square-root.
elementwise_affine (`bool`, defaults to `True`):
Boolean flag to denote if affine transformation should be applied.
bias (`bool`, defaults to False): If also training the `bias` param.
"""
def __init__(self, dim, eps: float, elementwise_affine: bool = True, bias: bool = False):
super().__init__()
self.eps = eps
self.elementwise_affine = elementwise_affine
if isinstance(dim, numbers.Integral):
dim = (dim,)
self.dim = torch.Size(dim)
self.weight = None
self.bias = None
if elementwise_affine:
self.weight = nn.Parameter(torch.ones(dim))
if bias:
self.bias = nn.Parameter(torch.zeros(dim))
def forward(self, hidden_states):
# if is_torch_npu_available():
# import torch_npu
#
# if self.weight is not None:
# # convert into half-precision if necessary
# if self.weight.dtype in [torch.float16, torch.bfloat16]:
# hidden_states = hidden_states.to(self.weight.dtype)
# hidden_states = torch_npu.npu_rms_norm(hidden_states, self.weight, epsilon=self.eps)[0]
# if self.bias is not None:
# hidden_states = hidden_states + self.bias
# else:
input_dtype = hidden_states.dtype
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
if self.weight is not None:
# convert into half-precision if necessary
if self.weight.dtype in [torch.float16, torch.bfloat16]:
hidden_states = hidden_states.to(self.weight.dtype)
hidden_states = hidden_states * self.weight
if self.bias is not None:
hidden_states = hidden_states + self.bias
else:
hidden_states = hidden_states.to(input_dtype)
return hidden_states
class PixelNorm(nn.Module):
def __init__(self, channels=32, dim=1, eps=1e-8):
super(PixelNorm, self).__init__()
self.dim = dim
self.eps = eps
def forward(self, x):
return x / torch.sqrt(torch.mean(x ** 2, dim=self.dim, keepdim=True) + self.eps)
# class PixelNorm(nn.Module):
# def __init__(self, channels=32, eps=1e-5):
# super(PixelNorm, self).__init__()
# self.eps = eps
#
# def forward(self, x):
# return (x - x.mean(dim=1, keepdim=True)) / (x.std(dim=1, keepdim=True) + self.eps)
class SpatialNorm(nn.Module):
def __init__(self, channels=32, eps=1e-6):
super(SpatialNorm, self).__init__()
self.eps = eps
def forward(self, x):
return x / torch.sqrt(torch.mean(x ** 2, dim=(1, 3, 4), keepdim=True) + self.eps)
class BatchNorm(nn.Module):
def __init__(self, channels=32, eps=1e-5):
super(BatchNorm, self).__init__()
def forward(self, x):
return x
class GroupNorm(nn.Module):
def __init__(self, channels=64, groups=32, ):
super().__init__()
self.norm = nn.GroupNorm(groups, channels)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
b, c, t, h, w = x.shape
out = self.norm(x.transpose(1, 2).flatten(0, 1))
return out.reshape((b, t) + out.shape[1:]).transpose(1, 2)
class LayerNorm(nn.Module):
def __init__(self, channels=64, ):
super().__init__()
self.norm = nn.LayerNorm(channels)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
b, c, t, h, w = x.shape
out = self.norm(x.flatten(2).transpose(1, 2))
return out.transpose(1, 2).reshape((b, c, t, h, w))
class DyTNorm(torch.nn.Module):
def __init__(self, dim: int, alpha_init: float = 0.5, affine: bool = True):
super().__init__()
self.alpha = torch.nn.Parameter(torch.ones(1) * alpha_init)
self.scale = torch.nn.Parameter(torch.ones(dim)) if affine else None
self.shift = torch.nn.Parameter(torch.zeros(dim)) if affine else None
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = (self.alpha * x).clamp(-1., 1.) # .tanh()
if self.scale is not None:
assert self.scale.shape[-1] == self.shift.shape[-1] == x.shape[
-1], f"Wrong shape: {self.scale.shape}, {self.shift.shape}, {x.shape}"
return x * self.scale + self.shift
else:
return x
class CausalConv3dRepeat(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size: Union[int, Tuple[int]] = 3,
strides: Union[int, Tuple[int]] = 1,
dilation: int = 1,
groups: int = 1,
**kwargs,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
kernel_size = cast_tuple(kernel_size, 3)
self.time_kernel_size = kernel_size[0]
dilation = (dilation, 1, 1)
height_pad = kernel_size[1] // 2
width_pad = kernel_size[2] // 2
padding = (0, height_pad, width_pad)
self.conv = nn.Conv3d(
in_channels,
out_channels,
kernel_size,
stride=strides,
dilation=dilation,
padding=padding,
padding_mode="zeros",
groups=groups,
)
def forward(self, x, causal: bool = True):
if causal:
first_frame_pad = x[:, :, :1, :, :].repeat(
(1, 1, self.time_kernel_size - 1, 1, 1)
)
x = torch.cat((first_frame_pad, x), dim=2)
else:
first_frame_pad = x[:, :, :1, :, :].repeat(
(1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
)
last_frame_pad = x[:, :, -1:, :, :].repeat(
(1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
)
x = torch.cat((first_frame_pad, x, last_frame_pad), dim=2)
x = self.conv(x)
return x
@property
def weight(self):
return self.conv.weight
class CausalConv3d(nn.Module):
def __init__(
self,
chan_in,
chan_out,
kernel_size: Union[int, Tuple[int, int, int]],
pad_mode="constant",
strides=None, # allow custom stride
**kwargs,
):
super().__init__()
kernel_size = cast_tuple(kernel_size, 3)
time_kernel_size, height_kernel_size, width_kernel_size = kernel_size
dilation = kwargs.pop("dilation", 1)
stride = strides[0] if strides is not None else kwargs.pop("stride", 1)
self.pad_mode = pad_mode
time_pad = dilation * (time_kernel_size - 1) + (1 - stride)
height_pad = height_kernel_size // 2
width_pad = width_kernel_size // 2
self.time_pad = time_pad
self.time_causal_padding = (width_pad, width_pad, height_pad, height_pad, time_pad, 0)
stride = strides if strides is not None else (stride, 1, 1)
dilation = (dilation, 1, 1)
self.conv = nn.Conv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)
def forward(self, x):
x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
x = self.conv(x)
return x
class NormalConv3d(nn.Module):
def __init__(
self,
chan_in,
chan_out,
kernel_size: Union[int, Tuple[int, int, int]],
pad_mode="constant",
strides=None, # allow custom stride
**kwargs,
):
super().__init__()
kernel_size = cast_tuple(kernel_size, 3)
time_kernel_size, height_kernel_size, width_kernel_size = kernel_size
dilation = kwargs.pop("dilation", 1)
stride = strides[0] if strides is not None else kwargs.pop("stride", 1)
self.pad_mode = pad_mode
# time_pad = dilation * (time_kernel_size - 1) + (1 - stride)
time_pad = time_kernel_size // 2
height_pad = height_kernel_size // 2
width_pad = width_kernel_size // 2
# self.time_pad = time_pad
# self.time_causal_padding = (width_pad, width_pad, height_pad, height_pad, time_pad, 0)
stride = strides if strides is not None else (stride, 1, 1)
dilation = (dilation, 1, 1)
self.conv = nn.Conv3d(chan_in, chan_out,
kernel_size,
stride=stride,
padding=(time_pad, height_pad, width_pad),
dilation=dilation,
**kwargs)
def forward(self, x):
# x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
x = self.conv(x)
return x
# Based on SpectralConv1d from the official StyleGAN-T code
# https://github.com/autonomousvision/stylegan-t/blob/36ab80ce76237fefe03e65e9b3161c040ae888e3/networks/discriminator.py#L29
class SpectralCausalConv3d(CausalConv3dRepeat):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
torch.nn.utils.parametrizations.spectral_norm(self.conv, name="weight", n_power_iterations=1, eps=1e-12, dim=0)
class ResBlock3D(nn.Module):
def __init__(
self,
in_channels, # SCH: added
filters,
conv_fn,
activation_fn=nn.Hardswish,
use_conv_shortcut=False,
norm_type=PixelNorm,
num_groups=32,
):
super().__init__()
self.in_channels = in_channels
self.filters = filters
self.activate = activation_fn()
self.use_conv_shortcut = use_conv_shortcut
# SCH: MAGVIT uses GroupNorm by default
self.norm1 = norm_type(in_channels)
self.conv1 = conv_fn(in_channels, self.filters, kernel_size=(3, 3, 3), bias=False)
self.norm2 = norm_type(self.filters)
self.conv2 = conv_fn(self.filters, self.filters, kernel_size=(3, 3, 3), bias=False)
if in_channels != filters:
if self.use_conv_shortcut:
self.conv3 = conv_fn(in_channels, self.filters, kernel_size=(3, 3, 3), bias=False)
else:
self.conv3 = conv_fn(in_channels, self.filters, kernel_size=(1, 1, 1), bias=False)
else:
self.conv3 = None
def forward(self, residual):
x = residual
x = self.norm1(x)
x = self.activate(x)
x = self.conv1(x)
x = self.norm2(x)
x = self.activate(x)
x = self.conv2(x)
if self.in_channels != self.filters and self.conv3 is not None: # SCH: ResBlock X->Y
residual = self.conv3(residual)
return x + residual
class ResBlock3DBN(nn.Module):
def __init__(
self,
in_channels, # SCH: added
filters,
conv_fn,
activation_fn=nn.Hardswish,
use_conv_shortcut=False,
norm_type=PixelNorm,
num_groups=32,
):
super().__init__()
self.in_channels = in_channels
self.filters = filters
self.activate = activation_fn()
self.use_conv_shortcut = use_conv_shortcut
# SCH: MAGVIT uses GroupNorm by default
self.conv1 = conv_fn(in_channels, self.filters, kernel_size=(3, 3, 3), bias=False)
self.norm1 = nn.BatchNorm3d(self.filters)
self.conv2 = conv_fn(self.filters, self.filters, kernel_size=(3, 3, 3), bias=False)
self.norm2 = nn.BatchNorm3d(self.filters)
if in_channels != filters:
if self.use_conv_shortcut:
self.conv3 = conv_fn(in_channels, self.filters, kernel_size=(3, 3, 3), bias=False)
else:
self.conv3 = conv_fn(in_channels, self.filters, kernel_size=(1, 1, 1), bias=False)
def forward(self, x):
residual = x
x = self.conv1(x)
x = self.norm1(x)
x = self.activate(x)
x = self.conv2(x)
x = self.norm2(x)
x = self.activate(x)
if self.in_channels != self.filters: # SCH: ResBlock X->Y
residual = self.conv3(residual)
return x + residual
class SpatialBlock(nn.Module):
def __init__(self, channels: int, activation_fn=nn.ReLU, channel_mul=1):
super().__init__()
act_fn = activation_fn()
self.conv = nn.Sequential(
nn.GroupNorm(32, channels),
act_fn,
nn.Conv2d(channels, channels * channel_mul, kernel_size=3, stride=1, padding=1, bias=False),
nn.GroupNorm(32, channels * channel_mul),
act_fn,
nn.Conv2d(channels * channel_mul, channels, kernel_size=3, stride=1, padding=1, bias=False),
)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
return self.conv(x) + x
class SpatialBlockBN(nn.Module):
def __init__(self, channels: int, activation_fn=nn.ReLU, channel_mul=1):
super().__init__()
act_fn = activation_fn()
self.conv = nn.Sequential(
nn.Conv2d(channels, channels * channel_mul, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(channels * channel_mul),
act_fn,
nn.Conv2d(channels * channel_mul, channels, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(channels),
act_fn,
)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
return self.conv(x) + x
def patchify(x, patch_size_hw=4, patch_size_t=1):
if patch_size_hw == 1 and patch_size_t == 1:
return x
if x.dim() == 4:
x = rearrange(
x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw
)
elif x.dim() == 5:
x = rearrange(
x,
"b c (f p) (h q) (w r) -> b (c p r q) f h w",
p=patch_size_t,
q=patch_size_hw,
r=patch_size_hw,
)
else:
raise ValueError(f"Invalid input shape: {x.shape}")
return x
def unpatchify(x, patch_size_hw=4, patch_size_t=1):
if patch_size_hw == 1 and patch_size_t == 1:
return x
if x.dim() == 4:
x = rearrange(
x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw
)
elif x.dim() == 5:
x = rearrange(
x,
"b (c p r q) f h w -> b c (f p) (h q) (w r)",
p=patch_size_t,
q=patch_size_hw,
r=patch_size_hw,
)
return x
class Patchify2D(nn.Module):
def __init__(self, channels=64, activation_fn=nn.Hardswish, channel_mul=2, block_type=SpatialBlock):
super().__init__()
self.layers = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
block_type(channels=32, activation_fn=activation_fn),
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
block_type(channels=64, activation_fn=activation_fn),
block_type(channels=64, activation_fn=activation_fn),
)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
b, c, t, h, w = x.shape
out = self.layers(x.transpose(1, 2).flatten(0, 1))
return out.reshape((b, t) + out.shape[1:]).transpose(1, 2)
class UnPatchify2D(nn.Module):
def __init__(self, channels=64, activation_fn=nn.Hardswish, channel_mul=2, block_type=SpatialBlock):
super().__init__()
self.layers = nn.Sequential(
block_type(channels=64, activation_fn=activation_fn),
block_type(channels=64, activation_fn=activation_fn),
nn.Conv2d(64, 32 * 4, kernel_size=3, stride=1, padding=1),
nn.PixelShuffle(2),
block_type(channels=32, activation_fn=activation_fn),
nn.Conv2d(32, 16 * 4, kernel_size=3, stride=1, padding=1),
nn.PixelShuffle(2),
nn.Conv2d(16, 3, kernel_size=3, stride=1, padding=1),
)
def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
b, c, t, h, w = x.shape
out = self.layers(x.transpose(1, 2).flatten(0, 1))
return out.reshape((b, t) + out.shape[1:]).transpose(1, 2)
def apply_rotary_emb(x, freqs):
cos, sin = freqs
x_real, x_imag = x.unflatten(2, (-1, 2)).unbind(-1) # [B, S, H, D // 2]
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
return out
@lru_cache
def create_causal_block_mask_cached(block_size, B, H, Q_LEN, KV_LEN, device="cuda"):
def causal_block_mask(b, h, q_idx, kv_idx):
mask = q_idx // block_size >= kv_idx // block_size
return mask
return create_mask(causal_block_mask, B, None, Q_LEN, KV_LEN, device=device,
# _compile=True
)
class LTXVideoAttentionProcessor2_0:
r"""
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
used in the LTX model. It applies a normalization layer and rotary embedding on the query and key vector.
"""
def __init__(self):
if not hasattr(F, "scaled_dot_product_attention"):
raise ImportError(
"LTXVideoAttentionProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
)
def __call__(
self,
attn: Attention,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[torch.Tensor] = None,
frame_seq_len: Optional[int] = None,
) -> torch.Tensor:
batch_size, sequence_length, _ = (
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
)
if attention_mask is not None:
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if encoder_hidden_states is None:
encoder_hidden_states = hidden_states
query = attn.to_q(hidden_states)
key = attn.to_k(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states)
query = attn.norm_q(query)
key = attn.norm_k(key)
if image_rotary_emb is not None:
query = apply_rotary_emb(query, image_rotary_emb)
key = apply_rotary_emb(key, image_rotary_emb)
query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
assert frame_seq_len is not None
B, H, q_len, _ = query.shape
_, _, kv_len, _ = key.shape
mask = create_causal_block_mask_cached(
block_size=frame_seq_len,
B=B,
H=H,
Q_LEN=q_len,
KV_LEN=kv_len,
device=query.device
)
hidden_states = F.scaled_dot_product_attention(
query, key, value, attn_mask=mask, dropout_p=0.0,
)
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
hidden_states = hidden_states.to(query.dtype)
hidden_states = attn.to_out[0](hidden_states)
hidden_states = attn.to_out[1](hidden_states)
return hidden_states
class LTXVideoRotaryPosEmbed(nn.Module):
def __init__(
self,
dim: int,
base_num_frames: int = 20,
base_height: int = 2048,
base_width: int = 2048,
patch_size: int = 1,
patch_size_t: int = 1,
theta: float = 10000.0,
) -> None:
super().__init__()
self.dim = dim
self.base_num_frames = base_num_frames
self.base_height = base_height
self.base_width = base_width
self.patch_size = patch_size
self.patch_size_t = patch_size_t
self.theta = theta
def forward(
self,
hidden_states: torch.Tensor,
num_frames: int,
height: int,
width: int,
rope_interpolation_scale: Optional[Tuple[torch.Tensor, float, float]] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
batch_size = hidden_states.size(0)
# Always compute rope in fp32
grid_h = torch.arange(height, dtype=torch.float32, device=hidden_states.device)
grid_w = torch.arange(width, dtype=torch.float32, device=hidden_states.device)
grid_f = torch.arange(num_frames, dtype=torch.float32, device=hidden_states.device)
grid = torch.meshgrid(grid_f, grid_h, grid_w, indexing="ij")
grid = torch.stack(grid, dim=0)
grid = grid.unsqueeze(0).repeat(batch_size, 1, 1, 1, 1)
if rope_interpolation_scale is not None:
grid[:, 0:1] = grid[:, 0:1] * rope_interpolation_scale[0] * self.patch_size_t / self.base_num_frames
grid[:, 1:2] = grid[:, 1:2] * rope_interpolation_scale[1] * self.patch_size / self.base_height
grid[:, 2:3] = grid[:, 2:3] * rope_interpolation_scale[2] * self.patch_size / self.base_width
grid = grid.flatten(2, 4).transpose(1, 2)
start = 1.0
end = self.theta
freqs = self.theta ** torch.linspace(
math.log(start, self.theta),
math.log(end, self.theta),
self.dim // 6,
device=hidden_states.device,
dtype=torch.float32,
)
freqs = freqs * math.pi / 2.0
freqs = freqs * (grid.unsqueeze(-1) * 2 - 1)
freqs = freqs.transpose(-1, -2).flatten(2)
cos_freqs = freqs.cos().repeat_interleave(2, dim=-1)
sin_freqs = freqs.sin().repeat_interleave(2, dim=-1)
if self.dim % 6 != 0:
cos_padding = torch.ones_like(cos_freqs[:, :, : self.dim % 6])
sin_padding = torch.zeros_like(cos_freqs[:, :, : self.dim % 6])
cos_freqs = torch.cat([cos_padding, cos_freqs], dim=-1)
sin_freqs = torch.cat([sin_padding, sin_freqs], dim=-1)
return cos_freqs, sin_freqs
@maybe_allow_in_graph
class LTXVideoTransformerBlock(nn.Module):
r"""
Transformer block used in [LTX](https://huggingface.co/Lightricks/LTX-Video).
Args:
dim (`int`):
The number of channels in the input and output.
num_attention_heads (`int`):
The number of heads to use for multi-head attention.
attention_head_dim (`int`):
The number of channels in each head.
qk_norm (`str`, defaults to `"rms_norm"`):
The normalization layer to use.
activation_fn (`str`, defaults to `"gelu-approximate"`):
Activation function to use in feed-forward.
eps (`float`, defaults to `1e-6`):
Epsilon value for normalization layers.
"""
def __init__(
self,
dim: int,
num_attention_heads: int,
attention_head_dim: int,
cross_attention_dim=None,
qk_norm: str = "rms_norm_across_heads",
activation_fn: str = "gelu-approximate",
attention_bias: bool = True,
attention_out_bias: bool = True,
eps: float = 1e-6,
elementwise_affine: bool = False,
):
super().__init__()
self.norm1 = nn.LayerNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
# self.norm1 = RMSNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
self.attn1 = Attention(
query_dim=dim,
heads=num_attention_heads,
kv_heads=num_attention_heads,
dim_head=attention_head_dim,
bias=attention_bias,
cross_attention_dim=None,
out_bias=attention_out_bias,
qk_norm=qk_norm,
processor=LTXVideoAttentionProcessor2_0(),
)
self.norm2 = nn.LayerNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
# self.norm2 = RMSNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
self.attn2 = Attention(
query_dim=dim,
cross_attention_dim=cross_attention_dim,
heads=num_attention_heads,
kv_heads=num_attention_heads,
dim_head=attention_head_dim,
bias=attention_bias,
out_bias=attention_out_bias,
qk_norm=qk_norm,
processor=LTXVideoAttentionProcessor2_0(),
)
self.ff = FeedForward(dim, activation_fn=activation_fn)
self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim ** 0.5)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
frame_seq_len=None,
) -> torch.Tensor:
batch_size = hidden_states.size(0)
norm_hidden_states = self.norm1(hidden_states)
num_ada_params = self.scale_shift_table.shape[0]
ada_values = self.scale_shift_table[None, None] # + temb.reshape(batch_size, temb.size(1), num_ada_params, -1)
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ada_values.unbind(dim=2)
norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
attn_hidden_states = self.attn1(
hidden_states=norm_hidden_states,
encoder_hidden_states=None,
image_rotary_emb=image_rotary_emb,
frame_seq_len=frame_seq_len,
)
hidden_states = hidden_states + attn_hidden_states * gate_msa
attn_hidden_states = self.attn2(
hidden_states,
encoder_hidden_states=None, # encoder_hidden_states,
image_rotary_emb=image_rotary_emb, # None,
frame_seq_len=frame_seq_len,
# attention_mask=encoder_attention_mask,
)
hidden_states = hidden_states + attn_hidden_states
norm_hidden_states = self.norm2(hidden_states) * (1 + scale_mlp) + shift_mlp
ff_output = self.ff(norm_hidden_states)
hidden_states = hidden_states + ff_output * gate_mlp
return hidden_states
class LinearAttention(torch.nn.Module):
def __init__(self,
query_dim,
heads=16,
dim_head=64,
window_size=1,
):
super().__init__()
self.heads = heads
self.dim_head = dim_head
self.window_size = window_size
self.scale = dim_head ** -0.5
self.to_q = torch.nn.Sequential(
torch.nn.Conv3d(query_dim, heads * dim_head, kernel_size=1, stride=1, padding=0),
torch.nn.BatchNorm3d(heads * dim_head),
)
self.to_k = torch.nn.Sequential(
torch.nn.Conv3d(query_dim, query_dim, kernel_size=3, stride=1, padding=1, groups=query_dim),
torch.nn.BatchNorm3d(query_dim),
torch.nn.Conv3d(query_dim, heads * dim_head * window_size, kernel_size=1, stride=1, padding=0),
torch.nn.BatchNorm3d(heads * dim_head * window_size),
)
self.to_v = torch.nn.Sequential(
torch.nn.Conv3d(query_dim, query_dim, kernel_size=3, stride=1, padding=1, groups=query_dim),
torch.nn.Conv3d(query_dim, heads * dim_head * window_size, kernel_size=1, stride=1, padding=0),
)
self.to_out = torch.nn.Conv3d(heads * dim_head, query_dim, kernel_size=1, stride=1, padding=0)
def forward(self, x):
# ####### x: [B, C, T, H, W] ########
b, c, t, h, w = x.shape
q = self.to_q(x).flatten(2).reshape(b, self.heads, self.dim_head, -1).unsqueeze(-2).permute(0, 1, 4, 3, 2)
k = self.to_k(x).flatten(2).reshape(b, self.heads, self.dim_head, self.window_size, -1).permute(0, 1, 4, 2, 3)
v = self.to_v(x).flatten(2).reshape(b, self.heads, self.dim_head, self.window_size, -1).permute(0, 1, 4, 3, 2)
# q = self.to_q(x).flatten(2).reshape(b, self.heads, self.dim_head, -1).transpose(-1, -2)
# k = self.to_k(x).flatten(2).reshape(b, self.heads, self.dim_head, -1)
# v = self.to_v(x).flatten(2).reshape(b, self.heads, self.dim_head, -1).transpose(-1, -2)
attn = torch.matmul(q, k) * self.scale
attn = attn.softmax(dim=-1)
out = torch.matmul(attn, v).squeeze(
dim=-2).transpose(-1, -2).flatten(1, 2).reshape(b, self.heads * self.dim_head, t, h, w)
# out = torch.matmul(attn, v).transpose(-1, -2).flatten(1, 2).reshape(b, self.heads * self.dim_head, t, h, w)
out = self.to_out(out)
return out
class LocalFeedForward(torch.nn.Module):
def __init__(self,
dim,
activation_fn=None,
expansion=4,
):
super().__init__()
self.layers = torch.nn.Sequential(
torch.nn.Conv2d(dim, dim * expansion, kernel_size=1, stride=1, padding=0),
torch.nn.Hardswish(),
torch.nn.Conv2d(dim * expansion, dim * expansion, kernel_size=3, stride=1, padding=1,
groups=dim * expansion),
torch.nn.Hardswish(),
torch.nn.Conv2d(dim * expansion, dim, kernel_size=1, stride=1, padding=0),
)
def forward(self, x):
# ####### x: [B, C, T, H, W] ########
b, c, t, h, w = x.shape
x = x.transpose(1, 2).flatten(0, 1)
out = self.layers(x)
return out.reshape(b, t, c, h, w).transpose(1, 2)
@maybe_allow_in_graph
class LinearTransformerBlock(nn.Module):
r"""
Transformer block used in [LTX](https://huggingface.co/Lightricks/LTX-Video).
Args:
dim (`int`):
The number of channels in the input and output.
num_attention_heads (`int`):
The number of heads to use for multi-head attention.
attention_head_dim (`int`):
The number of channels in each head.
qk_norm (`str`, defaults to `"rms_norm"`):
The normalization layer to use.
activation_fn (`str`, defaults to `"gelu-approximate"`):
Activation function to use in feed-forward.
eps (`float`, defaults to `1e-6`):
Epsilon value for normalization layers.
"""
def __init__(
self,
dim: int,
num_attention_heads: int,
attention_head_dim: int,
cross_attention_dim=None,
qk_norm: str = "rms_norm_across_heads",
activation_fn: str = "gelu-approximate",
attention_bias: bool = True,
attention_out_bias: bool = True,
eps: float = 1e-6,
elementwise_affine: bool = False,
):
super().__init__()
self.norm1 = LayerNorm(dim)
self.attn1 = LinearAttention(
query_dim=dim,
# heads=num_attention_heads,
# dim_head=attention_head_dim,
# window_size=9,
)
# self.norm2 = LayerNorm(dim)
# # self.attn2 = LinearAttention(
# # query_dim=dim,
# # cross_attention_dim=cross_attention_dim,
# # heads=num_attention_heads,
# # kv_heads=num_attention_heads,
# # dim_head=attention_head_dim,
# # bias=attention_bias,
# # out_bias=attention_out_bias,
# # qk_norm=qk_norm,
# # processor=LTXVideoAttentionProcessor2_0(),
# # window_size=9,
# # )
# self.ff = LocalFeedForward(dim)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
frame_seq_len=None,
) -> torch.Tensor:
norm_hidden_states = self.norm1(hidden_states)
attn_hidden_states = self.attn1(norm_hidden_states)
hidden_states = hidden_states + attn_hidden_states
# norm_hidden_states = self.norm2(hidden_states)
# ff_output = self.ff(norm_hidden_states)
# hidden_states = hidden_states + ff_output
return hidden_states
class Discriminator(ModelMixin, ConfigMixin):
@register_to_config
def __init__(
self,
in_out_channels=48,
latent_channels=128,
spatial_stride=(2, 2, 2, 2, 2),
temporal_stride=(2, 2, 2, 1, 1),
encoder_width=(32, 64, 128, 256, 256),
decoder_width=(256, 256, 128, 64, 32),
encoder_depth=(2, 4, 6, 8, 8),
decoder_depth=(6, 6, 4, 4, 2),
bottleneck_depth=4,
num_groups=32, # for nn.GroupNorm
activation_fn=nn.Hardswish,
encoder_conv_type=CausalConv3dRepeat,
decoder_conv_type=CausalConv3dRepeat,
encoder_block_type=ResBlock3D,
decoder_block_type=ResBlock3D,
use_pixel_shuffle=True,
patch_size=4,
patch_type="default",
use_attention=False,
scaling_factor=0.3,
symmetric_width=False,
bypass_features=False,
distill_features=False,
use_2d_mix=False,
use_ae=False,
):
super().__init__()
in_out_channels = in_out_channels * 2
latent_channels = 1
width = encoder_width
depth = encoder_depth
conv_type = encoder_conv_type
block_type = encoder_block_type
use_out_norm = False
use_attention = False
out_norm = PixelNorm
return_features = False
self.num_res_blocks = depth
self.num_blocks = len(spatial_stride)
self.num_groups = num_groups
self.activate = activation_fn()
self.use_out_norm = use_out_norm
self.conv_fn = conv_type
self.return_features = return_features
self.block_args = dict(
conv_fn=self.conv_fn,
activation_fn=activation_fn,
use_conv_shortcut=False,
num_groups=self.num_groups,
)
self.patch_size = patch_size
self.patch_type = patch_type
if self.patch_size > 1:
if self.patch_type == "default":
self.patchify = patchify
elif self.patch_type == "2DUniform":
self.patchify = Patchify2D(block_type=SpatialBlock)
else:
raise NotImplementedError
self.use_attention = use_attention
# first layer conv
self.conv_in = self.conv_fn(
in_out_channels,
width[0],
kernel_size=(3, 3, 3),
)
self.bottleneck = nn.ModuleList([])
for _ in range(bottleneck_depth):
self.bottleneck.append(block_type(width[0], width[0], **self.block_args))
# ResBlocks and conv downsample
self.block_res_blocks = nn.ModuleList([])
self.conv_blocks = nn.ModuleList([])
prev_filters = width[0] # record for in_channels
for idx, s_stride in enumerate(spatial_stride):
filters = width[idx]
self.conv_blocks.append(
self.conv_fn(
prev_filters, filters, kernel_size=(3, 3, 3), strides=(temporal_stride[idx], s_stride, s_stride)
)
)
block_items = nn.ModuleList([])
if self.use_attention and idx == len(spatial_stride) - 1:
self.rope = LTXVideoRotaryPosEmbed(
dim=1024,
base_num_frames=20,
base_height=2048,
base_width=2048,
patch_size=1,
patch_size_t=1,
theta=10000.0,
)
self.rope_interpolation_scale = (
2 ** (sum(temporal_stride) - len(temporal_stride)) / 25,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
)
for _ in range(depth[idx]):
block_items.append(
LTXVideoTransformerBlock(
dim=filters,
num_attention_heads=16,
attention_head_dim=64,
cross_attention_dim=None,
)
)
else:
for _ in range(depth[idx]):
block_items.append(block_type(filters, filters, **self.block_args))
self.block_res_blocks.append(block_items)
prev_filters = filters # update in_channels
# MAGVIT uses Group Normalization
if self.use_out_norm:
self.norm_out = out_norm(channels=prev_filters)
# self.conv_out = self.conv_fn(prev_filters, latent_channels * 2, kernel_size=(1, 1, 1))
self.conv_out = nn.Sequential(
SpectralCausalConv3d(prev_filters, prev_filters // 2, kernel_size=(1, 1, 1)),
self.activate,
SpectralCausalConv3d(prev_filters // 2, prev_filters // 4, kernel_size=(1, 1, 1)),
self.activate,
SpectralCausalConv3d(prev_filters // 4, prev_filters // 4, kernel_size=(1, 2, 2)),
# self.activate,
SpectralCausalConv3d(prev_filters // 4, prev_filters // 8, kernel_size=(1, 1, 1)),
self.activate,
SpectralCausalConv3d(prev_filters // 8, latent_channels * 2, kernel_size=(1, 1, 1)),
)
def forward(self, x1, x2):
if self.patch_size > 1:
x1 = self.patchify(x1)
x2 = self.patchify(x2)
x = torch.cat((x1, x2), dim=1)
x = self.conv_in(x)
for block in self.bottleneck:
x = block(x)
for i in range(self.num_blocks):
# if self.return_features and i > 0:
# features.append(x)
x = self.conv_blocks[i](x)
if self.use_attention and i == self.num_blocks - 1:
b, c, t, h, w = x.shape
x = x.flatten(2).transpose(1, 2)
image_rotary_emb = self.rope(x, t, h, w, self.rope_interpolation_scale)
for j in range(self.num_res_blocks[i]):
x = self.block_res_blocks[i][j](x, image_rotary_emb=image_rotary_emb)
x = x.transpose(1, 2).reshape(b, c, t, h, w)
else:
for j in range(self.num_res_blocks[i]):
x = self.block_res_blocks[i][j](x)
if self.use_out_norm:
x = self.norm_out(x)
x = self.activate(x)
x = self.conv_out(x)
return x.chunk(2, dim=1)
class Encoder(nn.Module):
"""Encoder Blocks."""
def __init__(
self,
in_out_channels=3,
latent_channels=128,
spatial_stride=(2, 2, 2, 2, 2),
temporal_stride=(2, 2, 2, 1, 1),
width=(32, 64, 128, 256, 256),
depth=(2, 4, 6, 8, 8),
bottleneck_depth=8,
num_groups=32, # for nn.GroupNorm
activation_fn=nn.Hardswish,
conv_type=CausalConv3d,
block_type=ResBlock3D,
norm_type=PixelNorm,
patch_size=1,
patch_type="2DUniform",
use_attention=False,
bypass_features=False,
distill_features=False,
use_ae=False,
attention_type="default",
):
super().__init__()
self.use_ae = use_ae
if not self.use_ae:
latent_channels = latent_channels * 2
self.num_res_blocks = depth
self.num_blocks = len(spatial_stride)
self.num_groups = num_groups
self.activate = activation_fn()
self.conv_fn = conv_type
self.bypass_features = bypass_features
self.distill_features = distill_features
if norm_type == BatchNorm:
block_type = ResBlock3DBN
self.block_args = dict(
conv_fn=self.conv_fn,
activation_fn=activation_fn,
use_conv_shortcut=False,
norm_type=norm_type,
num_groups=self.num_groups,
)
self.patch_size = patch_size
self.patch_type = patch_type
if self.patch_size > 1:
if self.patch_type == "default":
self.patchify = torch.nn.functional.pixel_unshuffle
in_out_channels = 3 * self.patch_size * self.patch_size
elif self.patch_type == "2DUniform":
self.patchify = Patchify2D(block_type=SpatialBlock, activation_fn=activation_fn)
else:
self.patchify = nn.Identity()
self.use_attention = use_attention
self.attention_type = attention_type
if attention_type == "default":
attention_layer = LTXVideoTransformerBlock
elif attention_type == "linear":
attention_layer = LinearTransformerBlock
else:
raise NotImplementedError
# first layer conv
self.conv_in = self.conv_fn(
in_out_channels,
width[0],
kernel_size=(3, 3, 3),
)
self.bottleneck = nn.ModuleList([])
for _ in range(bottleneck_depth):
self.bottleneck.append(block_type(width[0], width[0], **self.block_args))
# ResBlocks and conv downsample
self.block_res_blocks = nn.ModuleList([])
self.conv_blocks = nn.ModuleList([])
prev_filters = width[0] # record for in_channels
for idx, s_stride in enumerate(spatial_stride):
filters = width[idx]
self.conv_blocks.append(
self.conv_fn(
prev_filters, filters, kernel_size=(3, 3, 3), strides=(temporal_stride[idx], s_stride, s_stride)
)
)
block_items = nn.ModuleList([])
if self.use_attention and idx == len(spatial_stride) - 1:
self.rope = LTXVideoRotaryPosEmbed(
dim=1024,
base_num_frames=20,
base_height=2048,
base_width=2048,
patch_size=1,
patch_size_t=1,
theta=10000.0,
)
self.rope_interpolation_scale = (
2 ** (sum(temporal_stride) - len(temporal_stride)) / 25,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
)
for _ in range(depth[idx]):
block_items.append(
attention_layer(
dim=filters,
num_attention_heads=16,
attention_head_dim=64,
cross_attention_dim=None,
)
)
else:
for i in range(depth[idx]):
block_items.append(block_type(filters, filters, **self.block_args))
self.rope = None
self.block_res_blocks.append(block_items)
prev_filters = filters # update in_channels
# MAGVIT uses Group Normalization
if norm_type == BatchNorm:
self.norm_out = None
else:
self.norm_out = norm_type(prev_filters)
self.conv_out = self.conv_fn(prev_filters, latent_channels, kernel_size=(1, 1, 1))
if self.use_ae:
self.norm_ae = torch.nn.BatchNorm3d(latent_channels, affine=False)
else:
self.norm_ae = None
def forward(self, x):
if self.patch_size > 1:
if self.patch_type == "default":
x = self.patchify(x.transpose(1, 2), self.patch_size).transpose(1, 2)
else:
x = self.patchify(x)
x = self.conv_in(x)
if self.distill_features:
features = [x, ]
else:
features = []
for block in self.bottleneck:
x = block(x)
if self.bypass_features:
features = [x[:, :, 0:1], ]
for i, (conv_block, block_res_block) in enumerate(zip(self.conv_blocks, self.block_res_blocks)):
x = conv_block(x)
if self.distill_features:
features.append(x)
if self.use_attention and i == self.num_blocks - 1:
if self.attention_type == "default" and self.rope is not None:
b, c, t, h, w = x.shape
x = x.flatten(2).transpose(1, 2)
image_rotary_emb = self.rope(x, t, h, w, self.rope_interpolation_scale)
for j, res_block in enumerate(block_res_block):
x = res_block(x, image_rotary_emb=image_rotary_emb, frame_seq_len=h * w, )
x = x.transpose(1, 2).reshape(b, c, t, h, w)
elif self.attention_type == "linear":
for j, res_block in enumerate(block_res_block):
x = res_block(x)
else:
raise NotImplementedError
else:
for j, res_block in enumerate(block_res_block):
x = res_block(x)
if self.bypass_features: # and not (self.use_attention and i == self.num_blocks - 1)
features.append(x[:, :, 0:1])
if self.norm_out is not None:
x = self.norm_out(x)
x = self.activate(x)
x = self.conv_out(x)
if self.use_ae:
x = self.norm_ae(x)
return x, features
class Decoder(nn.Module):
"""Decoder Blocks."""
def __init__(
self,
in_out_channels=3,
latent_channels=128,
spatial_stride=(2, 2, 2, 2, 2),
temporal_stride=(1, 1, 2, 2, 2),
width=(256, 256, 128, 64, 32),
depth=(6, 6, 4, 4, 2),
bottleneck_depth=8,
num_groups=32, # for nn.GroupNorm
activation_fn=nn.Hardswish,
conv_type=NormalConv3d,
block_type=ResBlock3D,
use_pixel_shuffle=False,
norm_type=PixelNorm,
patch_size=1,
patch_type="2DUniform",
use_attention=False,
bypass_features=False,
distill_features=False,
attention_type="default",
):
super().__init__()
self.export = False
self.image_rotary_emb = None
self.num_res_blocks = depth
self.num_blocks = len(spatial_stride)
self.num_groups = num_groups
self.use_pixel_shuffle = use_pixel_shuffle
self.activate = activation_fn()
self.conv_fn = conv_type
self.bypass_features = bypass_features
self.distill_features = distill_features
if norm_type == BatchNorm:
block_type = ResBlock3DBN
spatial_block_type = SpatialBlockBN
else:
spatial_block_type = SpatialBlock
self.block_args = dict(
conv_fn=self.conv_fn,
activation_fn=activation_fn,
use_conv_shortcut=False,
norm_type=norm_type,
num_groups=self.num_groups,
)
self.patch_size = patch_size
self.patch_type = patch_type
if self.patch_size > 1:
if self.patch_type == "default":
self.unpatchify = torch.nn.functional.pixel_shuffle
in_out_channels = 3 * self.patch_size * self.patch_size
elif self.patch_type == "2DUniform":
self.unpatchify = UnPatchify2D(block_type=spatial_block_type, activation_fn=activation_fn)
else:
self.unpatchify = nn.Identity()
self.use_attention = use_attention
self.attention_type = attention_type
if attention_type == "default":
attention_layer = LTXVideoTransformerBlock
elif attention_type == "linear":
attention_layer = LinearTransformerBlock
else:
raise NotImplementedError
# last conv
self.conv1 = self.conv_fn(latent_channels, width[0], kernel_size=(3, 3, 3), bias=True)
self.block_res_blocks = nn.ModuleList([])
self.conv_blocks = nn.ModuleList([])
self.spatial_conv_blocks = nn.ModuleList([])
self.spatial_res_blocks = nn.ModuleList([])
self.strides = []
self.feature_fusion = nn.ModuleList([])
# reverse to keep track of the in_channels, but append also in a reverse direction
for idx, s_stride in enumerate(spatial_stride):
if self.bypass_features:
self.feature_fusion.append(FeatureFusion(width[idx], conv_fn=self.conv_fn), )
else:
self.feature_fusion.append(nn.Identity())
filters = width[idx]
next_filters = width[idx + 1] if idx < len(width) - 1 else width[idx]
block_items = nn.ModuleList([])
if s_stride > 1:
num_blocks = depth[idx] // 2
else:
num_blocks = depth[idx]
if self.use_attention and idx == 0:
self.rope = LTXVideoRotaryPosEmbed(
dim=1024,
base_num_frames=20,
base_height=2048,
base_width=2048,
patch_size=1,
patch_size_t=1,
theta=10000.0,
)
self.rope_interpolation_scale = (
2 ** (sum(temporal_stride) - len(temporal_stride)) / 25,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
2 ** (sum(spatial_stride) - len(spatial_stride)) * 4,
)
for _ in range(num_blocks):
block_items.append(
attention_layer(
dim=filters,
num_attention_heads=16,
attention_head_dim=64,
cross_attention_dim=None,
)
)
else:
for i in range(num_blocks):
block_items.append(block_type(filters, filters, **self.block_args))
self.block_res_blocks.append(block_items) # SCH: append in front
self.strides.append((temporal_stride[idx], s_stride))
if self.use_pixel_shuffle:
self.conv_blocks.append(
self.conv_fn(
filters, next_filters * temporal_stride[idx], kernel_size=(3, 3, 3)
),
)
else:
self.conv_blocks.append(
self.conv_fn(
filters, next_filters * temporal_stride[idx], kernel_size=(3, 3, 3)
),
)
if s_stride > 1:
spatial_block_items = nn.ModuleList([])
for i in range(num_blocks):
spatial_block_items.append(spatial_block_type(next_filters, activation_fn=activation_fn))
if self.use_pixel_shuffle:
self.spatial_conv_blocks.append(
nn.Conv2d(
next_filters, next_filters * s_stride * s_stride, kernel_size=3, stride=1, padding=1,
),
)
else:
self.spatial_conv_blocks.append(
nn.Conv2d(
next_filters, next_filters, kernel_size=3, stride=1, padding=1,
),
)
else:
spatial_block_items = nn.Identity()
self.spatial_conv_blocks.append(
nn.Identity(),
)
self.spatial_res_blocks.append(spatial_block_items)
if self.bypass_features:
self.feature_fusion.append(FeatureFusion(next_filters, conv_fn=self.conv_fn), )
else:
self.feature_fusion.append(nn.Identity())
# ResBlocks and conv upsample
self.bottleneck = nn.ModuleList([])
for _ in range(bottleneck_depth):
self.bottleneck.append(block_type(next_filters, next_filters, **self.block_args))
if norm_type == BatchNorm:
self.norm_out = None
else:
self.norm_out = norm_type(next_filters)
self.conv_out = self.conv_fn(next_filters, in_out_channels, kernel_size=(3, 3, 3), bias=True)
if self.use_pixel_shuffle:
self.up = nn.PixelShuffle(2)
else:
self.up = nn.Upsample(scale_factor=2, mode='bilinear')
def forward(self, x, features=None):
x = self.conv1(x)
if self.bypass_features:
assert features is not None
if self.training:
feature_weight = round(random.random()) / 2.
else:
feature_weight = 0.5
if self.distill_features:
features = []
for i, (feature_fusion, block_res_block, conv_block, spatial_res_block, spatial_conv_block) in enumerate(
zip(self.feature_fusion, self.block_res_blocks, self.conv_blocks, self.spatial_res_blocks,
self.spatial_conv_blocks)): # i in range(self.num_blocks):
if self.bypass_features: # and not (self.use_attention and i == 0)
x = feature_fusion(x, features.pop(-1), feature_weight=feature_weight)
if self.use_attention and i == 0:
if self.attention_type == "default":
b, c, t, h, w = x.shape
x = x.flatten(2).transpose(1, 2)
if self.image_rotary_emb is None or not self.export:
self.image_rotary_emb = self.rope(x, t, h, w, self.rope_interpolation_scale)
for block in block_res_block:
x = block(x,
image_rotary_emb=self.image_rotary_emb,
frame_seq_len=h * w, )
x = x.transpose(1, 2).reshape(b, c, t, h, w)
elif self.attention_type == "linear":
for block in block_res_block:
x = block(x)
else:
raise NotImplementedError
else:
for block in block_res_block:
x = block(x)
if self.distill_features:
features.append(x)
t_stride, s_stride = self.strides[i]
x = conv_block(x)
if t_stride > 1:
x = rearrange(
x,
"B (C ts) T H W -> B C (T ts) H W",
ts=t_stride, )[:, :, 1:]
if s_stride > 1:
b, c, t, h, w = x.shape
x = x.transpose(1, 2).flatten(0, 1)
for spatial_block in spatial_res_block:
x = spatial_block(x)
x = spatial_conv_block(x)
x = self.up(x)
x = x.reshape((b, t) + x.shape[1:]).transpose(1, 2)
if self.bypass_features:
x = self.feature_fusion[-1](x, features.pop(-1), feature_weight=feature_weight)
for block in self.bottleneck:
x = block(x)
if self.distill_features:
features.append(x)
if self.norm_out is not None:
x = self.norm_out(x)
x = self.activate(x)
x = self.conv_out(x)
if self.patch_size > 1:
if self.patch_type == "default":
x = self.unpatchify(x.transpose(1, 2), self.patch_size).transpose(1, 2)
else:
x = self.unpatchify(x)
if self.distill_features:
return x, features
else:
return x
class H3AE(ModelMixin, ConfigMixin):
_supports_gradient_checkpointing = True
@register_to_config
def __init__(
self,
in_out_channels=48,
latent_channels=128,
spatial_stride=(2, 2, 2, 2, 2),
temporal_stride=(2, 2, 2, 1, 1),
encoder_width=(32, 64, 128, 256, 256),
decoder_width=(256, 256, 128, 64, 32),
encoder_depth=(2, 4, 6, 8, 8),
decoder_depth=(6, 6, 4, 4, 2),
bottleneck_depth=4,
num_groups=32, # for nn.GroupNorm
activation_fn="hardswish",
norm_type="pn",
encoder_conv_type="CausalConv3dRepeat",
decoder_conv_type="CausalConv3dRepeat",
encoder_block_type="ResBlock3D",
decoder_block_type="ResBlock3D",
use_pixel_shuffle=True,
patch_size=4,
patch_type="2DUniform",
use_attention=False,
mean=0.,
scaling_factor=0.1666,
latents_mean: List[float] = [],
latents_std: List[float] = [],
symmetric_width=False,
bypass_features=False,
distill_features=False,
use_ae=False,
attention_type="default",
):
super().__init__()
if activation_fn == "hardswish":
activation_fn = nn.Hardswish
elif activation_fn == "relu":
activation_fn = nn.ReLU
else:
raise ValueError(f"Unknown activation function: {activation_fn}")
if norm_type == "pn":
norm = PixelNorm
elif norm_type == "gn":
norm = GroupNorm
elif norm_type == "ln":
norm = LayerNorm
elif norm_type == "sn":
norm = SpatialNorm
elif norm_type == "bn":
norm = BatchNorm
else:
raise ValueError(f"Unknown norm type: {norm_type}")
encoder_conv_type = eval(encoder_conv_type)
encoder_block_type = eval(encoder_block_type)
decoder_conv_type = eval(decoder_conv_type)
decoder_block_type = eval(decoder_block_type)
self.use_ae = use_ae
self.bypass_features = bypass_features
self.distill_features = distill_features
self.scaling_factor = scaling_factor
self.mean = mean
self.latents_mean = latents_mean
self.latents_std = latents_std
self.micro_frame_size = 17
self.time_downsample_factor = 2 ** (sum(temporal_stride) - len(temporal_stride))
self.spatial_downscale_factor = 2 ** (sum(spatial_stride) - len(spatial_stride)) * patch_size
self.temporal_downscale_factor = self.time_downsample_factor
self.micro_frame_latent = 1 + (self.micro_frame_size - 1) // self.time_downsample_factor
# self.time_padding = (
# 0
# if (self.micro_frame_size % self.time_downsample_factor == 0)
# else self.time_downsample_factor - self.micro_frame_size % self.time_downsample_factor
# )
self.time_padding = self.time_downsample_factor - 1
self.use_z_tiling = False
self.use_hw_tiling = False
self.z_sample_size = 1
self.gradient_checkpointing = True
# NOTE: following MAGVIT, conv in bias=False in encoder first conv
self.encoder = Encoder(
in_out_channels=in_out_channels,
latent_channels=latent_channels,
spatial_stride=spatial_stride,
temporal_stride=temporal_stride,
width=encoder_width,
depth=encoder_depth,
bottleneck_depth=bottleneck_depth,
num_groups=num_groups, # for nn.GroupNorm
activation_fn=activation_fn,
conv_type=encoder_conv_type,
block_type=encoder_block_type,
norm_type=norm,
patch_size=patch_size,
patch_type=patch_type,
use_attention=use_attention,
bypass_features=self.bypass_features,
distill_features=self.distill_features,
use_ae=self.use_ae,
attention_type=attention_type,
)
if symmetric_width:
decoder_func = Decoder
else:
raise NotImplementedError
self.decoder = decoder_func(
in_out_channels=in_out_channels,
latent_channels=latent_channels,
spatial_stride=list(reversed(spatial_stride)),
temporal_stride=list(reversed(temporal_stride)),
width=decoder_width,
depth=decoder_depth,
bottleneck_depth=bottleneck_depth,
num_groups=num_groups, # for nn.GroupNorm
activation_fn=activation_fn,
conv_type=decoder_conv_type,
block_type=decoder_block_type,
use_pixel_shuffle=use_pixel_shuffle,
norm_type=norm,
patch_size=patch_size,
patch_type=patch_type,
use_attention=use_attention,
bypass_features=self.bypass_features,
distill_features=self.distill_features,
attention_type=attention_type,
)
def set_tiling_params(self, sample_size: int = 512, overlap_factor: float = 0.25):
self.tile_sample_min_size = sample_size
num_blocks = len(self.encoder.down_blocks)
self.tile_latent_min_size = int(sample_size / (2 ** (num_blocks - 1)))
self.tile_overlap_factor = overlap_factor
def enable_z_tiling(self, z_sample_size: int = 8):
r"""
Enable tiling during VAE decoding.
When this option is enabled, the VAE will split the input tensor in tiles to compute decoding in several
steps. This is useful to save some memory and allow larger batch sizes.
"""
self.use_z_tiling = z_sample_size > 1
self.z_sample_size = z_sample_size
assert (
z_sample_size % 8 == 0 or z_sample_size == 1
), f"z_sample_size must be a multiple of 8 or 1. Got {z_sample_size}."
def disable_z_tiling(self):
r"""
Disable tiling during VAE decoding. If `use_tiling` was previously invoked, this method will go back to computing
decoding in one step.
"""
self.use_z_tiling = False
def enable_hw_tiling(self):
r"""
Enable tiling during VAE decoding along the height and width dimension.
"""
self.use_hw_tiling = True
def disable_hw_tiling(self):
r"""
Disable tiling during VAE decoding along the height and width dimension.
"""
self.use_hw_tiling = False
def _hw_tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True):
overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
row_limit = self.tile_latent_min_size - blend_extent
# Split the image into 512x512 tiles and encode them separately.
rows = []
for i in range(0, x.shape[3], overlap_size):
row = []
for j in range(0, x.shape[4], overlap_size):
tile = x[
:,
:,
:,
i: i + self.tile_sample_min_size,
j: j + self.tile_sample_min_size,
]
tile = self.encoder(tile)
tile = self.quant_conv(tile)
row.append(tile)
rows.append(row)
result_rows = []
for i, row in enumerate(rows):
result_row = []
for j, tile in enumerate(row):
# blend the above tile and the left tile
# to the current tile and add the current tile to the result row
if i > 0:
tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
if j > 0:
tile = self.blend_h(row[j - 1], tile, blend_extent)
result_row.append(tile[:, :, :, :row_limit, :row_limit])
result_rows.append(torch.cat(result_row, dim=4))
moments = torch.cat(result_rows, dim=3)
return moments
def blend_z(
self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
) -> torch.Tensor:
blend_extent = min(a.shape[2], b.shape[2], blend_extent)
for z in range(blend_extent):
b[:, :, z, :, :] = a[:, :, -blend_extent + z, :, :] * (
1 - z / blend_extent
) + b[:, :, z, :, :] * (z / blend_extent)
return b
def blend_v(
self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
) -> torch.Tensor:
blend_extent = min(a.shape[3], b.shape[3], blend_extent)
for y in range(blend_extent):
b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (
1 - y / blend_extent
) + b[:, :, :, y, :] * (y / blend_extent)
return b
def blend_h(
self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
) -> torch.Tensor:
blend_extent = min(a.shape[4], b.shape[4], blend_extent)
for x in range(blend_extent):
b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (
1 - x / blend_extent
) + b[:, :, :, :, x] * (x / blend_extent)
return b
def _hw_tiled_decode(self, z: torch.FloatTensor, target_shape):
overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
row_limit = self.tile_sample_min_size - blend_extent
tile_target_shape = (
*target_shape[:3],
self.tile_sample_min_size,
self.tile_sample_min_size,
)
# Split z into overlapping 64x64 tiles and decode them separately.
# The tiles have an overlap to avoid seams between tiles.
rows = []
for i in range(0, z.shape[3], overlap_size):
row = []
for j in range(0, z.shape[4], overlap_size):
tile = z[
:,
:,
:,
i: i + self.tile_latent_min_size,
j: j + self.tile_latent_min_size,
]
tile = self.post_quant_conv(tile)
decoded = self.decoder(tile, target_shape=tile_target_shape)
row.append(decoded)
rows.append(row)
result_rows = []
for i, row in enumerate(rows):
result_row = []
for j, tile in enumerate(row):
# blend the above tile and the left tile
# to the current tile and add the current tile to the result row
if i > 0:
tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
if j > 0:
tile = self.blend_h(row[j - 1], tile, blend_extent)
result_row.append(tile[:, :, :, :row_limit, :row_limit])
result_rows.append(torch.cat(result_row, dim=4))
dec = torch.cat(result_rows, dim=3)
return dec
def encode(
self, z: torch.FloatTensor, return_dict: bool = True
) -> Union[DecoderOutput, torch.FloatTensor]:
if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
num_splits = z.shape[2] // self.z_sample_size
sizes = [self.z_sample_size] * num_splits
sizes = (
sizes + [z.shape[2] - sum(sizes)]
if z.shape[2] - sum(sizes) > 0
else sizes
)
tiles = z.split(sizes, dim=2)
moments_tiles = [
(
self._hw_tiled_encode(z_tile, return_dict)
if self.use_hw_tiling
else self._encode(z_tile)
)
for z_tile in tiles
]
moments = torch.cat(moments_tiles, dim=2)
else:
moments = (
self._hw_tiled_encode(z, return_dict)
if self.use_hw_tiling
else self._encode(z)
)
moments, features = moments
if self.use_ae:
return AutoencoderKLOutput(latent_dist=moments, features=features)
posterior = DiagonalGaussianDistribution(moments)
if not return_dict:
return (posterior,)
return AutoencoderKLOutput(latent_dist=posterior, features=features)
def _encode(self, x: torch.FloatTensor) -> AutoencoderKLOutput:
if torch.is_grad_enabled() and self.gradient_checkpointing:
# moments = self._gradient_checkpointing_func(self.encoder, x)
moments = self.encoder(x)
# def create_custom_forward(module, return_dict=None):
# def custom_forward(*inputs):
# if return_dict is not None:
# return module(*inputs, return_dict=return_dict)
# else:
# return module(*inputs)
#
# return custom_forward
#
# moments = torch.utils.checkpoint.checkpoint(
# create_custom_forward(self.encoder),
# x,
# )
else:
moments = self.encoder(x)
# moments = self.quant_conv(h)
return moments
def _decode(
self,
z: torch.FloatTensor,
target_shape=None,
timesteps: Optional[torch.Tensor] = None,
features: Optional[torch.Tensor] = None,
) -> Union[DecoderOutput, torch.FloatTensor]:
# z = self.post_quant_conv(z)
# if "timesteps" in self.decoder_params:
# dec = self.decoder(z, target_shape=target_shape, timesteps=timesteps)
# else:
dec = self.decoder(z, features=features) # , target_shape=target_shape
return dec
def decode(
self,
z: torch.FloatTensor,
return_dict: bool = True,
target_shape=None,
timesteps: Optional[torch.Tensor] = None,
features: Optional[torch.Tensor] = None,
) -> Union[DecoderOutput, torch.FloatTensor]:
assert target_shape is None, "target_shape not supported yet"
if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
reduction_factor = int(
self.encoder.patch_size_t
* 2
** (
len(self.encoder.down_blocks)
- 1
- math.sqrt(self.encoder.patch_size)
)
)
split_size = self.z_sample_size // reduction_factor
num_splits = z.shape[2] // split_size
# copy target shape, and divide frame dimension (=2) by the context size
target_shape_split = list(target_shape)
target_shape_split[2] = target_shape[2] // num_splits
decoded_tiles = [
(
self._hw_tiled_decode(z_tile, target_shape_split)
if self.use_hw_tiling
else self._decode(z_tile, target_shape=target_shape_split, features=features)
)
for z_tile in torch.tensor_split(z, num_splits, dim=2)
]
decoded = torch.cat(decoded_tiles, dim=2)
else:
decoded = (
self._hw_tiled_decode(z, target_shape)
if self.use_hw_tiling
else self._decode(z, target_shape=target_shape, timesteps=timesteps, features=features)
)
if self.distill_features:
decoded, features = decoded
else:
features = None
if not return_dict:
return (decoded,)
return DecoderOutput(sample=decoded, features=features)
def forward(
self,
sample: torch.FloatTensor,
sample_posterior: bool = True,
return_dict: bool = True,
generator: Optional[torch.Generator] = None,
return_training: bool = True,
return_posterior: bool = False,
drop_type: Optional[str] = "",
) -> Union[DecoderOutput, torch.FloatTensor]:
r"""
Args:
sample (`torch.FloatTensor`): Input sample.
sample_posterior (`bool`, *optional*, defaults to `False`):
Whether to sample from the posterior.
return_dict (`bool`, *optional*, defaults to `True`):
Whether to return a [`DecoderOutput`] instead of a plain tuple.
generator (`torch.Generator`, *optional*):
Generator used to sample from the posterior.
"""
x = sample
output = self.encode(x)
if self.use_ae:
z = output.latent_dist
posterior = None
features = output.features
else:
posterior = output.latent_dist
features = output.features
if return_posterior:
return posterior
if sample_posterior:
z = posterior.sample(generator=generator)
else:
z = posterior.mode()
if drop_type and self.training:
if drop_type == "dropout3d":
z = torch.nn.functional.dropout3d(z, p=0.25, training=self.training, )
elif drop_type == "ours":
z = our_drop(z)
else:
pass
recon = self.decode(z, features=features)
dec = recon.sample
out_features = recon.features
if return_training:
return (dec, posterior, z, features, out_features)
# return (dec, posterior, z)
if not return_dict:
return (dec,)
return DecoderOutput(sample=dec, features=out_features)
if __name__ == "__main__":
pass