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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 5 |
+
from diffusers.models import AutoencoderKLWan
|
| 6 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
| 8 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 9 |
+
from diffusers.video_processor import VideoProcessor
|
| 10 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 11 |
+
from diffusers.pipelines.wan.pipeline_output import WanPipelineOutput
|
| 12 |
+
|
| 13 |
+
import scipy
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from transformer_minimax_remover import Transformer3DModel
|
| 17 |
+
from einops import rearrange
|
| 18 |
+
|
| 19 |
+
if is_torch_xla_available():
|
| 20 |
+
import torch_xla.core.xla_model as xm
|
| 21 |
+
|
| 22 |
+
XLA_AVAILABLE = True
|
| 23 |
+
else:
|
| 24 |
+
XLA_AVAILABLE = False
|
| 25 |
+
|
| 26 |
+
class Minimax_Remover_Pipeline(DiffusionPipeline):
|
| 27 |
+
|
| 28 |
+
model_cpu_offload_seq = "transformer->vae"
|
| 29 |
+
_callback_tensor_inputs = ["latents"]
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
transformer: Transformer3DModel,
|
| 34 |
+
vae: AutoencoderKLWan,
|
| 35 |
+
scheduler: FlowMatchEulerDiscreteScheduler
|
| 36 |
+
):
|
| 37 |
+
super().__init__()
|
| 38 |
+
|
| 39 |
+
self.register_modules(
|
| 40 |
+
vae=vae,
|
| 41 |
+
transformer=transformer,
|
| 42 |
+
scheduler=scheduler,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
|
| 46 |
+
self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
|
| 47 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 48 |
+
|
| 49 |
+
def prepare_latents(
|
| 50 |
+
self,
|
| 51 |
+
batch_size: int,
|
| 52 |
+
num_channels_latents: 16,
|
| 53 |
+
height: int = 720,
|
| 54 |
+
width: int = 1280,
|
| 55 |
+
num_latent_frames: int = 21,
|
| 56 |
+
dtype: Optional[torch.dtype] = None,
|
| 57 |
+
device: Optional[torch.device] = None,
|
| 58 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 59 |
+
latents: Optional[torch.Tensor] = None,
|
| 60 |
+
) -> torch.Tensor:
|
| 61 |
+
if latents is not None:
|
| 62 |
+
return latents.to(device=device, dtype=dtype)
|
| 63 |
+
|
| 64 |
+
shape = (
|
| 65 |
+
batch_size,
|
| 66 |
+
num_channels_latents,
|
| 67 |
+
num_latent_frames,
|
| 68 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 69 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 73 |
+
return latents
|
| 74 |
+
|
| 75 |
+
def expand_masks(self, masks, iterations):
|
| 76 |
+
masks = masks.cpu().detach().numpy()
|
| 77 |
+
# numpy array, masks [0,1], f h w c
|
| 78 |
+
masks2 = []
|
| 79 |
+
for i in range(len(masks)):
|
| 80 |
+
mask = masks[i]
|
| 81 |
+
mask = mask > 0
|
| 82 |
+
mask = scipy.ndimage.binary_dilation(mask, iterations=iterations)
|
| 83 |
+
masks2.append(mask)
|
| 84 |
+
masks = np.array(masks2).astype(np.float32)
|
| 85 |
+
masks = torch.from_numpy(masks)
|
| 86 |
+
masks = masks.repeat(1,1,1,3)
|
| 87 |
+
masks = rearrange(masks, "f h w c -> c f h w")
|
| 88 |
+
masks = masks[None,...]
|
| 89 |
+
return masks
|
| 90 |
+
|
| 91 |
+
def resize(self, images, w, h):
|
| 92 |
+
bsz,_,_,_,_ = images.shape
|
| 93 |
+
images = rearrange(images, "b c f w h -> (b f) c w h")
|
| 94 |
+
images = F.interpolate(images, (w,h), mode='bilinear')
|
| 95 |
+
images = rearrange(images, "(b f) c w h -> b c f w h", b=bsz)
|
| 96 |
+
return images
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def num_timesteps(self):
|
| 100 |
+
return self._num_timesteps
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def current_timestep(self):
|
| 104 |
+
return self._current_timestep
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def interrupt(self):
|
| 108 |
+
return self._interrupt
|
| 109 |
+
|
| 110 |
+
@torch.no_grad()
|
| 111 |
+
def __call__(
|
| 112 |
+
self,
|
| 113 |
+
height: int = 720,
|
| 114 |
+
width: int = 1280,
|
| 115 |
+
num_frames: int = 81,
|
| 116 |
+
num_inference_steps: int = 50,
|
| 117 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 118 |
+
images: Optional[torch.Tensor] = None,
|
| 119 |
+
masks: Optional[torch.Tensor] = None,
|
| 120 |
+
latents: Optional[torch.Tensor] = None,
|
| 121 |
+
output_type: Optional[str] = "np",
|
| 122 |
+
iterations: int = 16
|
| 123 |
+
):
|
| 124 |
+
|
| 125 |
+
self._current_timestep = None
|
| 126 |
+
self._interrupt = False
|
| 127 |
+
device = self._execution_device
|
| 128 |
+
batch_size = 1
|
| 129 |
+
transformer_dtype = torch.float16
|
| 130 |
+
|
| 131 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 132 |
+
timesteps = self.scheduler.timesteps
|
| 133 |
+
|
| 134 |
+
num_channels_latents = 16
|
| 135 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 136 |
+
|
| 137 |
+
latents = self.prepare_latents(
|
| 138 |
+
batch_size,
|
| 139 |
+
num_channels_latents,
|
| 140 |
+
height,
|
| 141 |
+
width,
|
| 142 |
+
num_latent_frames,
|
| 143 |
+
torch.float16,
|
| 144 |
+
device,
|
| 145 |
+
generator,
|
| 146 |
+
latents,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
masks = self.expand_masks(masks, iterations)
|
| 150 |
+
masks = self.resize(masks, height, width).to("cuda:0").half()
|
| 151 |
+
masks[masks>0] = 1
|
| 152 |
+
images = rearrange(images, "f h w c -> c f h w")
|
| 153 |
+
images = self.resize(images[None,...], height, width).to("cuda:0").half()
|
| 154 |
+
|
| 155 |
+
masked_images = images * (1-masks)
|
| 156 |
+
|
| 157 |
+
latents_mean = (
|
| 158 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 159 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 160 |
+
.to(self.vae.device, torch.float16)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 164 |
+
self.vae.device, torch.float16
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
with torch.no_grad():
|
| 168 |
+
masked_latents = self.vae.encode(masked_images.half()).latent_dist.mode()
|
| 169 |
+
masks_latents = self.vae.encode(2*masks.half()-1.0).latent_dist.mode()
|
| 170 |
+
|
| 171 |
+
masked_latents = (masked_latents - latents_mean) * latents_std
|
| 172 |
+
masks_latents = (masks_latents - latents_mean) * latents_std
|
| 173 |
+
|
| 174 |
+
self._num_timesteps = len(timesteps)
|
| 175 |
+
|
| 176 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 177 |
+
for i, t in enumerate(timesteps):
|
| 178 |
+
|
| 179 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 180 |
+
|
| 181 |
+
latent_model_input = torch.cat([latent_model_input, masked_latents, masks_latents], dim=1)
|
| 182 |
+
timestep = t.expand(latents.shape[0])
|
| 183 |
+
|
| 184 |
+
noise_pred = self.transformer(
|
| 185 |
+
hidden_states=latent_model_input.half(),
|
| 186 |
+
timestep=timestep
|
| 187 |
+
)[0]
|
| 188 |
+
|
| 189 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 190 |
+
|
| 191 |
+
progress_bar.update()
|
| 192 |
+
|
| 193 |
+
latents = latents.half() / latents_std + latents_mean
|
| 194 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
| 195 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
| 196 |
+
|
| 197 |
+
return WanPipelineOutput(frames=video)
|
test_minimax_remover.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import argparse
|
| 3 |
+
import numpy as np
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
from diffusers.utils import export_to_video
|
| 10 |
+
from omegaconf import OmegaConf
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from decord import VideoReader
|
| 13 |
+
from diffusers.models import AutoencoderKLWan
|
| 14 |
+
import scipy
|
| 15 |
+
from transformer_minimax_remover import Transformer3DModel
|
| 16 |
+
from einops import rearrange
|
| 17 |
+
from diffusers.schedulers import UniPCMultistepScheduler
|
| 18 |
+
from pipeline_minimax_remover import Minimax_Remover_Pipeline
|
| 19 |
+
|
| 20 |
+
random_seed = 42
|
| 21 |
+
video_length = 81
|
| 22 |
+
device = torch.device("cuda:0")
|
| 23 |
+
|
| 24 |
+
vae = AutoencoderKLWan.from_pretrained("./vae", torch_dtype=torch.float16)
|
| 25 |
+
transformer = Transformer3DModel.from_pretrained("./transformer", torch_dtype=torch.float16)
|
| 26 |
+
scheduler = UniPCMultistepScheduler.from_pretrained("./scheduler")
|
| 27 |
+
|
| 28 |
+
pipe = Minimax_Remover_Pipeline(transformer=transformer, vae=vae, scheduler=scheduler)
|
| 29 |
+
pipe.to("cuda:0")
|
| 30 |
+
|
| 31 |
+
def inference(pixel_values, masks, iterations=6):
|
| 32 |
+
video = pipe(
|
| 33 |
+
images=pixel_values,
|
| 34 |
+
masks=masks,
|
| 35 |
+
num_frames=video_length,
|
| 36 |
+
height=480,
|
| 37 |
+
width=832,
|
| 38 |
+
num_inference_steps=12,
|
| 39 |
+
generator=torch.Generator(device="cuda").manual_seed(random_seed),
|
| 40 |
+
iterations=iterations
|
| 41 |
+
).frames[0]
|
| 42 |
+
|
| 43 |
+
export_to_video(video, f"./output.mp4")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_video(video_path):
|
| 47 |
+
vr = VideoReader(video_path)
|
| 48 |
+
images = vr.get_batch(list(range(video_length))).asnumpy()
|
| 49 |
+
images = torch.from_numpy(images)/127.5 - 1.0
|
| 50 |
+
return images
|
| 51 |
+
|
| 52 |
+
def load_mask(mask_path):
|
| 53 |
+
vr = VideoReader(mask_path)
|
| 54 |
+
masks = vr.get_batch(list(range(video_length))).asnumpy()
|
| 55 |
+
masks = torch.from_numpy(masks)
|
| 56 |
+
masks = masks[:,:,:,:1]
|
| 57 |
+
masks[masks>20] = 255
|
| 58 |
+
masks[masks<255] = 0
|
| 59 |
+
masks = masks/255.0
|
| 60 |
+
return masks
|
| 61 |
+
|
| 62 |
+
#video_path = "../pexels_export/height/5720258-hd_1080_1920_24fps.mp4"
|
| 63 |
+
video_path = "../pexels_export/fast/3352673-hd_1280_720_30fps.mp4"
|
| 64 |
+
#mask_path = "../pexels_export/height/5720258-hd_1080_1920_24fps_mask.mp4"
|
| 65 |
+
mask_path = "../pexels_export/fast/3352673-hd_1280_720_30fps_mask.mp4"
|
| 66 |
+
|
| 67 |
+
images = load_video(video_path)
|
| 68 |
+
masks = load_mask(mask_path)
|
| 69 |
+
|
| 70 |
+
inference(images, masks)
|
transformer_minimax_remover.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Dict, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 9 |
+
from diffusers.utils import logging
|
| 10 |
+
from diffusers.models.attention import FeedForward
|
| 11 |
+
from diffusers.models.attention_processor import Attention
|
| 12 |
+
from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
|
| 13 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 14 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 15 |
+
from diffusers.models.normalization import FP32LayerNorm
|
| 16 |
+
|
| 17 |
+
class AttnProcessor2_0:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 20 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
|
| 21 |
+
|
| 22 |
+
def __call__(
|
| 23 |
+
self,
|
| 24 |
+
attn: Attention,
|
| 25 |
+
hidden_states: torch.Tensor,
|
| 26 |
+
rotary_emb: Optional[torch.Tensor] = None,
|
| 27 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 28 |
+
encoder_hidden_states: Optional[torch.Tensor] = None
|
| 29 |
+
) -> torch.Tensor:
|
| 30 |
+
|
| 31 |
+
encoder_hidden_states = hidden_states
|
| 32 |
+
query = attn.to_q(hidden_states)
|
| 33 |
+
key = attn.to_k(encoder_hidden_states)
|
| 34 |
+
value = attn.to_v(encoder_hidden_states)
|
| 35 |
+
|
| 36 |
+
if attn.norm_q is not None:
|
| 37 |
+
query = attn.norm_q(query)
|
| 38 |
+
if attn.norm_k is not None:
|
| 39 |
+
key = attn.norm_k(key)
|
| 40 |
+
|
| 41 |
+
query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
| 42 |
+
key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
| 43 |
+
value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
| 44 |
+
|
| 45 |
+
if rotary_emb is not None:
|
| 46 |
+
|
| 47 |
+
def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
|
| 48 |
+
x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
|
| 49 |
+
x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
|
| 50 |
+
return x_out.type_as(hidden_states)
|
| 51 |
+
|
| 52 |
+
query = apply_rotary_emb(query, rotary_emb)
|
| 53 |
+
key = apply_rotary_emb(key, rotary_emb)
|
| 54 |
+
|
| 55 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 56 |
+
query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False
|
| 57 |
+
)
|
| 58 |
+
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
|
| 59 |
+
hidden_states = hidden_states.type_as(query)
|
| 60 |
+
|
| 61 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 62 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 63 |
+
return hidden_states
|
| 64 |
+
|
| 65 |
+
class TimeEmbedding(nn.Module):
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
dim: int,
|
| 69 |
+
time_freq_dim: int,
|
| 70 |
+
time_proj_dim: int
|
| 71 |
+
):
|
| 72 |
+
super().__init__()
|
| 73 |
+
|
| 74 |
+
self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 75 |
+
self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
|
| 76 |
+
|
| 77 |
+
self.act_fn = nn.SiLU()
|
| 78 |
+
self.time_proj = nn.Linear(dim, time_proj_dim)
|
| 79 |
+
|
| 80 |
+
def forward(
|
| 81 |
+
self,
|
| 82 |
+
timestep: torch.Tensor,
|
| 83 |
+
):
|
| 84 |
+
timestep = self.timesteps_proj(timestep)
|
| 85 |
+
|
| 86 |
+
time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
|
| 87 |
+
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 88 |
+
timestep = timestep.to(time_embedder_dtype)
|
| 89 |
+
temb = self.time_embedder(timestep).type_as(self.time_proj.weight.data)
|
| 90 |
+
timestep_proj = self.time_proj(self.act_fn(temb))
|
| 91 |
+
|
| 92 |
+
return temb, timestep_proj
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class RotaryPosEmbed(nn.Module):
|
| 96 |
+
def __init__(
|
| 97 |
+
self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
|
| 98 |
+
):
|
| 99 |
+
super().__init__()
|
| 100 |
+
|
| 101 |
+
self.attention_head_dim = attention_head_dim
|
| 102 |
+
self.patch_size = patch_size
|
| 103 |
+
self.max_seq_len = max_seq_len
|
| 104 |
+
|
| 105 |
+
h_dim = w_dim = 2 * (attention_head_dim // 6)
|
| 106 |
+
t_dim = attention_head_dim - h_dim - w_dim
|
| 107 |
+
|
| 108 |
+
freqs = []
|
| 109 |
+
for dim in [t_dim, h_dim, w_dim]:
|
| 110 |
+
freq = get_1d_rotary_pos_embed(
|
| 111 |
+
dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
|
| 112 |
+
)
|
| 113 |
+
freqs.append(freq)
|
| 114 |
+
self.freqs = torch.cat(freqs, dim=1)
|
| 115 |
+
|
| 116 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 117 |
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
| 118 |
+
p_t, p_h, p_w = self.patch_size
|
| 119 |
+
ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
|
| 120 |
+
|
| 121 |
+
self.freqs = self.freqs.to(hidden_states.device)
|
| 122 |
+
freqs = self.freqs.split_with_sizes(
|
| 123 |
+
[
|
| 124 |
+
self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
|
| 125 |
+
self.attention_head_dim // 6,
|
| 126 |
+
self.attention_head_dim // 6,
|
| 127 |
+
],
|
| 128 |
+
dim=1,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
|
| 132 |
+
freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
|
| 133 |
+
freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
|
| 134 |
+
freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
|
| 135 |
+
return freqs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TransformerBlock(nn.Module):
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
dim: int,
|
| 142 |
+
ffn_dim: int,
|
| 143 |
+
num_heads: int,
|
| 144 |
+
qk_norm: str = "rms_norm_across_heads",
|
| 145 |
+
cross_attn_norm: bool = False,
|
| 146 |
+
eps: float = 1e-6,
|
| 147 |
+
added_kv_proj_dim: Optional[int] = None,
|
| 148 |
+
):
|
| 149 |
+
super().__init__()
|
| 150 |
+
|
| 151 |
+
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 152 |
+
self.attn1 = Attention(
|
| 153 |
+
query_dim=dim,
|
| 154 |
+
heads=num_heads,
|
| 155 |
+
kv_heads=num_heads,
|
| 156 |
+
dim_head=dim // num_heads,
|
| 157 |
+
qk_norm=qk_norm,
|
| 158 |
+
eps=eps,
|
| 159 |
+
bias=True,
|
| 160 |
+
cross_attention_dim=None,
|
| 161 |
+
out_bias=True,
|
| 162 |
+
processor=AttnProcessor2_0(),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
|
| 166 |
+
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 167 |
+
|
| 168 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
| 169 |
+
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
hidden_states: torch.Tensor,
|
| 173 |
+
temb: torch.Tensor,
|
| 174 |
+
rotary_emb: torch.Tensor,
|
| 175 |
+
) -> torch.Tensor:
|
| 176 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 177 |
+
self.scale_shift_table + temb.float()
|
| 178 |
+
).chunk(6, dim=1)
|
| 179 |
+
|
| 180 |
+
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
| 181 |
+
attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
|
| 182 |
+
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
| 183 |
+
|
| 184 |
+
norm_hidden_states = (self.norm2(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
| 185 |
+
hidden_states
|
| 186 |
+
)
|
| 187 |
+
ff_output = self.ffn(norm_hidden_states)
|
| 188 |
+
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
| 189 |
+
|
| 190 |
+
return hidden_states
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class Transformer3DModel(ModelMixin, ConfigMixin):
|
| 194 |
+
|
| 195 |
+
_skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
|
| 196 |
+
_no_split_modules = ["TransformerBlock"]
|
| 197 |
+
_keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2"]
|
| 198 |
+
|
| 199 |
+
@register_to_config
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
patch_size: Tuple[int] = (1, 2, 2),
|
| 203 |
+
num_attention_heads: int = 40,
|
| 204 |
+
attention_head_dim: int = 128,
|
| 205 |
+
in_channels: int = 16,
|
| 206 |
+
out_channels: int = 16,
|
| 207 |
+
freq_dim: int = 256,
|
| 208 |
+
ffn_dim: int = 13824,
|
| 209 |
+
num_layers: int = 40,
|
| 210 |
+
cross_attn_norm: bool = True,
|
| 211 |
+
qk_norm: Optional[str] = "rms_norm_across_heads",
|
| 212 |
+
eps: float = 1e-6,
|
| 213 |
+
added_kv_proj_dim: Optional[int] = None,
|
| 214 |
+
rope_max_seq_len: int = 1024
|
| 215 |
+
) -> None:
|
| 216 |
+
super().__init__()
|
| 217 |
+
|
| 218 |
+
inner_dim = num_attention_heads * attention_head_dim
|
| 219 |
+
out_channels = out_channels or in_channels
|
| 220 |
+
|
| 221 |
+
# 1. Patch & position embedding
|
| 222 |
+
self.rope = RotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
|
| 223 |
+
self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 224 |
+
|
| 225 |
+
# 2. Condition embeddings
|
| 226 |
+
self.condition_embedder = TimeEmbedding(
|
| 227 |
+
dim=inner_dim,
|
| 228 |
+
time_freq_dim=freq_dim,
|
| 229 |
+
time_proj_dim=inner_dim * 6,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# 3. Transformer blocks
|
| 233 |
+
self.blocks = nn.ModuleList(
|
| 234 |
+
[
|
| 235 |
+
TransformerBlock(
|
| 236 |
+
inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
|
| 237 |
+
)
|
| 238 |
+
for _ in range(num_layers)
|
| 239 |
+
]
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# 4. Output norm & projection
|
| 243 |
+
self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
|
| 244 |
+
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
| 245 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
|
| 246 |
+
|
| 247 |
+
def forward(
|
| 248 |
+
self,
|
| 249 |
+
hidden_states: torch.Tensor,
|
| 250 |
+
timestep: torch.LongTensor
|
| 251 |
+
) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 252 |
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
| 253 |
+
p_t, p_h, p_w = self.config.patch_size
|
| 254 |
+
post_patch_num_frames = num_frames // p_t
|
| 255 |
+
post_patch_height = height // p_h
|
| 256 |
+
post_patch_width = width // p_w
|
| 257 |
+
|
| 258 |
+
rotary_emb = self.rope(hidden_states)
|
| 259 |
+
|
| 260 |
+
hidden_states = self.patch_embedding(hidden_states)
|
| 261 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 262 |
+
|
| 263 |
+
temb, timestep_proj = self.condition_embedder(
|
| 264 |
+
timestep
|
| 265 |
+
)
|
| 266 |
+
timestep_proj = timestep_proj.unflatten(1, (6, -1))
|
| 267 |
+
|
| 268 |
+
for block in self.blocks:
|
| 269 |
+
hidden_states = block(hidden_states, timestep_proj, rotary_emb)
|
| 270 |
+
|
| 271 |
+
shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
|
| 272 |
+
hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 273 |
+
hidden_states = self.proj_out(hidden_states)
|
| 274 |
+
|
| 275 |
+
hidden_states = hidden_states.reshape(
|
| 276 |
+
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
| 277 |
+
)
|
| 278 |
+
hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 279 |
+
output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 280 |
+
|
| 281 |
+
return Transformer2DModelOutput(sample=output)
|