Open-Sora: Democratizing Efficient Video Production for All
Python
[feature] impl adaln model arch
ver2170106e6255575
diff --git a/open_sora/modeling/dit/__init__.py b/open_sora/modeling/dit/__init__.pyindex c13a0b3..73813b5 100644--- a/open_sora/modeling/dit/__init__.py+++ b/open_sora/modeling/dit/__init__.py@@ -1,3 +1,3 @@-from .dit import SUPPORTED_SEQ_PARALLEL_MODES, DiT, DiT_models+from .dit import SUPPORTED_MODEL_ARCH, SUPPORTED_SEQ_PARALLEL_MODES, DiT, DiT_models-__all__ = ["DiT_models", "DiT", "SUPPORTED_SEQ_PARALLEL_MODES"]+__all__ = ["DiT_models", "DiT", "SUPPORTED_SEQ_PARALLEL_MODES", "SUPPORTED_MODEL_ARCH"]diff --git a/open_sora/modeling/dit/dit.py b/open_sora/modeling/dit/dit.pyindex 93e1271..6b7bd00 100644--- a/open_sora/modeling/dit/dit.py+++ b/open_sora/modeling/dit/dit.py@@ -21,9 +21,14 @@ from timm.models.vision_transformer import Mlpfrom open_sora.utils.comm import gather_seq, split_seq-from .attn import CrossAttention, FastSeqParallelCrossAttention, SeqParallelCrossAttention+from .attn import (+ CrossAttention,+ FastSeqParallelCrossAttention,+ SeqParallelCrossAttention,+)SUPPORTED_SEQ_PARALLEL_MODES = ["ulysses", "fastseq"]+SUPPORTED_MODEL_ARCH = ["adaln", "cross-attn", "token-concat"]def modulate(x, shift, scale):@@ -61,17 +66,23 @@ class TimestepEmbedder(nn.Module):"""# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.pyhalf = dim // 2- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(- device=t.device- )+ freqs = torch.exp(+ -math.log(max_period)+ * torch.arange(start=0, end=half, dtype=torch.float32)+ / half+ ).to(device=t.device)args = t[:, None].float() * freqs[None]embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)if dim % 2:- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)+ embedding = torch.cat(+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1+ )return embeddingdef forward(self, t):- t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(self.mlp[0].weight.dtype)+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(+ self.mlp[0].weight.dtype+ )t_emb = self.mlp(t_freq)return t_emb@@ -84,7 +95,9 @@ class LabelEmbedder(nn.Module):def __init__(self, num_classes, hidden_size, dropout_prob):super().__init__()use_cfg_embedding = dropout_prob > 0- self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)+ self.embedding_table = nn.Embedding(+ num_classes + use_cfg_embedding, hidden_size+ )self.num_classes = num_classesself.dropout_prob = dropout_prob@@ -93,7 +106,9 @@ class LabelEmbedder(nn.Module):Drops labels to enable classifier-free guidance."""if force_drop_ids is None:- drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob+ drop_ids = (+ torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob+ )else:drop_ids = force_drop_ids == 1labels = torch.where(drop_ids, self.num_classes, labels)@@ -120,13 +135,17 @@ class PatchEmbedder(nn.Module):) -> None:super().__init__()self.patch_size = patch_size- self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)+ self.proj = nn.Conv2d(+ in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias+ )self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()def forward(self, x: torch.Tensor) -> torch.Tensor:# [B, S, C, P, P] -> [B, S, C*P*P]x = x.view(*x.shape[:2], -1)- out = F.linear(x, self.proj.weight.view(self.proj.weight.shape[0], -1), self.proj.bias)+ out = F.linear(+ x, self.proj.weight.view(self.proj.weight.shape[0], -1), self.proj.bias+ )out = self.norm(out)# [B, S, H]return out@@ -148,7 +167,10 @@ class TextEmbedder(nn.Module):self.proj = nn.Linear(in_features, embed_dim, bias=bias)def drop_sample(self, x: torch.Tensor) -> torch.Tensor:- drop_ids = torch.rand(x.shape[0], 1, 1, device=x.device) < self.dropout_prob+ drop_ids = (+ torch.rand(x.shape[0], *([1] * (x.ndim - 1)), device=x.device)+ < self.dropout_prob+ )x = torch.where(drop_ids, torch.zeros_like(x), x)return x@@ -216,7 +238,9 @@ class DiTBlock(nn.Module):attn_cls = FastSeqParallelCrossAttentionattn_kwargs["overlap"] = seq_parallel_overlapelse:- raise ValueError(f"seq_parallel_mode must be one of {SUPPORTED_SEQ_PARALLEL_MODES}")+ raise ValueError(+ f"seq_parallel_mode must be one of {SUPPORTED_SEQ_PARALLEL_MODES}"+ )else:attn_cls = CrossAttentionself.attn = attn_cls(@@ -244,14 +268,20 @@ class DiTBlock(nn.Module):act_layer=approx_gelu,drop=0,)- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True)+ )def forward(self, x, attention_mask, t, context=None):- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(t).chunk(6, dim=1)+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (+ self.adaLN_modulation(t).chunk(6, dim=1)+ )x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), context, attention_mask)- x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))+ x = x + gate_mlp.unsqueeze(1) * self.mlp(+ modulate(self.norm2(x), shift_mlp, scale_mlp)+ )return x@@ -263,9 +293,13 @@ class FinalLayer(nn.Module):def __init__(self, hidden_size, patch_size, out_channels):super().__init__()self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)- self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)+ self.linear = nn.Linear(+ hidden_size, patch_size * patch_size * out_channels, bias=True+ )self.patch_size = patch_size- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True)+ )def unpatchify(self, x):b, s, h = x.shape@@ -296,12 +330,14 @@ class DiT(nn.Module):max_num_embeddings=256 * 1024,text_dropout_prob=0.1,learn_sigma=True,- use_cross_attn=True,seq_parallel_group=None,seq_parallel_mode="ulysses",seq_parallel_overlap=False,+ model_arch="cross-attn",):super().__init__()+ assert model_arch in SUPPORTED_MODEL_ARCH+ self.model_arch = model_archself.grad_checkpointing = Falseself.learn_sigma = learn_sigmaself.in_channels = in_channels@@ -309,10 +345,20 @@ class DiT(nn.Module):self.patch_size = patch_sizeself.num_heads = num_headsself.seq_parallel_group = seq_parallel_group- self.seq_parallel_size = dist.get_world_size(self.seq_parallel_group) if seq_parallel_group is not None else 1- self.seq_parallel_rank = dist.get_rank(self.seq_parallel_group) if seq_parallel_group is not None else 0+ self.seq_parallel_size = (+ dist.get_world_size(self.seq_parallel_group)+ if seq_parallel_group is not None+ else 1+ )+ self.seq_parallel_rank = (+ dist.get_rank(self.seq_parallel_group)+ if seq_parallel_group is not None+ else 0+ )- self.video_embedder = PatchEmbedder(patch_size, in_channels, hidden_size, bias=True)+ self.video_embedder = PatchEmbedder(+ patch_size, in_channels, hidden_size, bias=True+ )self.t_embedder = TimestepEmbedder(hidden_size)self.pos_embed = PositionEmbedding(hidden_size, max_num_embeddings)self.text_embedder = TextEmbedder(@@ -320,13 +366,12 @@ class DiT(nn.Module):hidden_size,bias=True,dropout_prob=text_dropout_prob,- use_proj=not use_cross_attn,+ use_proj=model_arch != "cross-attn",)- if not use_cross_attn:+ if model_arch != "cross-attn":cross_attn_dim = Noneelse:cross_attn_dim = text_embed_dim- self.use_cross_attn = use_cross_attnself.blocks = nn.ModuleList([@@ -379,7 +424,9 @@ class DiT(nn.Module):assert attention_mask.ndim == 4attention_mask = attention_mask.to(dtype)inverted_mask = 1.0 - attention_mask- return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)+ return inverted_mask.masked_fill(+ inverted_mask.to(torch.bool), torch.finfo(dtype).min+ )return attention_maskdef enable_gradient_checkpointing(self):@@ -397,24 +444,36 @@ class DiT(nn.Module):):"""video_latent_states: [B, S, C, P, P]+ t: [B]+ text_latent_states: [B, H] if model_arch == "adaln" else [B, S, H]+ attention_mask: [B, 1, Sv, St] or [B, 1, Sv, Sv]"""video_latent_states = self.video_embedder(video_latent_states)text_len = text_latent_states.shape[1]text_latent_states = self.text_embedder(text_latent_states)- if not self.use_cross_attn:- video_latent_states = torch.cat([text_latent_states, video_latent_states], dim=1)+ if self.model_arch == "token-concat":+ video_latent_states = torch.cat(+ [text_latent_states, video_latent_states], dim=1+ )text_latent_states = Nonepos_embed = self.pos_embed(video_latent_states)video_latent_states = video_latent_states + pos_embedt = self.t_embedder(t) # (N, D)+ if self.model_arch == "adaln":+ t = t + text_latent_states+ text_latent_states = Noneattention_mask = self._prepare_mask(attention_mask, video_latent_states.dtype)if self.seq_parallel_group is not None and self.seq_parallel_size > 1:assert video_latent_states.shape[1] % self.seq_parallel_size == 0- video_latent_states = split_seq(video_latent_states, self.seq_parallel_size, self.seq_parallel_rank)+ video_latent_states = split_seq(+ video_latent_states, self.seq_parallel_size, self.seq_parallel_rank+ )if text_latent_states is not None:assert text_latent_states.shape[1] % self.seq_parallel_size == 0- text_latent_states = split_seq(text_latent_states, self.seq_parallel_size, self.seq_parallel_rank)+ text_latent_states = split_seq(+ text_latent_states, self.seq_parallel_size, self.seq_parallel_rank+ )for block in self.blocks:if self.grad_checkpointing and self.training:@@ -426,7 +485,9 @@ class DiT(nn.Module):text_latent_states,)else:- video_latent_states = block(video_latent_states, attention_mask, t, text_latent_states)+ video_latent_states = block(+ video_latent_states, attention_mask, t, text_latent_states+ )if self.seq_parallel_group is not None and self.seq_parallel_size > 1:video_latent_states = gather_seq(@@ -436,19 +497,23 @@ class DiT(nn.Module):self.seq_parallel_group,)- if not self.use_cross_attn:+ if self.model_arch == "token-concat":video_latent_states = video_latent_states[:, text_len:]video_latent_states = self.final_layer(video_latent_states, t)return video_latent_states- def forward_with_cfg(self, x, t, text_latent_states, cfg_scale, attention_mask=None):+ def forward_with_cfg(+ self, x, t, text_latent_states, cfg_scale, attention_mask=None+ ):"""Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance."""# https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynbhalf = x[: len(x) // 2]combined = torch.cat([half, half], dim=0)- model_out = self.forward(combined, t, text_latent_states, attention_mask=attention_mask)+ model_out = self.forward(+ combined, t, text_latent_states, attention_mask=attention_mask+ )# For exact reproducibility reasons, we apply classifier-free guidance on only# three channels by default. The standard approach to cfg applies it to all channels.# This can be done by uncommenting the following line and commenting-out the line following that.@@ -487,7 +552,9 @@ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=grid = grid.reshape([2, 1, grid_size, grid_size])pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)if cls_token and extra_tokens > 0:- pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)+ pos_embed = np.concatenate(+ [np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0+ )return pos_embeddiff --git a/open_sora/utils/data.py b/open_sora/utils/data.pyindex 99ad63c..a68b760 100644--- a/open_sora/utils/data.py+++ b/open_sora/utils/data.py@@ -139,7 +139,10 @@ def expand_mask_4d(q_mask: torch.Tensor, kv_mask: torch.Tensor) -> torch.Tensor:def make_batch(- samples: List[dict], video_dir: str, pad_to_multiple: Optional[int] = None+ samples: List[dict],+ video_dir: str,+ pad_to_multiple: Optional[int] = None,+ use_pooled_text: bool = False,) -> dict:"""Make a batch of samples.@@ -154,6 +157,12 @@ def make_batch(for sample in samples]texts = [sample["text_latent_states"] for sample in samples]+ if use_pooled_text:+ texts = torch.stack(texts, dim=0)+ return {+ "videos": videos,+ "text_latent_states": texts,+ }texts, text_padding_mask = pad_sequences(texts, pad_to_multiple=pad_to_multiple)return {"videos": videos,@@ -281,8 +290,8 @@ def preprocess_batch(patch_size: int,video_compressor: VideoCompressor,device=None,- use_cross_attn=True,pad_to_multiple: Optional[int] = None,+ model_arch: str = "cross-attn",) -> dict:if device is None:device = get_current_device()@@ -297,12 +306,17 @@ def preprocess_batch()batch["video_latent_states"] = video_latent_statesbatch["video_padding_mask"] = video_padding_mask- text_padding_mask = batch.pop("text_padding_mask").to(device)- if use_cross_attn:- batch["attention_mask"] = expand_mask_4d(video_padding_mask, text_padding_mask)+ if model_arch == "adaln":+ batch["attention_mask"] = expand_mask_4d(video_padding_mask, video_padding_mask)else:- attention_mask = torch.cat([text_padding_mask, video_padding_mask], dim=1)- batch["attention_mask"] = expand_mask_4d(attention_mask, attention_mask)+ text_padding_mask = batch.pop("text_padding_mask").to(device)+ if model_arch == "cross-attn":+ batch["attention_mask"] = expand_mask_4d(+ video_padding_mask, text_padding_mask+ )+ else:+ attention_mask = torch.cat([text_padding_mask, video_padding_mask], dim=1)+ batch["attention_mask"] = expand_mask_4d(attention_mask, attention_mask)batch["text_latent_states"] = batch["text_latent_states"].to(device)return batchdiff --git a/sample.py b/sample.pyindex 5acd53a..67aec4b 100644--- a/sample.py+++ b/sample.py@@ -19,6 +19,7 @@ from transformers import AutoTokenizer, CLIPTextModelfrom open_sora.diffusion import create_diffusionfrom open_sora.modeling import DiT_models+from open_sora.modeling.dit import SUPPORTED_MODEL_ARCHfrom open_sora.utils.data import col2video, create_video_compressor, unnormalize_video@@ -29,7 +30,10 @@ def main(args):device = get_current_device()video_compressor = create_video_compressor(args.compressor)- model_kwargs = {"in_channels": video_compressor.out_channels}+ model_kwargs = {+ "in_channels": video_compressor.out_channels,+ "model_arch": args.model_arch,+ }text_model = CLIPTextModel.from_pretrained(args.text_model).to(device).eval()tokenizer = AutoTokenizer.from_pretrained(args.text_model)@@ -42,7 +46,11 @@ def main(args):# Create sampling noise:text_inputs = tokenizer(args.text, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}- text_latent_states = text_model(**text_inputs).last_hidden_state+ text_latent_states = text_model(**text_inputs)+ if args.model_arch == "adaln":+ text_latent_states = text_latent_states.pooler_output+ else:+ text_latent_states = text_latent_states.last_hidden_statenum_frames = args.fps * args.secz = torch.randn(@@ -66,11 +74,14 @@ def main(args):model_kwargs["cfg_scale"] = args.cfg_scaleelse:model_kwargs["text_latent_states"] = text_latent_states+ context_len = (+ text_latent_states.shape[1] if args.model_arch == "cross-attn" else z.shape[1]+ )model_kwargs["attention_mask"] = torch.ones(z.shape[0],1,z.shape[1],- text_latent_states.shape[1],+ context_len,device=device,dtype=torch.int,)@@ -107,6 +118,9 @@ if __name__ == "__main__":parser.add_argument("-m", "--model", type=str, choices=list(DiT_models.keys()), default="DiT-S/8")+ parser.add_argument(+ "-x", "--model_arch", choices=SUPPORTED_MODEL_ARCH, default="cross-attn"+ )parser.add_argument("--text",type=str,diff --git a/scripts/data/preprocess_data.py b/scripts/data/preprocess_data.pyindex a781876..bc0dfbb 100644--- a/scripts/data/preprocess_data.py+++ b/scripts/data/preprocess_data.py@@ -1,5 +1,4 @@import argparse-import ioimport mathimport os@@ -8,13 +7,15 @@ from datasets import load_datasetfrom torchvision.io import read_videofrom transformers import AutoTokenizer, CLIPTextModel-EMPTY_SAMPLE = {"video_file": [], "video_latent_states": [], "text_latent_states": []}+EMPTY_SAMPLE = {"video_file": [], "text_latent_states": []}-def process_text(text, tokenizer, text_model):+def process_text(text, tokenizer, text_model, use_pooled_text):inputs = tokenizer(text, padding=True, return_tensors="pt")inputs = {k: v.cuda() for k, v in inputs.items()}outputs = text_model(**inputs)+ if use_pooled_text:+ return list(outputs.pooler_output.cpu().unbind(0))output_states = []for i, x in enumerate(outputs.last_hidden_state):valid_x = x[inputs["attention_mask"][i].bool()]@@ -23,12 +24,14 @@ def process_text(text, tokenizer, text_model):@torch.no_grad()-def process_item(item, video_dir, tokenizer, text_model):+def process_item(item, video_dir, tokenizer, text_model, use_pooled_text):video_path = os.path.join(video_dir, item["file"])video = read_video(video_path, pts_unit="sec")[0]if video.size(0) > 600:return EMPTY_SAMPLE- text_latent_states = process_text(item["captions"], tokenizer, text_model)+ text_latent_states = process_text(+ item["captions"], tokenizer, text_model, use_pooled_text+ )torch.cuda.empty_cache()return {"video_file": [item["file"]] * len(text_latent_states),@@ -36,9 +39,9 @@ def process_item(item, video_dir, tokenizer, text_model):}-def process_batch(batch, video_dir, tokenizer, text_model):+def process_batch(batch, video_dir, tokenizer, text_model, use_pooled_text):item = {"file": batch["file"][0], "captions": batch["captions"][0]}- return process_item(item, video_dir, tokenizer, text_model)+ return process_item(item, video_dir, tokenizer, text_model, use_pooled_text)def process_dataset(@@ -47,6 +50,7 @@ def process_dataset(output_dir,num_spliced_dataset_bins=10,text_model="openai/clip-vit-base-patch32",+ use_pooled_text=False,):tokenizer = AutoTokenizer.from_pretrained(text_model)text_model = CLIPTextModel.from_pretrained(text_model).cuda().eval()@@ -81,6 +85,7 @@ def process_dataset("video_dir": video_dir,"tokenizer": tokenizer,"text_model": text_model,+ "use_pooled_text": use_pooled_text,},batched=True,batch_size=1,@@ -118,6 +123,7 @@ if __name__ == "__main__":default="openai/clip-vit-base-patch32",help="CLIP text model",)+ parser.add_argument("--use_pooled_text", action="store_true", default=False)args = parser.parse_args()process_dataset(args.captions_file,@@ -125,4 +131,5 @@ if __name__ == "__main__":args.output_dir,args.num_spliced_dataset_bins,args.text_model,+ args.use_pooled_text,)diff --git a/train.py b/train.pyindex 22a372f..2d48f63 100644--- a/train.py+++ b/train.py@@ -26,7 +26,7 @@ from tqdm import tqdmfrom open_sora.diffusion import create_diffusionfrom open_sora.modeling import DiT_models-from open_sora.modeling.dit import SUPPORTED_SEQ_PARALLEL_MODES+from open_sora.modeling.dit import SUPPORTED_MODEL_ARCH, SUPPORTED_SEQ_PARALLEL_MODESfrom open_sora.utils.data import (create_video_compressor,load_datasets,@@ -113,6 +113,7 @@ def main(args):"seq_parallel_group": plugin.sp_group,"seq_parallel_mode": args.sp_mode,"seq_parallel_overlap": args.sp_overlap,+ "model_arch": args.model_arch,}# Step 4: Create DiT and EMA@@ -143,7 +144,10 @@ def main(args):dataset,batch_size=args.batch_size,collate_fn=partial(- make_batch, video_dir=args.video_dir, pad_to_multiple=args.sp_size+ make_batch,+ video_dir=args.video_dir,+ pad_to_multiple=args.sp_size,+ use_pooled_text=args.model_arch == "adaln",),shuffle=True,drop_last=True,@@ -179,7 +183,11 @@ def main(args):total_loss = torch.tensor(0.0, device=get_current_device())for step, batch in enumerate(dataloader):batch = preprocess_batch(- batch, patch_size, video_compressor, pad_to_multiple=args.sp_size+ batch,+ patch_size,+ video_compressor,+ pad_to_multiple=args.sp_size,+ model_arch=args.model_arch,)video_inputs = batch.pop("video_latent_states")mask = batch.pop("video_padding_mask")@@ -243,6 +251,9 @@ if __name__ == "__main__":parser.add_argument("-m", "--model", type=str, choices=list(DiT_models.keys()), default="DiT-S/8")+ parser.add_argument(+ "-x", "--model_arch", choices=SUPPORTED_MODEL_ARCH, default="cross-attn"+ )parser.add_argument("-d", "--dataset", nargs="+", default=[])parser.add_argument("-v", "--video_dir", type=str, required=True)parser.add_argument("-e", "--epochs", type=int, default=10)