├── .gitignore ├── DiT ├── __init__.py ├── model.py ├── utils.py └── vae.py ├── LICENSE.txt ├── README.md ├── __assets__ ├── demos │ ├── demo_1 │ │ ├── first_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_1.jpg │ │ ├── layer_2.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory.json │ │ └── trajectory.npz │ ├── demo_2 │ │ ├── first_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_1.jpg │ │ ├── layer_2.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory.json │ │ └── trajectory.npz │ ├── demo_3 │ │ ├── first_frame.jpg │ │ ├── last_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_0_last.jpg │ │ ├── layer_1.jpg │ │ ├── layer_1_last.jpg │ │ ├── layer_2.jpg │ │ ├── layer_2_last.jpg │ │ ├── layer_3.jpg │ │ ├── layer_3_last.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory.json │ │ └── trajectory.npz │ ├── demo_4 │ │ ├── first_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_1.jpg │ │ ├── layer_2.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory.json │ │ └── trajectory.npz │ ├── demo_5 │ │ ├── first_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_1.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory.json │ │ └── trajectory.npz │ └── realworld │ │ ├── config.yaml │ │ ├── first_frame.jpg │ │ ├── layer_0.jpg │ │ ├── layer_1.jpg │ │ ├── layer_2.jpg │ │ ├── sketch.mp4 │ │ ├── trajectory_bg.json │ │ └── trajectory_dog.json └── figs │ └── demos.gif ├── lineart ├── LICENSE └── __init__.py ├── lvdm ├── basics.py ├── common.py ├── data │ └── dataset.py ├── models │ ├── autoencoder.py │ ├── condition.py │ ├── controlnet.py │ ├── layer_controlnet.py │ └── unet.py ├── modules │ ├── ae_dualref_modules.py │ ├── ae_modules.py │ ├── attention.py │ └── attention_svd.py ├── pipelines │ └── pipeline_animation.py └── utils.py ├── requirements.txt └── scripts ├── animate_Layer.py ├── app.py ├── demo1.yaml ├── demo2.yaml ├── demo3.yaml ├── demo4.yaml ├── demo5.yaml └── infer_DiT.py /.gitignore: -------------------------------------------------------------------------------- 1 | wandb/ 2 | *debug* 3 | debugs/ 4 | outputs/ 5 | samples/ 6 | __pycache__/ 7 | 8 | *.ipynb 9 | *.safetensors 10 | *.ckpt 11 | *.pth 12 | /data 13 | /vis 14 | /checkpoints 15 | -------------------------------------------------------------------------------- /DiT/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IamCreateAI/LayerAnimate/bb8417c519a4a130ad70b49d2990a89b4b6eed72/DiT/__init__.py -------------------------------------------------------------------------------- /DiT/model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (c) Alibaba, Inc. and its affiliates. 3 | import torch 4 | import torch.nn as nn 5 | from typing import Any, Dict 6 | from diffusers import __version__ 7 | from diffusers.configuration_utils import register_to_config 8 | from diffusers.utils import ( 9 | SAFETENSORS_WEIGHTS_NAME, 10 | WEIGHTS_NAME, 11 | logging, 12 | is_torch_version, 13 | _get_model_file, 14 | _add_variant 15 | ) 16 | from diffusers.models.model_loading_utils import load_state_dict 17 | from wan.modules.model import WanModel, WanAttentionBlock, sinusoidal_embedding_1d 18 | from omegaconf import ListConfig, DictConfig, OmegaConf 19 | 20 | 21 | logger = logging.get_logger(__name__) # pylint: disable=invalid-name 22 | 23 | 24 | class VaceWanAttentionBlock(WanAttentionBlock): 25 | def __init__( 26 | self, 27 | cross_attn_type, 28 | dim, 29 | ffn_dim, 30 | num_heads, 31 | window_size=(-1, -1), 32 | qk_norm=True, 33 | cross_attn_norm=False, 34 | eps=1e-6, 35 | block_id=0 36 | ): 37 | super().__init__(cross_attn_type, dim, ffn_dim, num_heads, window_size, qk_norm, cross_attn_norm, eps) 38 | self.block_id = block_id 39 | if block_id == 0: 40 | self.before_proj = nn.Linear(self.dim, self.dim) 41 | nn.init.zeros_(self.before_proj.weight) 42 | nn.init.zeros_(self.before_proj.bias) 43 | self.after_proj = nn.Linear(self.dim, self.dim) 44 | nn.init.zeros_(self.after_proj.weight) 45 | nn.init.zeros_(self.after_proj.bias) 46 | 47 | def forward(self, c, x, **kwargs): 48 | if self.block_id == 0: 49 | c = self.before_proj(c) + x 50 | all_c = [] 51 | else: 52 | all_c = list(torch.unbind(c)) 53 | c = all_c.pop(-1) 54 | c = super().forward(c, **kwargs) 55 | c_skip = self.after_proj(c) 56 | all_c += [c_skip, c] 57 | c = torch.stack(all_c) 58 | return c 59 | 60 | 61 | class BaseWanAttentionBlock(WanAttentionBlock): 62 | def __init__( 63 | self, 64 | cross_attn_type, 65 | dim, 66 | ffn_dim, 67 | num_heads, 68 | window_size=(-1, -1), 69 | qk_norm=True, 70 | cross_attn_norm=False, 71 | eps=1e-6, 72 | block_id=None 73 | ): 74 | super().__init__(cross_attn_type, dim, ffn_dim, num_heads, window_size, qk_norm, cross_attn_norm, eps) 75 | self.block_id = block_id 76 | 77 | def forward(self, x, hints, context_scale=1.0, **kwargs): 78 | x = super().forward(x, **kwargs) 79 | if self.block_id is not None: 80 | x = x + hints[self.block_id] * context_scale 81 | return x 82 | 83 | 84 | class VaceWanModel(WanModel): 85 | _supports_gradient_checkpointing = True 86 | 87 | @register_to_config 88 | def __init__(self, 89 | vace_layers=None, 90 | vace_in_dim=None, 91 | model_type='t2v', 92 | patch_size=(1, 2, 2), 93 | text_len=512, 94 | in_dim=16, 95 | dim=2048, 96 | ffn_dim=8192, 97 | freq_dim=256, 98 | text_dim=4096, 99 | out_dim=16, 100 | num_heads=16, 101 | num_layers=32, 102 | window_size=(-1, -1), 103 | qk_norm=True, 104 | cross_attn_norm=True, 105 | eps=1e-6): 106 | super().__init__(model_type, patch_size, text_len, in_dim, dim, ffn_dim, freq_dim, text_dim, out_dim, 107 | num_heads, num_layers, window_size, qk_norm, cross_attn_norm, eps) 108 | 109 | self.vace_layers = [i for i in range(0, self.num_layers, 2)] if vace_layers is None else vace_layers 110 | self.vace_in_dim = self.in_dim if vace_in_dim is None else vace_in_dim 111 | 112 | assert 0 in self.vace_layers 113 | self.vace_layers_mapping = {i: n for n, i in enumerate(self.vace_layers)} 114 | 115 | # blocks 116 | self.blocks = nn.ModuleList([ 117 | BaseWanAttentionBlock('t2v_cross_attn', self.dim, self.ffn_dim, self.num_heads, self.window_size, self.qk_norm, 118 | self.cross_attn_norm, self.eps, 119 | block_id=self.vace_layers_mapping[i] if i in self.vace_layers else None) 120 | for i in range(self.num_layers) 121 | ]) 122 | 123 | # vace blocks 124 | self.vace_blocks = nn.ModuleList([ 125 | VaceWanAttentionBlock('t2v_cross_attn', self.dim, self.ffn_dim, self.num_heads, self.window_size, self.qk_norm, 126 | self.cross_attn_norm, self.eps, block_id=i) 127 | for i in self.vace_layers 128 | ]) 129 | 130 | # vace patch embeddings 131 | self.vace_patch_embedding = nn.Conv3d( 132 | self.vace_in_dim, self.dim, kernel_size=self.patch_size, stride=self.patch_size 133 | ) 134 | 135 | self.gradient_checkpointing = False 136 | 137 | def _set_gradient_checkpointing(self, module, value=False): 138 | self.gradient_checkpointing = value 139 | 140 | def forward_vace( 141 | self, 142 | x, 143 | vace_context, 144 | seq_len, 145 | kwargs 146 | ): 147 | # embeddings 148 | c = [self.vace_patch_embedding(u.unsqueeze(0)) for u in vace_context] 149 | c = [u.flatten(2).transpose(1, 2) for u in c] 150 | c = torch.cat([ 151 | torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))], 152 | dim=1) for u in c 153 | ]) 154 | 155 | # arguments 156 | new_kwargs = dict(x=x) 157 | new_kwargs.update(kwargs) 158 | 159 | for block in self.vace_blocks: 160 | if self.training and self.gradient_checkpointing: 161 | 162 | def create_custom_forward(module): 163 | def custom_forward(*inputs, **kwargs): 164 | return module(*inputs, **kwargs) 165 | 166 | return custom_forward 167 | ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} 168 | new_kwargs.update(ckpt_kwargs) 169 | c = torch.utils.checkpoint.checkpoint(create_custom_forward(block), c, **new_kwargs) 170 | else: 171 | c = block(c, **new_kwargs) 172 | hints = torch.unbind(c)[:-1] 173 | return hints 174 | 175 | def forward( 176 | self, 177 | x, 178 | t, 179 | vace_context, 180 | context, 181 | seq_len, 182 | vace_context_scale=1.0, 183 | clip_fea=None, 184 | y=None, 185 | ): 186 | r""" 187 | Forward pass through the diffusion model 188 | 189 | Args: 190 | x (List[Tensor]): 191 | List of input video tensors, each with shape [C_in, F, H, W] 192 | t (Tensor): 193 | Diffusion timesteps tensor of shape [B] 194 | context (List[Tensor]): 195 | List of text embeddings each with shape [L, C] 196 | seq_len (`int`): 197 | Maximum sequence length for positional encoding 198 | clip_fea (Tensor, *optional*): 199 | CLIP image features for image-to-video mode 200 | y (List[Tensor], *optional*): 201 | Conditional video inputs for image-to-video mode, same shape as x 202 | 203 | Returns: 204 | List[Tensor]: 205 | List of denoised video tensors with original input shapes [C_out, F, H / 8, W / 8] 206 | """ 207 | # if self.model_type == 'i2v': 208 | # assert clip_fea is not None and y is not None 209 | # params 210 | device = self.patch_embedding.weight.device 211 | if self.freqs.device != device: 212 | self.freqs = self.freqs.to(device) 213 | 214 | # if y is not None: 215 | # x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)] 216 | 217 | # embeddings 218 | x = [self.patch_embedding(u.unsqueeze(0)) for u in x] 219 | grid_sizes = torch.stack( 220 | [torch.tensor(u.shape[2:], dtype=torch.long) for u in x]) 221 | x = [u.flatten(2).transpose(1, 2) for u in x] 222 | seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long) 223 | assert seq_lens.max() <= seq_len 224 | x = torch.cat([ 225 | torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))], 226 | dim=1) for u in x 227 | ]) 228 | 229 | # time embeddings 230 | with torch.amp.autocast('cuda', dtype=torch.float32): 231 | e = self.time_embedding( 232 | sinusoidal_embedding_1d(self.freq_dim, t).float()) 233 | e0 = self.time_projection(e).unflatten(1, (6, self.dim)) 234 | assert e.dtype == torch.float32 and e0.dtype == torch.float32 235 | 236 | # context 237 | context_lens = None 238 | context = self.text_embedding( 239 | torch.stack([ 240 | torch.cat( 241 | [u, u.new_zeros(self.text_len - u.size(0), u.size(1))]) 242 | for u in context 243 | ])) 244 | 245 | # if clip_fea is not None: 246 | # context_clip = self.img_emb(clip_fea) # bs x 257 x dim 247 | # context = torch.concat([context_clip, context], dim=1) 248 | 249 | # arguments 250 | kwargs = dict( 251 | e=e0, 252 | seq_lens=seq_lens, 253 | grid_sizes=grid_sizes, 254 | freqs=self.freqs, 255 | context=context, 256 | context_lens=context_lens) 257 | 258 | hints = self.forward_vace(x, vace_context, seq_len, kwargs) 259 | kwargs['hints'] = hints 260 | kwargs['context_scale'] = vace_context_scale 261 | 262 | for block in self.blocks: 263 | if self.training and self.gradient_checkpointing: 264 | 265 | def create_custom_forward(module): 266 | def custom_forward(*inputs, **kwargs): 267 | return module(*inputs, **kwargs) 268 | 269 | return custom_forward 270 | ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} 271 | kwargs.update(ckpt_kwargs) 272 | x = torch.utils.checkpoint.checkpoint(create_custom_forward(block), x, **kwargs) 273 | else: 274 | x = block(x, **kwargs) 275 | 276 | # head 277 | x = self.head(x, e) 278 | 279 | # unpatchify 280 | x = self.unpatchify(x, grid_sizes) 281 | x = torch.stack(x) 282 | return x 283 | 284 | @classmethod 285 | def from_pretrained(cls, pretrained_model_name_or_path, model_additional_kwargs={}, **kwargs): 286 | cache_dir = kwargs.pop("cache_dir", None) 287 | force_download = kwargs.pop("force_download", False) 288 | proxies = kwargs.pop("proxies", None) 289 | local_files_only = kwargs.pop("local_files_only", None) 290 | token = kwargs.pop("token", None) 291 | revision = kwargs.pop("revision", None) 292 | subfolder = kwargs.pop("subfolder", None) 293 | variant = kwargs.pop("variant", None) 294 | use_safetensors = kwargs.pop("use_safetensors", None) 295 | 296 | allow_pickle = False 297 | if use_safetensors is None: 298 | use_safetensors = True 299 | allow_pickle = True 300 | 301 | # Load config if we don't provide a configuration 302 | config_path = pretrained_model_name_or_path 303 | 304 | user_agent = { 305 | "diffusers": __version__, 306 | "file_type": "model", 307 | "framework": "pytorch", 308 | } 309 | 310 | # load config 311 | config, unused_kwargs, commit_hash = cls.load_config( 312 | config_path, 313 | cache_dir=cache_dir, 314 | return_unused_kwargs=True, 315 | return_commit_hash=True, 316 | force_download=force_download, 317 | proxies=proxies, 318 | local_files_only=local_files_only, 319 | token=token, 320 | revision=revision, 321 | subfolder=subfolder, 322 | user_agent=user_agent, 323 | **kwargs, 324 | ) 325 | 326 | for key, value in model_additional_kwargs.items(): 327 | if isinstance(value, (ListConfig, DictConfig)): 328 | config[key] = OmegaConf.to_container(value, resolve=True) 329 | else: 330 | config[key] = value 331 | 332 | # load model 333 | model_file = None 334 | if use_safetensors: 335 | try: 336 | model_file = _get_model_file( 337 | pretrained_model_name_or_path, 338 | weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant), 339 | cache_dir=cache_dir, 340 | force_download=force_download, 341 | proxies=proxies, 342 | local_files_only=local_files_only, 343 | token=token, 344 | revision=revision, 345 | subfolder=subfolder, 346 | user_agent=user_agent, 347 | commit_hash=commit_hash, 348 | ) 349 | 350 | except IOError as e: 351 | logger.error(f"An error occurred while trying to fetch {pretrained_model_name_or_path}: {e}") 352 | if not allow_pickle: 353 | raise 354 | logger.warning( 355 | "Defaulting to unsafe serialization. Pass `allow_pickle=False` to raise an error instead." 356 | ) 357 | 358 | if model_file is None: 359 | model_file = _get_model_file( 360 | pretrained_model_name_or_path, 361 | weights_name=_add_variant(WEIGHTS_NAME, variant), 362 | cache_dir=cache_dir, 363 | force_download=force_download, 364 | proxies=proxies, 365 | local_files_only=local_files_only, 366 | token=token, 367 | revision=revision, 368 | subfolder=subfolder, 369 | user_agent=user_agent, 370 | commit_hash=commit_hash, 371 | ) 372 | 373 | model = cls.from_config(config, **unused_kwargs) 374 | state_dict = load_state_dict(model_file, variant) 375 | 376 | if state_dict['vace_patch_embedding.weight'].shape[1] != model.vace_patch_embedding.weight.shape[1]: 377 | state_dict.pop('vace_patch_embedding.weight') 378 | 379 | missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False) 380 | print(f"VaceWanModel loaded from {model_file} with {len(missing_keys)} missing keys and {len(unexpected_keys)} unexpected keys.") 381 | return model -------------------------------------------------------------------------------- /DiT/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import torch 4 | import os 5 | from einops import rearrange 6 | import imageio 7 | import torchvision 8 | 9 | 10 | def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8): 11 | videos = rearrange(videos, "b c t h w -> t b c h w") 12 | outputs = [] 13 | for x in videos: 14 | x = torchvision.utils.make_grid(x, nrow=n_rows) 15 | x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) 16 | if rescale: 17 | x = (x + 1.0) / 2.0 # -1,1 -> 0,1 18 | x = (x * 255).numpy().astype(np.uint8) 19 | outputs.append(x) 20 | 21 | os.makedirs(os.path.dirname(path), exist_ok=True) 22 | imageio.mimsave(path, outputs, fps=fps) 23 | 24 | 25 | def save_videos_with_traj(videos: torch.Tensor, trajectory: torch.Tensor, path: str, rescale=False, fps=8, line_width=7, circle_radius=10): 26 | # videos: [C, F, H, W] 27 | # trajectory: [F, N, 2] 28 | os.makedirs(os.path.dirname(path), exist_ok=True) 29 | videos = rearrange(videos, "c f h w -> f h w c") 30 | if rescale: 31 | videos = (videos + 1) / 2 32 | videos = (videos * 255).numpy().astype(np.uint8) 33 | outputs = [] 34 | for frame_idx, img in enumerate(videos): 35 | # img: [H, W, C], traj: [N, 2] 36 | # draw trajectory use cv2.line 37 | img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) 38 | for traj_idx in range(trajectory.shape[1]): 39 | for history_idx in range(frame_idx): 40 | cv2.line(img, tuple(trajectory[history_idx, traj_idx].int().tolist()), tuple(trajectory[history_idx+1, traj_idx].int().tolist()), (0, 0, 255), line_width) 41 | cv2.circle(img, tuple(trajectory[frame_idx, traj_idx].int().tolist()), circle_radius, (100, 230, 160), -1) 42 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 43 | outputs.append(img) 44 | imageio.mimsave(path, outputs, fps=fps) 45 | 46 | 47 | def generate_gaussian_template(imgSize=200): 48 | """ Adapted from DragAnything: https://github.com/showlab/DragAnything/blob/79355363218a7eb9b3437a31b8604b6d436d9337/dataset/dataset.py#L110""" 49 | circle_img = np.zeros((imgSize, imgSize), np.float32) 50 | circle_mask = cv2.circle(circle_img, (imgSize//2, imgSize//2), imgSize//2, 1, -1) 51 | 52 | isotropicGrayscaleImage = np.zeros((imgSize, imgSize), np.float32) 53 | 54 | # Guass Map 55 | for i in range(imgSize): 56 | for j in range(imgSize): 57 | isotropicGrayscaleImage[i, j] = 1 / 2 / np.pi / (40 ** 2) * np.exp( 58 | -1 / 2 * ((i - imgSize / 2) ** 2 / (40 ** 2) + (j - imgSize / 2) ** 2 / (40 ** 2))) 59 | 60 | isotropicGrayscaleImage = isotropicGrayscaleImage * circle_mask 61 | isotropicGrayscaleImage = (isotropicGrayscaleImage / np.max(isotropicGrayscaleImage)).astype(np.float32) 62 | isotropicGrayscaleImage = (isotropicGrayscaleImage / np.max(isotropicGrayscaleImage)*255).astype(np.uint8) 63 | 64 | # isotropicGrayscaleImage = cv2.resize(isotropicGrayscaleImage, (40, 40)) 65 | return isotropicGrayscaleImage 66 | 67 | 68 | def generate_gaussian_heatmap(tracks, width, height, layer_index, layer_capacity, side=20, offset=True): 69 | heatmap_template = generate_gaussian_template() 70 | num_frames, num_points = tracks.shape[:2] 71 | if isinstance(tracks, torch.Tensor): 72 | tracks = tracks.cpu().numpy() 73 | if offset: 74 | offset_kernel = cv2.resize(heatmap_template / 255, (2 * side + 1, 2 * side + 1)) 75 | offset_kernel /= np.sum(offset_kernel) 76 | offset_kernel /= offset_kernel[side, side] 77 | heatmaps = [] 78 | for frame_idx in range(num_frames): 79 | if offset: 80 | layer_imgs = np.zeros((layer_capacity, height, width, 3), dtype=np.float32) 81 | else: 82 | layer_imgs = np.zeros((layer_capacity, height, width, 1), dtype=np.float32) 83 | layer_heatmaps = [] 84 | for point_idx in range(num_points): 85 | x, y = tracks[frame_idx, point_idx] 86 | layer_id = layer_index[point_idx] 87 | if x < 0 or y < 0 or x >= width or y >= height: 88 | continue 89 | x1 = int(max(x - side, 0)) 90 | x2 = int(min(x + side, width - 1)) 91 | y1 = int(max(y - side, 0)) 92 | y2 = int(min(y + side, height - 1)) 93 | if (x2 - x1) < 1 or (y2 - y1) < 1: 94 | continue 95 | temp_map = cv2.resize(heatmap_template, (x2-x1, y2-y1)) 96 | layer_imgs[layer_id, y1:y2,x1:x2, 0] = np.maximum(layer_imgs[layer_id, y1:y2,x1:x2, 0], temp_map) 97 | if offset: 98 | if frame_idx < (num_frames - 1): 99 | next_x, next_y = tracks[frame_idx + 1, point_idx] 100 | else: 101 | next_x, next_y = x, y 102 | layer_imgs[layer_id, int(y), int(x), 1] = next_x - x 103 | layer_imgs[layer_id, int(y), int(x), 2] = next_y - y 104 | for img in layer_imgs: 105 | if offset: 106 | img[:, :, 1:] = cv2.filter2D(img[:, :, 1:], -1, offset_kernel) 107 | else: 108 | img = cv2.cvtColor(img[:, :, 0].astype(np.uint8), cv2.COLOR_GRAY2RGB) 109 | layer_heatmaps.append(img) 110 | heatmaps.append(np.stack(layer_heatmaps, axis=0)) 111 | heatmaps = np.stack(heatmaps, axis=0) 112 | return torch.from_numpy(heatmaps).permute(0, 1, 4, 2, 3).contiguous().float() # [F, N_layer, C, H, W] 113 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LayerAnimate: Layer-level Control for Animation 2 | 3 | [Yuxue Yang](https://yuxueyang1204.github.io/)1,2, [Lue Fan](https://lue.fan/)2, [Zuzeng Lin](https://www.researchgate.net/scientific-contributions/Zuzeng-Lin-2192777418)3, [Feng Wang](https://happynear.wang/)4, [Zhaoxiang Zhang](https://zhaoxiangzhang.net)1,2† 4 | 5 | 1UCAS  2CASIA  3TJU  4CreateAI  Corresponding author 6 | 7 |   8 |   9 |   10 |   11 |
12 | 13 | Official implementation of **LayerAnimate: Layer-level Control for Animation**, ICCV 2025 14 | 15 |
16 | 17 | **Videos on the [project website](https://layeranimate.github.io) vividly introduces our work and presents qualitative results for an enhanced view experience.** 18 | 19 | ## Updates 20 | 21 | - [25-08-22] Release the [Layer Curation Pipeline](https://github.com/YuxueYang1204/Layer-Curation-Pipeline), including the demo and comprehensive usage guidance. 22 | - [25-06-26] Our work is accepted by ICCV 2025! 🎉 23 | - [25-05-29] We have extended LayerAnimate to the DiT ([Wan2.1 1.3B](https://github.com/Wan-Video/Wan2.1)) variant, enabling the generation of 81 frames at 480 × 832 resolution. It performs surprisingly well in the [Real-World Domain](https://layeranimate.github.io/#real_world) shown in the project website. 24 | - [25-03-31] Release the online demo on [Hugging Face](https://huggingface.co/spaces/IamCreateAI/LayerAnimate). 25 | - [25-03-30] Release a gradio script [app.py](scripts/app.py) to run the demo locally. Please raise an issue if you encounter any problems. 26 | - [25-03-22] Release the checkpoint and the inference script. **We update layer curation pipeline and support trajectory control for a flexible composition of various layer-level controls.** 27 | - [25-01-15] Release the project page and the arXiv preprint. 28 | 29 | ## Layer curation pipeline 30 | 31 | We have released [a comprehensive pipeline](https://github.com/YuxueYang1204/Layer-Curation-Pipeline) for extracting motion-based layers from video sequences. The layer curation pipeline automatically decomposes videos into different layers based on motion patterns, where you can control the number of extracted layers by adjusting the layer capacity parameter to obtain varying levels of motion granularity. 32 | 33 | More details can be found in the [repo](https://github.com/YuxueYang1204/Layer-Curation-Pipeline). 34 | 35 | | Input Videos | Layer Results | 36 | |:--:|:--:| 37 | |