roll-ai commited on
Commit
b14067d
·
verified ·
1 Parent(s): 15100e0

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