roll-ai commited on
Commit
0659b98
·
verified ·
1 Parent(s): 3aca420

Upload 175 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +46 -0
  2. Dockerfile +43 -0
  3. cogvideo_controlnet_pcd.py +251 -0
  4. cogvideo_transformer.py +127 -0
  5. controlnet_pipeline.py +809 -0
  6. data/epic_gif.gif +3 -0
  7. data/test_i2v/captions/000000000005.2.013.txt +1 -0
  8. data/test_i2v/captions/000000000793.0.003.txt +1 -0
  9. data/test_i2v/captions/000000000896.2.005.txt +1 -0
  10. data/test_i2v/captions/000000001059.6.004.txt +1 -0
  11. data/test_i2v/captions/000000049282.4.005.txt +1 -0
  12. data/test_i2v/captions/000000049768.11.002.txt +1 -0
  13. data/test_i2v/captions/000002012796.6.001.txt +1 -0
  14. data/test_i2v/captions/000003031893.11.003.txt +1 -0
  15. data/test_i2v/masked_videos/000000000005.2.013.mp4 +3 -0
  16. data/test_i2v/masked_videos/000000000793.0.003.mp4 +3 -0
  17. data/test_i2v/masked_videos/000000000896.2.005.mp4 +3 -0
  18. data/test_i2v/masked_videos/000000001059.6.004.mp4 +3 -0
  19. data/test_i2v/masked_videos/000000049282.4.005.mp4 +3 -0
  20. data/test_i2v/masked_videos/000000049768.11.002.mp4 +3 -0
  21. data/test_i2v/masked_videos/000002012796.6.001.mp4 +3 -0
  22. data/test_i2v/masked_videos/000003031893.11.003.mp4 +3 -0
  23. data/test_i2v/masks/000000000005.2.013.npz +3 -0
  24. data/test_i2v/masks/000000000793.0.003.npz +3 -0
  25. data/test_i2v/masks/000000000896.2.005.npz +3 -0
  26. data/test_i2v/masks/000000001059.6.004.npz +3 -0
  27. data/test_i2v/masks/000000049282.4.005.npz +3 -0
  28. data/test_i2v/masks/000000049768.11.002.npz +3 -0
  29. data/test_i2v/masks/000002012796.6.001.npz +3 -0
  30. data/test_i2v/masks/000003031893.11.003.npz +3 -0
  31. data/test_i2v/videos/000000000005.2.013.mp4 +3 -0
  32. data/test_i2v/videos/000000000793.0.003.mp4 +3 -0
  33. data/test_i2v/videos/000000000896.2.005.mp4 +3 -0
  34. data/test_i2v/videos/000000001059.6.004.mp4 +3 -0
  35. data/test_i2v/videos/000000049282.4.005.mp4 +3 -0
  36. data/test_i2v/videos/000000049768.11.002.mp4 +3 -0
  37. data/test_i2v/videos/000002012796.6.001.mp4 +3 -0
  38. data/test_i2v/videos/000003031893.11.003.mp4 +3 -0
  39. data/test_v2v/captions/amalfi-coast_traj_loop2.txt +1 -0
  40. data/test_v2v/captions/art-museum_gradual_0_-30_0.0_0_0.txt +1 -0
  41. data/test_v2v/captions/dog_gradual_0_-30_-0.6_0_0.txt +1 -0
  42. data/test_v2v/captions/fish_gradual_25_0_0.0_0_0.txt +1 -0
  43. data/test_v2v/captions/grandma-birthday_gradual_0_0_0.2_0_0.txt +1 -0
  44. data/test_v2v/captions/happy-cat_gradual_-20_0_0.0_0_0.txt +1 -0
  45. data/test_v2v/captions/suv-in-the-dust_gradual_0_30_0.0_0_0.txt +1 -0
  46. data/test_v2v/captions/vlogger-corgi_traj_loop2.txt +1 -0
  47. data/test_v2v/masked_videos/amalfi-coast_traj_loop2.mp4 +3 -0
  48. data/test_v2v/masked_videos/art-museum_gradual_0_-30_0.0_0_0.mp4 +3 -0
  49. data/test_v2v/masked_videos/dog_gradual_0_-30_-0.6_0_0.mp4 +3 -0
  50. data/test_v2v/masked_videos/fish_gradual_25_0_0.0_0_0.mp4 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,49 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ data/epic_gif.gif filter=lfs diff=lfs merge=lfs -text
37
+ data/test_i2v/masked_videos/000000000005.2.013.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ data/test_i2v/masked_videos/000000000793.0.003.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ data/test_i2v/masked_videos/000000000896.2.005.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ data/test_i2v/masked_videos/000000001059.6.004.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ data/test_i2v/masked_videos/000000049282.4.005.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ data/test_i2v/masked_videos/000000049768.11.002.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ data/test_i2v/masked_videos/000002012796.6.001.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ data/test_i2v/masked_videos/000003031893.11.003.mp4 filter=lfs diff=lfs merge=lfs -text
45
+ data/test_i2v/videos/000000000005.2.013.mp4 filter=lfs diff=lfs merge=lfs -text
46
+ data/test_i2v/videos/000000000793.0.003.mp4 filter=lfs diff=lfs merge=lfs -text
47
+ data/test_i2v/videos/000000000896.2.005.mp4 filter=lfs diff=lfs merge=lfs -text
48
+ data/test_i2v/videos/000000001059.6.004.mp4 filter=lfs diff=lfs merge=lfs -text
49
+ data/test_i2v/videos/000000049282.4.005.mp4 filter=lfs diff=lfs merge=lfs -text
50
+ data/test_i2v/videos/000000049768.11.002.mp4 filter=lfs diff=lfs merge=lfs -text
51
+ data/test_i2v/videos/000002012796.6.001.mp4 filter=lfs diff=lfs merge=lfs -text
52
+ data/test_i2v/videos/000003031893.11.003.mp4 filter=lfs diff=lfs merge=lfs -text
53
+ data/test_v2v/masked_videos/amalfi-coast_traj_loop2.mp4 filter=lfs diff=lfs merge=lfs -text
54
+ data/test_v2v/masked_videos/art-museum_gradual_0_-30_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
55
+ data/test_v2v/masked_videos/dog_gradual_0_-30_-0.6_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
56
+ data/test_v2v/masked_videos/fish_gradual_25_0_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
57
+ data/test_v2v/masked_videos/grandma-birthday_gradual_0_0_0.2_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
58
+ data/test_v2v/masked_videos/happy-cat_gradual_-20_0_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
59
+ data/test_v2v/masked_videos/suv-in-the-dust_gradual_0_30_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ data/test_v2v/masked_videos/vlogger-corgi_traj_loop2.mp4 filter=lfs diff=lfs merge=lfs -text
61
+ data/test_v2v/videos/amalfi-coast_traj_loop2.mp4 filter=lfs diff=lfs merge=lfs -text
62
+ data/test_v2v/videos/art-museum_gradual_0_-30_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
63
+ data/test_v2v/videos/dog_gradual_0_-30_-0.6_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
64
+ data/test_v2v/videos/fish_gradual_25_0_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
65
+ data/test_v2v/videos/grandma-birthday_gradual_0_0_0.2_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
66
+ data/test_v2v/videos/happy-cat_gradual_-20_0_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
67
+ data/test_v2v/videos/suv-in-the-dust_gradual_0_30_0.0_0_0.mp4 filter=lfs diff=lfs merge=lfs -text
68
+ data/test_v2v/videos/vlogger-corgi_traj_loop2.mp4 filter=lfs diff=lfs merge=lfs -text
69
+ inference/v2v_data/test/videos/0-NNvgaTcVzAG0-r.mp4 filter=lfs diff=lfs merge=lfs -text
70
+ inference/v2v_data/test/videos/p7.mp4 filter=lfs diff=lfs merge=lfs -text
71
+ preprocess/RAFT/demo-frames/frame_0016.png filter=lfs diff=lfs merge=lfs -text
72
+ preprocess/RAFT/demo-frames/frame_0017.png filter=lfs diff=lfs merge=lfs -text
73
+ preprocess/RAFT/demo-frames/frame_0018.png filter=lfs diff=lfs merge=lfs -text
74
+ preprocess/RAFT/demo-frames/frame_0019.png filter=lfs diff=lfs merge=lfs -text
75
+ preprocess/RAFT/demo-frames/frame_0020.png filter=lfs diff=lfs merge=lfs -text
76
+ preprocess/RAFT/demo-frames/frame_0021.png filter=lfs diff=lfs merge=lfs -text
77
+ preprocess/RAFT/demo-frames/frame_0022.png filter=lfs diff=lfs merge=lfs -text
78
+ preprocess/RAFT/demo-frames/frame_0023.png filter=lfs diff=lfs merge=lfs -text
79
+ preprocess/RAFT/demo-frames/frame_0024.png filter=lfs diff=lfs merge=lfs -text
80
+ preprocess/RAFT/demo-frames/frame_0025.png filter=lfs diff=lfs merge=lfs -text
81
+ preprocess/RAFT/RAFT.png filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.2.2-cuda12.1-cudnn8-runtime
2
+
3
+ SHELL ["/bin/bash", "-c"]
4
+
5
+ # Environment variables for Hugging Face cache
6
+ ENV HF_HOME=/app/hf_cache
7
+ ENV TRANSFORMERS_CACHE=/app/hf_cache
8
+ ENV HF_TOKEN=${HF_TOKEN}
9
+ ENV PATH=/opt/conda/bin:$PATH
10
+ # Install system dependencies
11
+ RUN apt-get update && apt-get install -y \
12
+ git wget curl unzip ffmpeg libgl1-mesa-glx libglib2.0-0 && \
13
+ apt-get clean
14
+
15
+ # Set up working directory as /app
16
+ WORKDIR /app
17
+
18
+ # Copy project into /app
19
+ COPY . /app
20
+
21
+ # Fix permissions for all subdirectories
22
+ RUN mkdir -p /app/pretrained /app/hf_cache /.cache/gdown && \
23
+ chmod -R 777 /app && \
24
+ chmod -R 777 /.cache && \
25
+ chmod -R 777 /root
26
+
27
+ # Create conda environment and install dependencies
28
+ COPY requirements.txt /app/requirements.txt
29
+ RUN conda create -n epic python=3.10 -y && \
30
+ conda run -n epic pip install --upgrade pip && \
31
+ conda run -n epic pip install -r /app/requirements.txt
32
+
33
+ RUN chmod -R 777 /app /workspace
34
+
35
+ # # List contents (for debug)
36
+ RUN ls -la /app
37
+ RUN pip install gradio
38
+
39
+ # Expose Gradio default port
40
+ EXPOSE 7860
41
+
42
+ # Start the Gradio app
43
+ CMD ["conda", "run", "--no-capture-output", "-n", "epic", "python", "gradio_app.py"]
cogvideo_controlnet_pcd.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ from einops import rearrange
6
+ import torch.nn.functional as F
7
+ from diffusers.models.transformers.cogvideox_transformer_3d import Transformer2DModelOutput, CogVideoXBlock
8
+ from diffusers.utils import is_torch_version
9
+ from diffusers.loaders import PeftAdapterMixin
10
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
11
+ from diffusers.models.embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps, get_3d_sincos_pos_embed
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from diffusers.models.attention import Attention, FeedForward
14
+ from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor2_0
15
+ from diffusers.models.normalization import AdaLayerNorm, CogVideoXLayerNormZero, AdaLayerNormZeroSingle
16
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
17
+
18
+
19
+ class CogVideoXControlnetPCD(ModelMixin, ConfigMixin, PeftAdapterMixin):
20
+ _supports_gradient_checkpointing = True
21
+
22
+ @register_to_config
23
+ def __init__(
24
+ self,
25
+ num_attention_heads: int = 30,
26
+ use_zero_conv: bool = False,
27
+ attention_head_dim: int = 64,
28
+ vae_channels: int = 16,
29
+ in_channels: int = 3,
30
+ downscale_coef: int = 8,
31
+ flip_sin_to_cos: bool = True,
32
+ freq_shift: int = 0,
33
+ time_embed_dim: int = 512,
34
+ num_layers: int = 8,
35
+ dropout: float = 0.0,
36
+ attention_bias: bool = True,
37
+ sample_width: int = 90,
38
+ sample_height: int = 60,
39
+ sample_frames: int = 49,
40
+ patch_size: int = 2,
41
+ temporal_compression_ratio: int = 4,
42
+ max_text_seq_length: int = 226,
43
+ activation_fn: str = "gelu-approximate",
44
+ timestep_activation_fn: str = "silu",
45
+ norm_elementwise_affine: bool = True,
46
+ norm_eps: float = 1e-5,
47
+ spatial_interpolation_scale: float = 1.875,
48
+ temporal_interpolation_scale: float = 1.0,
49
+ use_rotary_positional_embeddings: bool = False,
50
+ use_learned_positional_embeddings: bool = False,
51
+ out_proj_dim: int = None,
52
+ out_proj_dim_zero_init: bool = False,
53
+ ):
54
+ super().__init__()
55
+ inner_dim = num_attention_heads * attention_head_dim
56
+
57
+ if not use_rotary_positional_embeddings and use_learned_positional_embeddings:
58
+ raise ValueError(
59
+ "There are no CogVideoX checkpoints available with disable rotary embeddings and learned positional "
60
+ "embeddings. If you're using a custom model and/or believe this should be supported, please open an "
61
+ "issue at https://github.com/huggingface/diffusers/issues."
62
+ )
63
+
64
+ self.vae_channels = vae_channels
65
+ start_channels = in_channels * (downscale_coef ** 2)
66
+ input_channels = [start_channels, start_channels // 2, start_channels // 4]
67
+ self.unshuffle = nn.PixelUnshuffle(downscale_coef)
68
+ self.use_zero_conv = use_zero_conv
69
+
70
+ if use_zero_conv:
71
+ self.controlnet_encode_first = nn.Sequential(
72
+ nn.Conv2d(input_channels[0], input_channels[1], kernel_size=1, stride=1, padding=0),
73
+ nn.GroupNorm(2, input_channels[1]),
74
+ nn.ReLU(),
75
+ )
76
+
77
+ self.controlnet_encode_second = nn.Sequential(
78
+ nn.Conv2d(input_channels[1], input_channels[2], kernel_size=1, stride=1, padding=0),
79
+ nn.GroupNorm(2, input_channels[2]),
80
+ nn.ReLU(),
81
+ )
82
+ patch_embed_in_channels = vae_channels + input_channels[2]
83
+
84
+ else:
85
+ patch_embed_in_channels = vae_channels*2
86
+
87
+ # 1. Patch embedding
88
+ # self.patch_embed = CogVideoXPatchEmbed(
89
+ # patch_size=patch_size,
90
+ # in_channels=patch_embed_in_channels,
91
+ # embed_dim=inner_dim,
92
+ # bias=True,
93
+ # sample_width=sample_width,
94
+ # sample_height=sample_height,
95
+ # sample_frames=sample_frames,
96
+ # temporal_compression_ratio=temporal_compression_ratio,
97
+ # spatial_interpolation_scale=spatial_interpolation_scale,
98
+ # temporal_interpolation_scale=temporal_interpolation_scale,
99
+ # use_positional_embeddings=not use_rotary_positional_embeddings,
100
+ # use_learned_positional_embeddings=use_learned_positional_embeddings,
101
+ # )
102
+ self.patch_embed = CogVideoXPatchEmbed(
103
+ patch_size=patch_size,
104
+ in_channels=patch_embed_in_channels,
105
+ embed_dim=inner_dim,
106
+ bias=True,
107
+ sample_width=sample_width,
108
+ sample_height=sample_height,
109
+ sample_frames=sample_frames,
110
+ temporal_compression_ratio=temporal_compression_ratio,
111
+ spatial_interpolation_scale=spatial_interpolation_scale,
112
+ temporal_interpolation_scale=temporal_interpolation_scale,
113
+ use_positional_embeddings=not use_rotary_positional_embeddings,
114
+ use_learned_positional_embeddings=use_learned_positional_embeddings,
115
+ )
116
+ self.embedding_dropout = nn.Dropout(dropout)
117
+
118
+ # 2. Time embeddings
119
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
120
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
121
+
122
+ # 3. Define spatio-temporal transformers blocks
123
+ self.transformer_blocks = nn.ModuleList(
124
+ [
125
+ CogVideoXBlock(
126
+ dim=inner_dim,
127
+ num_attention_heads=num_attention_heads,
128
+ attention_head_dim=attention_head_dim,
129
+ time_embed_dim=time_embed_dim,
130
+ dropout=dropout,
131
+ activation_fn=activation_fn,
132
+ attention_bias=attention_bias,
133
+ norm_elementwise_affine=norm_elementwise_affine,
134
+ norm_eps=norm_eps,
135
+ )
136
+ for _ in range(num_layers)
137
+ ]
138
+ )
139
+
140
+ self.out_projectors = None
141
+ if out_proj_dim is not None:
142
+ self.out_projectors = nn.ModuleList(
143
+ [nn.Linear(inner_dim, out_proj_dim) for _ in range(num_layers)]
144
+ )
145
+ if out_proj_dim_zero_init:
146
+ for out_projector in self.out_projectors:
147
+ self.zeros_init_linear(out_projector)
148
+
149
+ self.gradient_checkpointing = False
150
+
151
+ def zeros_init_linear(self, linear: nn.Module):
152
+ if isinstance(linear, (nn.Linear, nn.Conv1d)):
153
+ if hasattr(linear, "weight"):
154
+ nn.init.zeros_(linear.weight)
155
+ if hasattr(linear, "bias"):
156
+ nn.init.zeros_(linear.bias)
157
+
158
+ def _set_gradient_checkpointing(self, module, value=False):
159
+ self.gradient_checkpointing = value
160
+
161
+ def compress_time(self, x, num_frames):
162
+ x = rearrange(x, '(b f) c h w -> b f c h w', f=num_frames)
163
+ batch_size, frames, channels, height, width = x.shape
164
+ x = rearrange(x, 'b f c h w -> (b h w) c f')
165
+
166
+ if x.shape[-1] % 2 == 1:
167
+ x_first, x_rest = x[..., 0], x[..., 1:]
168
+ if x_rest.shape[-1] > 0:
169
+ x_rest = F.avg_pool1d(x_rest, kernel_size=2, stride=2)
170
+
171
+ x = torch.cat([x_first[..., None], x_rest], dim=-1)
172
+ else:
173
+ x = F.avg_pool1d(x, kernel_size=2, stride=2)
174
+ x = rearrange(x, '(b h w) c f -> (b f) c h w', b=batch_size, h=height, w=width)
175
+ return x
176
+
177
+ def forward(
178
+ self,
179
+ hidden_states: torch.Tensor,
180
+ encoder_hidden_states: torch.Tensor,
181
+ controlnet_states: Tuple[torch.Tensor, torch.Tensor],
182
+ timestep: Union[int, float, torch.LongTensor],
183
+ controlnet_output_mask: Optional[torch.Tensor] = None,
184
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
185
+ timestep_cond: Optional[torch.Tensor] = None,
186
+ return_dict: bool = True,
187
+ ):
188
+ print("hidden_states.shape =", hidden_states.shape)
189
+ print("controlnet_states.shape =", controlnet_states.shape)
190
+
191
+ hidden_states = torch.cat([hidden_states, controlnet_states], dim=2)
192
+
193
+ # controlnet_states = self.controlnext_encoder(controlnet_states, timestep=timestep)
194
+ # 1. Time embedding
195
+ timesteps = timestep
196
+ t_emb = self.time_proj(timesteps)
197
+
198
+ # timesteps does not contain any weights and will always return f32 tensors
199
+ # but time_embedding might actually be running in fp16. so we need to cast here.
200
+ # there might be better ways to encapsulate this.
201
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
202
+ emb = self.time_embedding(t_emb, timestep_cond)
203
+
204
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
205
+ hidden_states = self.embedding_dropout(hidden_states)
206
+
207
+
208
+ text_seq_length = encoder_hidden_states.shape[1]
209
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
210
+ hidden_states = hidden_states[:, text_seq_length:]
211
+
212
+
213
+ controlnet_hidden_states = ()
214
+ # 3. Transformer blocks
215
+ for i, block in enumerate(self.transformer_blocks):
216
+ if self.training and self.gradient_checkpointing:
217
+
218
+ def create_custom_forward(module):
219
+ def custom_forward(*inputs):
220
+ return module(*inputs)
221
+
222
+ return custom_forward
223
+
224
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
225
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
226
+ create_custom_forward(block),
227
+ hidden_states,
228
+ encoder_hidden_states,
229
+ emb,
230
+ image_rotary_emb,
231
+ **ckpt_kwargs,
232
+ )
233
+ else:
234
+ hidden_states, encoder_hidden_states = block(
235
+ hidden_states=hidden_states,
236
+ encoder_hidden_states=encoder_hidden_states,
237
+ temb=emb,
238
+ image_rotary_emb=image_rotary_emb,
239
+ )
240
+
241
+ if self.out_projectors is not None:
242
+ if controlnet_output_mask is not None:
243
+ controlnet_hidden_states += (self.out_projectors[i](hidden_states) * controlnet_output_mask,)
244
+ else:
245
+ controlnet_hidden_states += (self.out_projectors[i](hidden_states),)
246
+ else:
247
+ controlnet_hidden_states += (hidden_states,)
248
+
249
+ if not return_dict:
250
+ return (controlnet_hidden_states,)
251
+ return Transformer2DModelOutput(sample=controlnet_hidden_states)
cogvideo_transformer.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import numpy as np
5
+ from diffusers.utils import is_torch_version
6
+ from diffusers.models.transformers.cogvideox_transformer_3d import CogVideoXTransformer3DModel, Transformer2DModelOutput
7
+
8
+
9
+ class CustomCogVideoXTransformer3DModel(CogVideoXTransformer3DModel):
10
+ def set_learnable_parameters(self, unfrozen_layers: int = 16):
11
+ for param in self.patch_embed.parameters():
12
+ param.requires_grad = True
13
+
14
+ for i in range(unfrozen_layers):
15
+ block = self.transformer_blocks[i]
16
+ attn = block.attn1
17
+ for module in [block.norm2, block.ff]:
18
+ for param in self.patch_embed.parameters():
19
+ param.requires_grad = True
20
+
21
+ for name in ['to_q', 'to_k', 'to_v', 'norm_q', 'norm_k']:
22
+ module = getattr(attn, name, None)
23
+ if module is not None:
24
+ for param in module.parameters():
25
+ param.requires_grad = True
26
+ else:
27
+ print(f"[Warning] {name} not found in attn1 of block {i}")
28
+
29
+ def forward(
30
+ self,
31
+ hidden_states: torch.Tensor,
32
+ encoder_hidden_states: torch.Tensor,
33
+ timestep: Union[int, float, torch.LongTensor],
34
+ start_frame = None,
35
+ timestep_cond: Optional[torch.Tensor] = None,
36
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
37
+ controlnet_states: torch.Tensor = None,
38
+ controlnet_weights: Optional[Union[float, int, list, np.ndarray, torch.FloatTensor]] = 1.0,
39
+ return_dict: bool = True,
40
+ ):
41
+ batch_size, num_frames, channels, height, width = hidden_states.shape
42
+
43
+ if start_frame is not None:
44
+ hidden_states = torch.cat([start_frame, hidden_states], dim=2)
45
+ # 1. Time embedding
46
+ timesteps = timestep
47
+ t_emb = self.time_proj(timesteps)
48
+
49
+ # timesteps does not contain any weights and will always return f32 tensors
50
+ # but time_embedding might actually be running in fp16. so we need to cast here.
51
+ # there might be better ways to encapsulate this.
52
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
53
+ emb = self.time_embedding(t_emb, timestep_cond)
54
+
55
+ # 2. Patch embedding
56
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
57
+ hidden_states = self.embedding_dropout(hidden_states)
58
+
59
+ text_seq_length = encoder_hidden_states.shape[1]
60
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
61
+ hidden_states = hidden_states[:, text_seq_length:]
62
+
63
+ # 3. Transformer blocks
64
+ for i, block in enumerate(self.transformer_blocks):
65
+ if self.gradient_checkpointing:
66
+ def create_custom_forward(module):
67
+ def custom_forward(*inputs):
68
+ return module(*inputs)
69
+
70
+ return custom_forward
71
+
72
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
73
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
74
+ create_custom_forward(block),
75
+ hidden_states,
76
+ encoder_hidden_states,
77
+ emb,
78
+ image_rotary_emb,
79
+ **ckpt_kwargs,
80
+ )
81
+ else:
82
+ hidden_states, encoder_hidden_states = block(
83
+ hidden_states=hidden_states,
84
+ encoder_hidden_states=encoder_hidden_states,
85
+ temb=emb,
86
+ image_rotary_emb=image_rotary_emb,
87
+ )
88
+
89
+ if (controlnet_states is not None) and (i < len(controlnet_states)):
90
+ controlnet_states_block = controlnet_states[i]
91
+ controlnet_block_weight = 1.0
92
+ if isinstance(controlnet_weights, (list, np.ndarray)) or torch.is_tensor(controlnet_weights):
93
+ controlnet_block_weight = controlnet_weights[i]
94
+ elif isinstance(controlnet_weights, (float, int)):
95
+ controlnet_block_weight = controlnet_weights
96
+
97
+ hidden_states = hidden_states + controlnet_states_block * controlnet_block_weight
98
+
99
+ if not self.config.use_rotary_positional_embeddings:
100
+ # CogVideoX-2B
101
+ hidden_states = self.norm_final(hidden_states)
102
+ else:
103
+ # CogVideoX-5B
104
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
105
+ hidden_states = self.norm_final(hidden_states)
106
+ hidden_states = hidden_states[:, text_seq_length:]
107
+
108
+ # 4. Final block
109
+ hidden_states = self.norm_out(hidden_states, temb=emb)
110
+ hidden_states = self.proj_out(hidden_states)
111
+
112
+ # 5. Unpatchify
113
+ p = self.config.patch_size
114
+ p_t = self.config.patch_size_t
115
+
116
+ if p_t is None:
117
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
118
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
119
+ else:
120
+ output = hidden_states.reshape(
121
+ batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p
122
+ )
123
+ output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2)
124
+
125
+ if not return_dict:
126
+ return (output,)
127
+ return Transformer2DModelOutput(sample=output)
controlnet_pipeline.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import math
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import numpy as np
7
+ import PIL
8
+ from PIL import Image
9
+ from torchvision import transforms
10
+ from einops import rearrange, repeat
11
+ from transformers import T5EncoderModel, T5Tokenizer
12
+ from diffusers.video_processor import VideoProcessor
13
+ from diffusers.utils.torch_utils import randn_tensor
14
+ from diffusers.models.embeddings import get_3d_rotary_pos_embed
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
16
+ from diffusers.models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
17
+ from diffusers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
18
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
19
+ from diffusers.pipelines.cogvideo.pipeline_cogvideox import CogVideoXPipelineOutput, CogVideoXLoraLoaderMixin
20
+ from diffusers.image_processor import PipelineImageInput
21
+
22
+ from cogvideo_controlnet_pcd import CogVideoXControlnetPCD as CogVideoXControlnet
23
+
24
+ def resize_for_crop(image, crop_h, crop_w):
25
+ img_h, img_w = image.shape[-2:]
26
+ if img_h >= crop_h and img_w >= crop_w:
27
+ coef = max(crop_h / img_h, crop_w / img_w)
28
+ elif img_h <= crop_h and img_w <= crop_w:
29
+ coef = max(crop_h / img_h, crop_w / img_w)
30
+ else:
31
+ coef = crop_h / img_h if crop_h > img_h else crop_w / img_w
32
+ out_h, out_w = int(img_h * coef), int(img_w * coef)
33
+ resized_image = transforms.functional.resize(image, (out_h, out_w), antialias=True)
34
+ return resized_image
35
+
36
+
37
+ def prepare_frames(input_images, video_size, do_resize=True, do_crop=True):
38
+ input_images = np.stack([np.array(x) for x in input_images])
39
+ images_tensor = torch.from_numpy(input_images).permute(0, 3, 1, 2) / 127.5 - 1
40
+ if do_resize:
41
+ images_tensor = [resize_for_crop(x, crop_h=video_size[0], crop_w=video_size[1]) for x in images_tensor]
42
+ if do_crop:
43
+ images_tensor = [transforms.functional.center_crop(x, video_size) for x in images_tensor]
44
+ if isinstance(images_tensor, list):
45
+ images_tensor = torch.stack(images_tensor)
46
+ return images_tensor.unsqueeze(0)
47
+
48
+
49
+ def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
50
+ tw = tgt_width
51
+ th = tgt_height
52
+ h, w = src
53
+ r = h / w
54
+ if r > (th / tw):
55
+ resize_height = th
56
+ resize_width = int(round(th / h * w))
57
+ else:
58
+ resize_width = tw
59
+ resize_height = int(round(tw / w * h))
60
+
61
+ crop_top = int(round((th - resize_height) / 2.0))
62
+ crop_left = int(round((tw - resize_width) / 2.0))
63
+
64
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
65
+
66
+
67
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
68
+ def retrieve_timesteps(
69
+ scheduler,
70
+ num_inference_steps: Optional[int] = None,
71
+ device: Optional[Union[str, torch.device]] = None,
72
+ timesteps: Optional[List[int]] = None,
73
+ sigmas: Optional[List[float]] = None,
74
+ **kwargs,
75
+ ):
76
+ """
77
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
78
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
79
+
80
+ Args:
81
+ scheduler (`SchedulerMixin`):
82
+ The scheduler to get timesteps from.
83
+ num_inference_steps (`int`):
84
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
85
+ must be `None`.
86
+ device (`str` or `torch.device`, *optional*):
87
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
88
+ timesteps (`List[int]`, *optional*):
89
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
90
+ `num_inference_steps` and `sigmas` must be `None`.
91
+ sigmas (`List[float]`, *optional*):
92
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
93
+ `num_inference_steps` and `timesteps` must be `None`.
94
+
95
+ Returns:
96
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
97
+ second element is the number of inference steps.
98
+ """
99
+ if timesteps is not None and sigmas is not None:
100
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
101
+ if timesteps is not None:
102
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
103
+ if not accepts_timesteps:
104
+ raise ValueError(
105
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
106
+ f" timestep schedules. Please check whether you are using the correct scheduler."
107
+ )
108
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
109
+ timesteps = scheduler.timesteps
110
+ num_inference_steps = len(timesteps)
111
+ elif sigmas is not None:
112
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
113
+ if not accept_sigmas:
114
+ raise ValueError(
115
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
116
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
117
+ )
118
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
119
+ timesteps = scheduler.timesteps
120
+ num_inference_steps = len(timesteps)
121
+ else:
122
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
123
+ timesteps = scheduler.timesteps
124
+ return timesteps, num_inference_steps
125
+
126
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
127
+ def retrieve_latents(
128
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
129
+ ):
130
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
131
+ return encoder_output.latent_dist.sample(generator)
132
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
133
+ return encoder_output.latent_dist.mode()
134
+ elif hasattr(encoder_output, "latents"):
135
+ return encoder_output.latents
136
+ else:
137
+ raise AttributeError("Could not access latents of provided encoder_output")
138
+
139
+ class ControlnetCogVideoXImageToVideoPCDPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin):
140
+ _optional_components = []
141
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
142
+
143
+ _callback_tensor_inputs = [
144
+ "latents",
145
+ "prompt_embeds",
146
+ "negative_prompt_embeds",
147
+ ]
148
+
149
+ def __init__(
150
+ self,
151
+ tokenizer: T5Tokenizer,
152
+ text_encoder: T5EncoderModel,
153
+ vae: AutoencoderKLCogVideoX,
154
+ transformer: CogVideoXTransformer3DModel,
155
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
156
+ controlnet: CogVideoXControlnet,
157
+ ):
158
+ super().__init__()
159
+
160
+ self.register_modules(
161
+ tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, controlnet=controlnet, scheduler=scheduler
162
+ )
163
+ self.vae_scale_factor_spatial = (
164
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
165
+ )
166
+ self.vae_scale_factor_temporal = (
167
+ self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
168
+ )
169
+ self.vae_scaling_factor_image = (
170
+ self.vae.config.scaling_factor if hasattr(self, "vae") and self.vae is not None else 0.7 # 1.15258426
171
+ )
172
+
173
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
174
+
175
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._get_t5_prompt_embeds
176
+ def _get_t5_prompt_embeds(
177
+ self,
178
+ prompt: Union[str, List[str]] = None,
179
+ num_videos_per_prompt: int = 1,
180
+ max_sequence_length: int = 226,
181
+ device: Optional[torch.device] = None,
182
+ dtype: Optional[torch.dtype] = None,
183
+ ):
184
+ device = device or self._execution_device
185
+ dtype = dtype or self.text_encoder.dtype
186
+
187
+ prompt = [prompt] if isinstance(prompt, str) else prompt
188
+ batch_size = len(prompt)
189
+
190
+ text_inputs = self.tokenizer(
191
+ prompt,
192
+ padding="max_length",
193
+ max_length=max_sequence_length,
194
+ truncation=True,
195
+ add_special_tokens=True,
196
+ return_tensors="pt",
197
+ )
198
+ text_input_ids = text_inputs.input_ids
199
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
200
+
201
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
202
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
203
+ logger.warning(
204
+ "The following part of your input was truncated because `max_sequence_length` is set to "
205
+ f" {max_sequence_length} tokens: {removed_text}"
206
+ )
207
+
208
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
209
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
210
+
211
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
212
+ _, seq_len, _ = prompt_embeds.shape
213
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
214
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
215
+
216
+ return prompt_embeds
217
+
218
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt
219
+ def encode_prompt(
220
+ self,
221
+ prompt: Union[str, List[str]],
222
+ negative_prompt: Optional[Union[str, List[str]]] = None,
223
+ do_classifier_free_guidance: bool = True,
224
+ num_videos_per_prompt: int = 1,
225
+ prompt_embeds: Optional[torch.Tensor] = None,
226
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
227
+ max_sequence_length: int = 226,
228
+ device: Optional[torch.device] = None,
229
+ dtype: Optional[torch.dtype] = None,
230
+ ):
231
+ r"""
232
+ Encodes the prompt into text encoder hidden states.
233
+
234
+ Args:
235
+ prompt (`str` or `List[str]`, *optional*):
236
+ prompt to be encoded
237
+ negative_prompt (`str` or `List[str]`, *optional*):
238
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
239
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
240
+ less than `1`).
241
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
242
+ Whether to use classifier free guidance or not.
243
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
244
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
245
+ prompt_embeds (`torch.Tensor`, *optional*):
246
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
247
+ provided, text embeddings will be generated from `prompt` input argument.
248
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
249
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
250
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
251
+ argument.
252
+ device: (`torch.device`, *optional*):
253
+ torch device
254
+ dtype: (`torch.dtype`, *optional*):
255
+ torch dtype
256
+ """
257
+ device = device or self._execution_device
258
+
259
+ prompt = [prompt] if isinstance(prompt, str) else prompt
260
+ if prompt is not None:
261
+ batch_size = len(prompt)
262
+ else:
263
+ batch_size = prompt_embeds.shape[0]
264
+
265
+ if prompt_embeds is None:
266
+ prompt_embeds = self._get_t5_prompt_embeds(
267
+ prompt=prompt,
268
+ num_videos_per_prompt=num_videos_per_prompt,
269
+ max_sequence_length=max_sequence_length,
270
+ device=device,
271
+ dtype=dtype,
272
+ )
273
+
274
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
275
+ negative_prompt = negative_prompt or ""
276
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
277
+
278
+ if prompt is not None and type(prompt) is not type(negative_prompt):
279
+ raise TypeError(
280
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
281
+ f" {type(prompt)}."
282
+ )
283
+ elif batch_size != len(negative_prompt):
284
+ raise ValueError(
285
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
286
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
287
+ " the batch size of `prompt`."
288
+ )
289
+
290
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
291
+ prompt=negative_prompt,
292
+ num_videos_per_prompt=num_videos_per_prompt,
293
+ max_sequence_length=max_sequence_length,
294
+ device=device,
295
+ dtype=dtype,
296
+ )
297
+
298
+ return prompt_embeds, negative_prompt_embeds
299
+
300
+ def prepare_latents(
301
+ self,
302
+ image: torch.Tensor,
303
+ batch_size: int = 1,
304
+ num_channels_latents: int = 16,
305
+ num_frames: int = 13,
306
+ height: int = 60,
307
+ width: int = 90,
308
+ dtype: Optional[torch.dtype] = None,
309
+ device: Optional[torch.device] = None,
310
+ generator: Optional[torch.Generator] = None,
311
+ latents: Optional[torch.Tensor] = None,
312
+ ):
313
+ if isinstance(generator, list) and len(generator) != batch_size:
314
+ raise ValueError(
315
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
316
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
317
+ )
318
+
319
+ num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
320
+ shape = (
321
+ batch_size,
322
+ num_frames,
323
+ num_channels_latents,
324
+ height // self.vae_scale_factor_spatial,
325
+ width // self.vae_scale_factor_spatial,
326
+ )
327
+
328
+ # For CogVideoX1.5, the latent should add 1 for padding (Not use)
329
+ if self.transformer.config.patch_size_t is not None:
330
+ shape = shape[:1] + (shape[1] + shape[1] % self.transformer.config.patch_size_t,) + shape[2:]
331
+
332
+ image = image.unsqueeze(2) # [B, C, F, H, W]
333
+
334
+ if isinstance(generator, list):
335
+ image_latents = [
336
+ retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i]) for i in range(batch_size)
337
+ ]
338
+ else:
339
+ image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in image]
340
+
341
+ image_latents = torch.cat(image_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W]
342
+
343
+ if not self.vae.config.invert_scale_latents:
344
+ image_latents = self.vae_scaling_factor_image * image_latents
345
+ else:
346
+ # This is awkward but required because the CogVideoX team forgot to multiply the
347
+ # scaling factor during training :)
348
+ image_latents = 1 / self.vae_scaling_factor_image * image_latents
349
+
350
+ padding_shape = (
351
+ batch_size,
352
+ num_frames - 1,
353
+ num_channels_latents,
354
+ height // self.vae_scale_factor_spatial,
355
+ width // self.vae_scale_factor_spatial,
356
+ )
357
+
358
+ latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype)
359
+ image_latents = torch.cat([image_latents, latent_padding], dim=1)
360
+
361
+ # Select the first frame along the second dimension
362
+ if self.transformer.config.patch_size_t is not None:
363
+ first_frame = image_latents[:, : image_latents.size(1) % self.transformer.config.patch_size_t, ...]
364
+ image_latents = torch.cat([first_frame, image_latents], dim=1)
365
+
366
+ if latents is None:
367
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
368
+ else:
369
+ latents = latents.to(device)
370
+
371
+ # scale the initial noise by the standard deviation required by the scheduler
372
+ latents = latents * self.scheduler.init_noise_sigma
373
+ return latents, image_latents
374
+
375
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.decode_latents
376
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
377
+ latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
378
+ latents = 1 / self.vae_scaling_factor_image * latents
379
+
380
+ frames = self.vae.decode(latents).sample
381
+ return frames
382
+
383
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps
384
+ def get_timesteps(self, num_inference_steps, timesteps, strength, device):
385
+ # get the original timestep using init_timestep
386
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
387
+
388
+ t_start = max(num_inference_steps - init_timestep, 0)
389
+ timesteps = timesteps[t_start * self.scheduler.order :]
390
+
391
+ return timesteps, num_inference_steps - t_start
392
+
393
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
394
+ def prepare_extra_step_kwargs(self, generator, eta):
395
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
396
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
397
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
398
+ # and should be between [0, 1]
399
+
400
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
401
+ extra_step_kwargs = {}
402
+ if accepts_eta:
403
+ extra_step_kwargs["eta"] = eta
404
+
405
+ # check if the scheduler accepts generator
406
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
407
+ if accepts_generator:
408
+ extra_step_kwargs["generator"] = generator
409
+ return extra_step_kwargs
410
+
411
+ def check_inputs(
412
+ self,
413
+ image,
414
+ prompt,
415
+ height,
416
+ width,
417
+ negative_prompt,
418
+ callback_on_step_end_tensor_inputs,
419
+ prompt_embeds=None,
420
+ negative_prompt_embeds=None,
421
+ ):
422
+ if (
423
+ not isinstance(image, torch.Tensor)
424
+ and not isinstance(image, PIL.Image.Image)
425
+ and not isinstance(image, list)
426
+ ):
427
+ raise ValueError(
428
+ "`image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
429
+ f" {type(image)}"
430
+ )
431
+
432
+ if height % 8 != 0 or width % 8 != 0:
433
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
434
+
435
+ if callback_on_step_end_tensor_inputs is not None and not all(
436
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
437
+ ):
438
+ raise ValueError(
439
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
440
+ )
441
+ if prompt is not None and prompt_embeds is not None:
442
+ raise ValueError(
443
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
444
+ " only forward one of the two."
445
+ )
446
+ elif prompt is None and prompt_embeds is None:
447
+ raise ValueError(
448
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
449
+ )
450
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
451
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
452
+
453
+ if prompt is not None and negative_prompt_embeds is not None:
454
+ raise ValueError(
455
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
456
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
457
+ )
458
+
459
+ if negative_prompt is not None and negative_prompt_embeds is not None:
460
+ raise ValueError(
461
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
462
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
463
+ )
464
+
465
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
466
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
467
+ raise ValueError(
468
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
469
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
470
+ f" {negative_prompt_embeds.shape}."
471
+ )
472
+
473
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.fuse_qkv_projections
474
+ def fuse_qkv_projections(self) -> None:
475
+ r"""Enables fused QKV projections."""
476
+ self.fusing_transformer = True
477
+ self.transformer.fuse_qkv_projections()
478
+
479
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.unfuse_qkv_projections
480
+ def unfuse_qkv_projections(self) -> None:
481
+ r"""Disable QKV projection fusion if enabled."""
482
+ if not self.fusing_transformer:
483
+ logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
484
+ else:
485
+ self.transformer.unfuse_qkv_projections()
486
+ self.fusing_transformer = False
487
+
488
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._prepare_rotary_positional_embeddings
489
+ def _prepare_rotary_positional_embeddings(
490
+ self,
491
+ height: int,
492
+ width: int,
493
+ num_frames: int,
494
+ device: torch.device,
495
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
496
+ grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
497
+ grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
498
+
499
+ p = self.transformer.config.patch_size
500
+ p_t = self.transformer.config.patch_size_t
501
+
502
+ base_size_width = self.transformer.config.sample_width // p
503
+ base_size_height = self.transformer.config.sample_height // p
504
+
505
+ if p_t is None:
506
+ # CogVideoX 1.0
507
+ grid_crops_coords = get_resize_crop_region_for_grid(
508
+ (grid_height, grid_width), base_size_width, base_size_height
509
+ )
510
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
511
+ embed_dim=self.transformer.config.attention_head_dim,
512
+ crops_coords=grid_crops_coords,
513
+ grid_size=(grid_height, grid_width),
514
+ temporal_size=num_frames,
515
+ device=device,
516
+ )
517
+ else:
518
+ # CogVideoX 1.5
519
+ base_num_frames = (num_frames + p_t - 1) // p_t
520
+
521
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
522
+ embed_dim=self.transformer.config.attention_head_dim,
523
+ crops_coords=None,
524
+ grid_size=(grid_height, grid_width),
525
+ temporal_size=base_num_frames,
526
+ grid_type="slice",
527
+ max_size=(base_size_height, base_size_width),
528
+ device=device,
529
+ )
530
+
531
+ return freqs_cos, freqs_sin
532
+
533
+ def encode_video(self, video):
534
+ video = video.to(self.device, dtype=self.vae.dtype)
535
+ video = video.permute(0, 2, 1, 3, 4) # [B, C, F, H, W]
536
+ latent_dist = self.vae.encode(video).latent_dist.sample() * self.vae.config.scaling_factor
537
+ return latent_dist.permute(0, 2, 1, 3, 4).to(memory_format=torch.contiguous_format)
538
+
539
+ @property
540
+ def guidance_scale(self):
541
+ return self._guidance_scale
542
+
543
+ @property
544
+ def num_timesteps(self):
545
+ return self._num_timesteps
546
+
547
+ @property
548
+ def attention_kwargs(self):
549
+ return self._attention_kwargs
550
+
551
+ @property
552
+ def interrupt(self):
553
+ return self._interrupt
554
+
555
+ @torch.no_grad()
556
+ def __call__(
557
+ self,
558
+ image: PipelineImageInput,
559
+ anchor_video: None,
560
+ controlnet_output_mask: None,
561
+ prompt: Optional[Union[str, List[str]]] = None,
562
+ negative_prompt: Optional[Union[str, List[str]]] = None,
563
+ height: Optional[int] = None,
564
+ width: Optional[int] = None,
565
+ num_frames: int = 49,
566
+ num_inference_steps: int = 50,
567
+ timesteps: Optional[List[int]] = None,
568
+ guidance_scale: float = 6,
569
+ use_dynamic_cfg: bool = False,
570
+ num_videos_per_prompt: int = 1,
571
+ eta: float = 0.0,
572
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
573
+ latents: Optional[torch.FloatTensor] = None,
574
+ prompt_embeds: Optional[torch.FloatTensor] = None,
575
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
576
+ output_type: str = "pil",
577
+ return_dict: bool = True,
578
+ attention_kwargs: Optional[Dict[str, Any]] = None,
579
+ callback_on_step_end: Optional[
580
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
581
+ ] = None,
582
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
583
+ max_sequence_length: int = 226,
584
+ controlnet_weights: Optional[Union[float, list, np.ndarray, torch.FloatTensor]] = 1.0,
585
+ controlnet_guidance_start: float = 0.0,
586
+ controlnet_guidance_end: float = 1.0,
587
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
588
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
589
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
590
+
591
+ height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial #720
592
+ width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial # 480
593
+ num_frames = num_frames or self.transformer.config.sample_frames
594
+
595
+ num_videos_per_prompt = 1
596
+
597
+ # 1. Check inputs. Raise error if not correct
598
+ self.check_inputs(
599
+ image=image,
600
+ prompt=prompt,
601
+ height=height,
602
+ width=width,
603
+ negative_prompt=negative_prompt,
604
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
605
+ prompt_embeds=prompt_embeds,
606
+ negative_prompt_embeds=negative_prompt_embeds,
607
+ )
608
+ self._guidance_scale = guidance_scale
609
+ self._attention_kwargs = attention_kwargs
610
+ self._interrupt = False
611
+
612
+ # 2. Default call parameters
613
+ if prompt is not None and isinstance(prompt, str):
614
+ batch_size = 1
615
+ elif prompt is not None and isinstance(prompt, list):
616
+ batch_size = len(prompt)
617
+ else:
618
+ batch_size = prompt_embeds.shape[0]
619
+
620
+ device = self._execution_device
621
+
622
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
623
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
624
+ # corresponds to doing no classifier free guidance.
625
+ do_classifier_free_guidance = guidance_scale > 1.0
626
+
627
+ # 3. Encode input prompt
628
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
629
+ prompt=prompt,
630
+ negative_prompt=negative_prompt,
631
+ do_classifier_free_guidance=do_classifier_free_guidance,
632
+ num_videos_per_prompt=num_videos_per_prompt,
633
+ prompt_embeds=prompt_embeds,
634
+ negative_prompt_embeds=negative_prompt_embeds,
635
+ max_sequence_length=max_sequence_length,
636
+ device=device,
637
+ )
638
+ if do_classifier_free_guidance:
639
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
640
+
641
+ # 4. Prepare timesteps
642
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
643
+ self._num_timesteps = len(timesteps)
644
+
645
+ # 5. Prepare latents
646
+ latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
647
+
648
+ # For CogVideoX 1.5, the latent frames should be padded to make it divisible by patch_size_t
649
+ patch_size_t = self.transformer.config.patch_size_t
650
+ additional_frames = 0
651
+ if patch_size_t is not None and latent_frames % patch_size_t != 0:
652
+ additional_frames = patch_size_t - latent_frames % patch_size_t
653
+ num_frames += additional_frames * self.vae_scale_factor_temporal
654
+
655
+ image = self.video_processor.preprocess(image, height=height, width=width).to(
656
+ device, dtype=prompt_embeds.dtype
657
+ )
658
+
659
+ latent_channels = self.transformer.config.in_channels // 2 # 8
660
+ latents, image_latents = self.prepare_latents(
661
+ image,
662
+ batch_size * num_videos_per_prompt,
663
+ latent_channels,
664
+ num_frames,
665
+ height,
666
+ width,
667
+ prompt_embeds.dtype,
668
+ device,
669
+ generator,
670
+ latents,
671
+ )
672
+
673
+ # 6 encoding anchor videos
674
+
675
+ anchor_states = self.encode_video(anchor_video[None]).to(device)
676
+
677
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
678
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
679
+
680
+ # 8. Create rotary embeds if required
681
+ image_rotary_emb = (
682
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
683
+ if self.transformer.config.use_rotary_positional_embeddings
684
+ else None
685
+ )
686
+
687
+ # 8. Create ofs embeds if required
688
+ ofs_emb = None if self.transformer.config.ofs_embed_dim is None else latents.new_full((1,), fill_value=2.0)
689
+
690
+ # 9. Denoising loop
691
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
692
+
693
+ if do_classifier_free_guidance:
694
+ anchor_states = torch.cat([anchor_states] * 2)
695
+
696
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
697
+ # for DPM-solver++
698
+ old_pred_original_sample = None
699
+ for i, t in enumerate(timesteps):
700
+ if self.interrupt:
701
+ continue
702
+
703
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
704
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
705
+
706
+ latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents
707
+
708
+ latent_and_image_input = torch.cat([latent_model_input, latent_image_input], dim=2)
709
+
710
+
711
+ # latent_and_image_input = torch.cat([latent_model_input], dim=2)
712
+
713
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
714
+ timestep = t.expand(latent_model_input.shape[0])
715
+
716
+ current_sampling_percent = i / len(timesteps)
717
+
718
+ latent_model_input = latent_model_input.to(dtype=self.transformer.dtype)
719
+ prompt_embeds = prompt_embeds.to(dtype=self.transformer.dtype)
720
+
721
+ controlnet_states = None
722
+ # latent_model_input
723
+ # input_controlnet_states
724
+
725
+ input_controlnet_states = anchor_states
726
+ if (controlnet_guidance_start <= current_sampling_percent <= controlnet_guidance_end):
727
+ controlnet_states = self.controlnet(
728
+ hidden_states=latent_model_input,
729
+ encoder_hidden_states=prompt_embeds,
730
+ image_rotary_emb=image_rotary_emb,
731
+ controlnet_states=input_controlnet_states,
732
+ controlnet_output_mask = controlnet_output_mask,
733
+ timestep=timestep,
734
+ return_dict=False,
735
+
736
+ )[0]
737
+ if isinstance(controlnet_states, (tuple, list)):
738
+ controlnet_states = [x.to(dtype=self.transformer.dtype) for x in controlnet_states]
739
+ else:
740
+ controlnet_states = controlnet_states.to(dtype=self.transformer.dtype)
741
+
742
+ # predict noise model_output
743
+ noise_pred = self.transformer(
744
+ hidden_states=latent_and_image_input,
745
+ encoder_hidden_states=prompt_embeds,
746
+ timestep=timestep,
747
+ image_rotary_emb=image_rotary_emb,
748
+ controlnet_states=controlnet_states,
749
+ controlnet_weights=controlnet_weights,
750
+ return_dict=False,
751
+ )[0]
752
+
753
+ noise_pred = noise_pred.float()
754
+
755
+ # perform guidance
756
+ if use_dynamic_cfg:
757
+ self._guidance_scale = 1 + guidance_scale * (
758
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
759
+ )
760
+ if do_classifier_free_guidance:
761
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
762
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
763
+
764
+ # compute the previous noisy sample x_t -> x_t-1
765
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
766
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
767
+ else:
768
+ latents, old_pred_original_sample = self.scheduler.step(
769
+ noise_pred,
770
+ old_pred_original_sample,
771
+ t,
772
+ timesteps[i - 1] if i > 0 else None,
773
+ latents,
774
+ **extra_step_kwargs,
775
+ return_dict=False,
776
+ )
777
+ latents = latents.to(prompt_embeds.dtype)
778
+
779
+ # call the callback, if provided
780
+ if callback_on_step_end is not None:
781
+ callback_kwargs = {}
782
+ for k in callback_on_step_end_tensor_inputs:
783
+ callback_kwargs[k] = locals()[k]
784
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
785
+
786
+ latents = callback_outputs.pop("latents", latents)
787
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
788
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
789
+
790
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
791
+ progress_bar.update()
792
+
793
+ if not output_type == "latent":
794
+ # Discard any padding frames that were added for CogVideoX 1.5
795
+ latents = latents[:, additional_frames:]
796
+ video = self.decode_latents(latents)
797
+ video = self.video_processor.postprocess_video(video=video, output_type=output_type)
798
+ else:
799
+ video = latents
800
+
801
+ # Offload all models
802
+ self.maybe_free_model_hooks()
803
+
804
+ if not return_dict:
805
+ return (video,)
806
+
807
+ return CogVideoXPipelineOutput(frames=video)
808
+
809
+
data/epic_gif.gif ADDED

Git LFS Details

  • SHA256: 03703e31f7964e5cbc1c8a10a16936a2bdab6e81070a62730b416e5108526459
  • Pointer size: 133 Bytes
  • Size of remote file: 10.7 MB
data/test_i2v/captions/000000000005.2.013.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Inside a dimly lit subway car, a first-person perspective shows a gloved hand holding a handgun aimed at the camera, with the barrel pointing directly at the viewer. the scene is tense, with the hand's movement suggesting an imminent threat. the background is blurred, indicating motion, and the interior is adorned with teal and blue seats, silver poles, and red and white advertisements. two seconds later, the perspective shifts to a gloved hand holding a black handgun aimed at the camera, with the barrel pointing directly at the viewer. the interior is quiet, with teal and blue seats, silver poles, and red and white advertisements, including one for 'the lion king'. the atmosphere is tense, with the hand's movement suggesting an imminent threat.
data/test_i2v/captions/000000000793.0.003.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A purple porsche suv drives on a dirt road through a mountainous landscape, with a helicopter parked on a rocky outcrop in the distance, under a sky with scattered clouds. the scene is part of a video game, indicated by the 'gta 5' logo. two seconds later, the same purple suv, now identified with a 'cayenne' badge, continues its journey on the dirt road, kicking up dust. the background features a rugged mountainous terrain, a clear blue sky with scattered clouds, and a distant helicopter on a rocky outcrop, suggesting an adventurous setting.
data/test_i2v/captions/000000000896.2.005.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A character dressed in dark, medieval attire with white hair and yellow eyes rides a reddish-brown horse through a lush, green forest. the scene is set in a video game environment, with a user interface visible in the upper left corner, indicating gameplay mechanics. as the character continues, they traverse a grassy path surrounded by dense coniferous trees, with the game's interface showing health and stamina bars, a mini-map, and inventory icons. the player's progress is tracked by level indicators and currency, suggesting an immersive role-playing experience. the character's yellow eyes and white hair are consistent throughout the journey.
data/test_i2v/captions/000000001059.6.004.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A lone explorer in a detailed exoskeleton suit with a helmet and visor is seen traversing a desolate, rocky terrain under an overcast sky, suggesting a science fiction setting. the explorer's journey is marked by solitude and the stark beauty of an extraterrestrial environment, with no other life or human activity visible. the scene is set against a backdrop of reddish-brown soil and dark volcanic rocks, with the mood of isolation and the allure of discovery emphasized by the subdued lighting and the absence of any other life or human activity.
data/test_i2v/captions/000000049282.4.005.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A bustling street scene in rome, italy, with pedestrians walking by shops like 'superman' and 'salvatore ferragamo'. the architecture is european, with buildings painted in warm yellows and oranges. a man in a white t-shirt and backpack looks over his shoulder, while a woman in a red coat and sunglasses walks forward. two seconds later, the scene shifts to a narrow street lined with yellow buildings, where people stroll under an awning labeled 'ristorante'. the atmosphere is vibrant, with a mix of casual and smart-casual attire, and a 'sale' sign on a storefront suggests commercial activity.
data/test_i2v/captions/000000049768.11.002.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A serene coastal town with a pastel-colored building adorned with green shutters and a striped awning. a clothesline with laundry adds a domestic touch to the tranquil scene. the town is set against a backdrop of a rugged cliff and a calm blue sea, with a clear sky overhead. as the video continues, the same building is shown with a green door and a yellow and white striped awning, maintaining the peaceful atmosphere. contrasting with the detailed coastal setting, the video caption suggests a group of people sitting at a table with food and drinks, which does not align with the visual content described in the frames.
data/test_i2v/captions/000002012796.6.001.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A whimsical, nautical-themed interior with wooden cabinetry and a central mural of a pirate scene. initially, the room is adorned with a ship's wheel, a compass rose, and a framed picture of a ship, all under a warm, inviting light. at the two-second mark, the scene shifts to a corridor with wooden paneling, round portholes, and a framed picture of a shipwreck, with a solitary figure standing in the distance. by the fourth second, the setting changes to a warmly lit bar area with wooden tables, red stools, and a maritime-themed mural, creating a cozy atmosphere.
data/test_i2v/captions/000003031893.11.003.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A muscular, tattooed man with a black cap and red shorts is seen performing bicep curls with a white dumbbell at a gym, his reflection visible in a large mirror. the gym is equipped with various weights and exercise machines, set against wooden walls and flooring, creating a warm atmosphere. two seconds later, the same man, now in a black tank top, continues his workout with a barbell on a bench, surrounded by a mirror reflecting the gym's interior, including a treadmill and weight racks, all under warm lighting. contrary to the detailed scenes, the overall description inaccurately mentions a shirtless man standing in front of a refrigerator.
data/test_i2v/masked_videos/000000000005.2.013.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e26c4e1563e7e7963a180408468e377f48cf6a0c9639c60abe7d97d794798304
3
+ size 494333
data/test_i2v/masked_videos/000000000793.0.003.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1010d8cd07b77aaf14ee10a86f75916d8cc501aaf8fad6d4cf0b196dfb0f083
3
+ size 321633
data/test_i2v/masked_videos/000000000896.2.005.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebe76f05ad108e42d9a668cf3f08f0965f10dbf5f7f755b9dc4b13b4ccc9cd03
3
+ size 1168624
data/test_i2v/masked_videos/000000001059.6.004.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d37c98497b103552cde6355e186bf7be0d9fbd18029d512af76c6df3a54f2c9c
3
+ size 304053
data/test_i2v/masked_videos/000000049282.4.005.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:966ba1cf67689feafc6e3964041c7282957ee3bb8032116b9e58e3d11a52804f
3
+ size 402082
data/test_i2v/masked_videos/000000049768.11.002.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7c8d5ae12acbe72000b14741a645df14b3309f4a16854061e1b68cb2f30ae50
3
+ size 1076475
data/test_i2v/masked_videos/000002012796.6.001.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ab4d4bee407c6f86a5d4188c3679bee832f070388a251e2d4629fd6d7e6250d
3
+ size 157999
data/test_i2v/masked_videos/000003031893.11.003.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb7d9beb34ff81afd97834b3322a90ec6a28ac351be4211b78636b7b74300f7e
3
+ size 171900
data/test_i2v/masks/000000000005.2.013.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f088f95b36218a7cc33406b77783b7913afed9213b2ee73d80c23caab5d464a6
3
+ size 441136
data/test_i2v/masks/000000000793.0.003.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b37b20f2b1e3fe3843bb145c3279aa414018bb167ba28fc54e1a9bc5eed975b
3
+ size 205096
data/test_i2v/masks/000000000896.2.005.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf449ba298632f7d2a811e15e5dbabbbaec3c2301e7ba70021afd42ad90831e3
3
+ size 691623
data/test_i2v/masks/000000001059.6.004.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d03d4c6877ffbc1a6fb49fb59d9f5f1098d96bc1f7d73829768760fac3a7bf99
3
+ size 148122
data/test_i2v/masks/000000049282.4.005.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ded019f277286353c850f08c49a94b70887e0ea71607c6eb8959b79739ecb924
3
+ size 214608
data/test_i2v/masks/000000049768.11.002.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fe0878aee08cc545f6b717515f142cb9299813ce3d89b4e64c5b2c7a6a2a708
3
+ size 590769
data/test_i2v/masks/000002012796.6.001.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1951d5c5fdec649a59e569e3309398fb311745ed72930e8e720a5699208c4c4
3
+ size 169341
data/test_i2v/masks/000003031893.11.003.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d79e7b6e102b7adcc5ddaafafa0c66e67c4efe81a0f7f9f1270cd17b66a193f
3
+ size 158881
data/test_i2v/videos/000000000005.2.013.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a385d5f2066dacaf38a6819cb8594e1b44ca25574c23cc5e67d7a039b9309ef2
3
+ size 575154
data/test_i2v/videos/000000000793.0.003.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e51cb421efeb29dfc0ddf93a01a7e8dea822b6ed1ae3ee53e94120170f4fad0
3
+ size 757391
data/test_i2v/videos/000000000896.2.005.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32bd466321a25326e6c01c22d4342fbc9e2180609092d5ddc5f6b91b07929dda
3
+ size 1349710
data/test_i2v/videos/000000001059.6.004.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f660782c05b937e2ec08834e76778818049a04d30c0617e538018528ab49bc73
3
+ size 797266
data/test_i2v/videos/000000049282.4.005.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8f7c03191429649a4a23a503db089c6a864b2e4ae0418c8431ea9159954e460
3
+ size 1177012
data/test_i2v/videos/000000049768.11.002.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b66d0e0729d314bb275297d27a2b6e073962d70cd6cf1d5caac20bf10adc254
3
+ size 909919
data/test_i2v/videos/000002012796.6.001.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7e8b1ab3ca836e70e3386ca26658dcd74df503952cace96ae1a9743b3af44f4
3
+ size 446478
data/test_i2v/videos/000003031893.11.003.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26e186da08e186ad578a68da4bb0b376049e51f0039a302b63e0b2f4c9a25685
3
+ size 506332
data/test_v2v/captions/amalfi-coast_traj_loop2.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ The video showcases an aerial view of a historic coastal structure perched on a cliff overlooking the sea. The architecture features a mix of stone and brick, with arched doorways and windows, and a prominent dome on one side. The surrounding area includes a large open plaza where people are gathered, some walking and others sitting, enjoying the scenic view. The coastline is rugged, with rocky outcrops jutting into the deep blue water below. In the background, there are more buildings and structures, indicating a nearby town or village. The overall scene is bathed in warm sunlight, highlighting the textures of the stone and the vibrant colors of. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/art-museum_gradual_0_-30_0.0_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ The video showcases an art gallery with a spacious, well-lit interior featuring polished wooden floors arranged in a herringbone pattern. The walls are adorned with a variety of framed paintings, each with distinct styles and subjects. On the left side, there are landscapes and abstract artworks, while the right side displays more traditional portraits and historical scenes. The ceiling is ornate, with intricate designs and recessed lighting that highlights the artwork. The gallery appears to be empty, allowing the viewer to focus solely on the art pieces and the elegant architecture of the space.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/dog_gradual_0_-30_-0.6_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A small, light brown puppy with floppy ears sits on a speckled carpet in front of a window with sheer curtains. The puppy looks around curiously, its head tilting slightly as it takes in its surroundings. The soft, natural light from the window illuminates the scene, creating a warm and cozy atmosphere. The puppy's expression is one of innocent curiosity, adding to the charm of the moment.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/fish_gradual_25_0_0.0_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A vibrant blue and yellow striped fish, resembling an angelfish, swims gracefully among rocky formations in what appears to be an aquarium setting. The fish's flowing fins and the intricate patterns on its body are highlighted by the underwater lighting, creating a serene and captivating scene. The background consists of large, rugged rocks that add texture and depth to the environment, enhancing the naturalistic feel of the habitat.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/grandma-birthday_gradual_0_0_0.2_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A joyful celebration unfolds as an elderly woman stands at a table, her face lit up with excitement and anticipation. In front of her is a beautifully decorated birthday cake adorned with numerous candles in shades of pink and yellow. The woman leans forward, her eyes sparkling with delight, as she prepares to blow out the candles. Surrounding her are several people, including family members and friends, who are clapping and cheering enthusiastically. The atmosphere is warm and festive, filled with laughter and happiness as everyone shares in the moment of joy.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/happy-cat_gradual_-20_0_0.0_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A fluffy orange and white cat with striking green eyes is seen walking through a lush garden. The path is lined with vibrant green foliage and dotted with small yellow flowers. The cat moves gracefully, its paws padding softly on the earthy ground. As it walks, the camera follows closely behind, capturing the serene beauty of the garden and the curious nature of the feline. The sunlight filters through the leaves, casting dappled shadows that dance across the scene, adding to the tranquil atmosphere.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/suv-in-the-dust_gradual_0_30_0.0_0_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A white off-road vehicle is seen driving along a winding dirt road in a mountainous, forested area. The terrain is rugged and uneven, with the vehicle kicking up dust as it maneuvers through the curves. The surrounding landscape features dense trees and shrubs, with patches of exposed earth and rocks. The sky above is clear and blue, indicating a sunny day. The vehicle's shadow stretches long on the ground, suggesting the sun is high in the sky. The overall scene conveys a sense of adventure and exploration in a remote, natural setting.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/captions/vlogger-corgi_traj_loop2.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A corgi dog is sitting on a vibrant blue beach towel adorned with yellow floral patterns, positioned on a sandy beach. The dog is wearing stylish sunglasses and a colorful lei around its neck, giving it a festive and playful appearance. A GoPro camera mounted on a selfie stick is pointed towards the dog, suggesting that it might be recording a video or taking photos. In the background, tall palm trees sway gently in the breeze, and the ocean stretches out to meet the horizon under a clear blue sky. The scene exudes a relaxed and joyful atmosphere, perfect for a day at the beach.. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.
data/test_v2v/masked_videos/amalfi-coast_traj_loop2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a88a29ce9e47e9f5c78222721f0adc5c5f7098f90c7371f3859d8742513f8ed
3
+ size 752999
data/test_v2v/masked_videos/art-museum_gradual_0_-30_0.0_0_0.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa32d57497c1ded042b4e7944f07b15828d2a3199db79f94c0c670f846dbde88
3
+ size 442795
data/test_v2v/masked_videos/dog_gradual_0_-30_-0.6_0_0.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be94b77bd5367476198b3e0758614e8ef672b8d6ae8bcd451a005980d43e3ffe
3
+ size 334957
data/test_v2v/masked_videos/fish_gradual_25_0_0.0_0_0.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3875bc6b8ebc9cf35dc77625004b63d1ec816aca1e6133cea42664ef49f2a673
3
+ size 675659