LPX55 commited on
Commit
10f65ab
·
verified ·
1 Parent(s): 117e1b1

Upload 4 files

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. README.md +31 -9
  3. i2v.sft +3 -0
  4. inference.py +299 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ i2v.sft filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,34 @@
1
  ---
2
- title: HunYuan Keyframe
3
- emoji: 🔥
4
- colorFrom: pink
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.22.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ base_model:
3
+ - tencent/HunyuanVideo
4
+ library_name: diffusers
 
 
 
 
 
5
  ---
6
 
7
+ HunyuanVideo Keyframe Control Lora is an adapter for HunyuanVideo T2V model for keyframe-based video generation. ​Our architecture builds upon existing models, introducing key enhancements to optimize keyframe-based video generation:​
8
+ * We modify the input patch embedding projection layer to effectively incorporate keyframe information. By adjusting the convolutional input parameters, we enable the model to process image inputs within the Diffusion Transformer (DiT) framework.​
9
+ * We apply Low-Rank Adaptation (LoRA) across all linear layers and the convolutional input layer. This approach facilitates efficient fine-tuning by introducing low-rank matrices that approximate the weight updates, thereby preserving the base model's foundational capabilities while reducing the number of trainable parameters.
10
+ * The model is conditioned on user-defined keyframes, allowing precise control over the generated video's start and end frames. This conditioning ensures that the generated content aligns seamlessly with the specified keyframes, enhancing the coherence and narrative flow of the video.​
11
+
12
+ | Image 1 | Image 2 | Generated Video |
13
+ |---------|---------|-----------------|
14
+ | ![Image 1](https://content.dashtoon.ai/stability-images/41aeca63-064a-4003-8c8b-bfe2cc80d275.png) | ![Image 2](https://content.dashtoon.ai/stability-images/28956177-3455-4b56-bb6c-73eacef323ca.png) | <video controls autoplay src="https://content.dashtoon.ai/stability-images/14b7dd1a-1f46-4c4c-b4ec-9d0f948712af.mp4"></video> |
15
+ | ![Image 1](https://content.dashtoon.ai/stability-images/ddabbf2f-4218-497b-8239-b7b882d93000.png) | ![Image 2](https://content.dashtoon.ai/stability-images/b603acba-40a4-44ba-aa26-ed79403df580.png) | <video controls autoplay src="https://content.dashtoon.ai/stability-images/b00ba193-b3b7-41a1-9bc1-9fdaceba6efa.mp4"></video> |
16
+ | ![Image 1](https://content.dashtoon.ai/stability-images/5298cf0c-0955-4568-935a-2fb66045f21d.png) | ![Image 2](https://content.dashtoon.ai/stability-images/722a4ea7-7092-4323-8e83-3f627e8fd7f8.png) | <video controls autoplay src="https://content.dashtoon.ai/stability-images/0cb84780-4fdf-4ecc-ab48-12e7e1055a39.mp4"></video> |
17
+ | ![Image 1](https://content.dashtoon.ai/stability-images/69d9a49f-95c0-4e85-bd49-14a039373c8b.png) | ![Image 2](https://content.dashtoon.ai/stability-images/0cef7fa9-e15a-48ec-9bd3-c61921181802.png) | <video controls autoplay src="https://content.dashtoon.ai/stability-images/ce12156f-0ac2-4d16-b489-37e85c61b5b2.mp4"></video> |
18
+
19
+ ## Code:
20
+ The tranining code can be found [here](https://github.com/dashtoon/hunyuan-video-keyframe-control-lora).
21
+
22
+ ## Recommended Settings
23
+ 1. The model works best on human subjects. Single subject images work slightly better.
24
+ 2. It is recommended to use the following image generation resolutions `720x1280`, `544x960`, `1280x720`, `960x544`.
25
+ 3. It is recommended to set frames from 33 upto 97. Can go upto 121 frames as well (but not tested much).
26
+ 4. Prompting helps a lot but works even without. The prompt can be as simple as just the name of the object you want to generate or can be detailed.
27
+ 5. `num_inference_steps` is recommended to be 50, but for fast results you can use 30 as well. Anything less than 30 is not recommended.
28
+
29
+ ## Diffusers
30
+ HunyuanVideo Keyframe Control Lora can be used directly from Diffusers. Install the latest version of Diffusers.
31
+
32
+
33
+ ## Inference
34
+ While the included `inference.py` script can be used to run inference. We would encourage folks to visit out [github repo](https://github.com/dashtoon/hunyuan-video-keyframe-control-lora/blob/main/hv_control_lora_inference.py) which contains a much optimized version of this inference script.
i2v.sft ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70064a591c3ffb300b3c0e16884ef495446d554e7a5c7e3749e42eddabf1cd1d
3
+ size 135
inference.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import safetensors.torch
2
+ import torchvision.transforms.v2 as transforms
3
+ import cv2
4
+ import torch
5
+ import numpy as np
6
+ from typing import List, Optional, Tuple, Union
7
+ from PIL import Image
8
+ from diffusers import HunyuanVideoPipeline, FlowMatchEulerDiscreteScheduler
9
+ from diffusers.models.transformers.transformer_hunyuan_video import HunyuanVideoPatchEmbed, HunyuanVideoTransformer3DModel
10
+ from diffusers.utils import export_to_video
11
+ from diffusers.models.attention import Attention
12
+ from diffusers.utils.state_dict_utils import convert_state_dict_to_diffusers, convert_unet_state_dict_to_peft
13
+ from peft import LoraConfig, get_peft_model_state_dict, set_peft_model_state_dict
14
+ from diffusers.models.embeddings import apply_rotary_emb
15
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
16
+ from diffusers.loaders import HunyuanVideoLoraLoaderMixin
17
+ from diffusers.models import AutoencoderKLHunyuanVideo, HunyuanVideoTransformer3DModel
18
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
19
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
20
+ from diffusers.utils.torch_utils import randn_tensor
21
+ from diffusers.video_processor import VideoProcessor
22
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
23
+ from diffusers.pipelines.hunyuan_video.pipeline_output import HunyuanVideoPipelineOutput
24
+ from diffusers.pipelines.hunyuan_video.pipeline_hunyuan_video import retrieve_timesteps, DEFAULT_PROMPT_TEMPLATE
25
+ from diffusers.utils import load_image
26
+
27
+ video_transforms = transforms.Compose(
28
+ [
29
+ transforms.Lambda(lambda x: x / 255.0),
30
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
31
+ ]
32
+ )
33
+
34
+
35
+ def resize_image_to_bucket(image: Union[Image.Image, np.ndarray], bucket_reso: tuple[int, int]) -> np.ndarray:
36
+ """
37
+ Resize the image to the bucket resolution.
38
+ """
39
+ is_pil_image = isinstance(image, Image.Image)
40
+ if is_pil_image:
41
+ image_width, image_height = image.size
42
+ else:
43
+ image_height, image_width = image.shape[:2]
44
+
45
+ if bucket_reso == (image_width, image_height):
46
+ return np.array(image) if is_pil_image else image
47
+
48
+ bucket_width, bucket_height = bucket_reso
49
+
50
+ scale_width = bucket_width / image_width
51
+ scale_height = bucket_height / image_height
52
+ scale = max(scale_width, scale_height)
53
+ image_width = int(image_width * scale + 0.5)
54
+ image_height = int(image_height * scale + 0.5)
55
+
56
+ if scale > 1:
57
+ image = Image.fromarray(image) if not is_pil_image else image
58
+ image = image.resize((image_width, image_height), Image.LANCZOS)
59
+ image = np.array(image)
60
+ else:
61
+ image = np.array(image) if is_pil_image else image
62
+ image = cv2.resize(image, (image_width, image_height), interpolation=cv2.INTER_AREA)
63
+
64
+ # crop the image to the bucket resolution
65
+ crop_left = (image_width - bucket_width) // 2
66
+ crop_top = (image_height - bucket_height) // 2
67
+ image = image[crop_top : crop_top + bucket_height, crop_left : crop_left + bucket_width]
68
+
69
+ return image
70
+
71
+
72
+ model_id = "hunyuanvideo-community/HunyuanVideo"
73
+ transformer = HunyuanVideoTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16)
74
+ pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.bfloat16)
75
+
76
+ # Enable memory savings
77
+ pipe.vae.enable_tiling()
78
+ pipe.enable_model_cpu_offload()
79
+ pipe.enable_model_cpu_offload()
80
+
81
+ with torch.no_grad(): # enable image inputs
82
+ initial_input_channels = pipe.transformer.config.in_channels
83
+ new_img_in = HunyuanVideoPatchEmbed(
84
+ patch_size=(pipe.transformer.config.patch_size_t, pipe.transformer.config.patch_size, pipe.transformer.config.patch_size),
85
+ in_chans=pipe.transformer.config.in_channels * 2,
86
+ embed_dim=pipe.transformer.config.num_attention_heads * pipe.transformer.config.attention_head_dim,
87
+ )
88
+ new_img_in = new_img_in.to(pipe.device, dtype=pipe.dtype)
89
+ new_img_in.proj.weight.zero_()
90
+ new_img_in.proj.weight[:, :initial_input_channels].copy_(pipe.transformer.x_embedder.proj.weight)
91
+
92
+ if pipe.transformer.x_embedder.proj.bias is not None:
93
+ new_img_in.proj.bias.copy_(pipe.transformer.x_embedder.proj.bias)
94
+
95
+ pipe.transformer.x_embedder = new_img_in
96
+
97
+ LORA_PATH = "<PATH TO CONTROL LORA>"
98
+ lora_state_dict = pipe.lora_state_dict(LORA_PATH)
99
+ transformer_lora_state_dict = {f'{k.replace("transformer.", "")}': v for k, v in lora_state_dict.items() if k.startswith("transformer.") and "lora" in k}
100
+ pipe.load_lora_into_transformer(transformer_lora_state_dict, transformer=pipe.transformer, adapter_name="i2v", _pipeline=pipe)
101
+ pipe.set_adapters(["i2v"], adapter_weights=[1.0])
102
+ pipe.fuse_lora(components=["transformer"], lora_scale=1.0, adapter_names=["i2v"])
103
+ pipe.unload_lora_weights()
104
+
105
+ n_frames, height, width = 77, 1280, 720
106
+ prompt = "a woman"
107
+ cond_frame1 = load_image("https://content.dashtoon.ai/stability-images/e524013d-55d4-483a-b80a-dfc51d639158.png")
108
+ cond_frame1 = resize_image_to_bucket(cond_frame1, bucket_reso=(width, height))
109
+
110
+ cond_frame2 = load_image("https://content.dashtoon.ai/stability-images/0b29c296-0a90-4b92-96b9-1ed0ae21e480.png")
111
+ cond_frame2 = resize_image_to_bucket(cond_frame2, bucket_reso=(width, height))
112
+
113
+ cond_video = np.zeros(shape=(n_frames, height, width, 3))
114
+ cond_video[0], cond_video[-1] = np.array(cond_frame1), np.array(cond_frame2)
115
+
116
+ cond_video = torch.from_numpy(cond_video.copy()).permute(0, 3, 1, 2)
117
+ cond_video = torch.stack([video_transforms(x) for x in cond_video], dim=0).unsqueeze(0)
118
+
119
+ with torch.inference_mode():
120
+ image_or_video = cond_video.to(device="cuda", dtype=pipe.dtype)
121
+ image_or_video = image_or_video.permute(0, 2, 1, 3, 4).contiguous() # [B, F, C, H, W] -> [B, C, F, H, W]
122
+ cond_latents = pipe.vae.encode(image_or_video).latent_dist.sample()
123
+ cond_latents = cond_latents * pipe.vae.config.scaling_factor
124
+ cond_latents = cond_latents.to(dtype=pipe.dtype)
125
+ assert not torch.any(torch.isnan(cond_latents))
126
+
127
+
128
+ @torch.inference_mode()
129
+ def call_pipe(
130
+ pipe,
131
+ prompt: Union[str, List[str]] = None,
132
+ prompt_2: Union[str, List[str]] = None,
133
+ height: int = 720,
134
+ width: int = 1280,
135
+ num_frames: int = 129,
136
+ num_inference_steps: int = 50,
137
+ sigmas: List[float] = None,
138
+ guidance_scale: float = 6.0,
139
+ num_videos_per_prompt: Optional[int] = 1,
140
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
141
+ latents: Optional[torch.Tensor] = None,
142
+ prompt_embeds: Optional[torch.Tensor] = None,
143
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
144
+ prompt_attention_mask: Optional[torch.Tensor] = None,
145
+ output_type: Optional[str] = "pil",
146
+ return_dict: bool = True,
147
+ attention_kwargs: Optional[Dict[str, Any]] = None,
148
+ callback_on_step_end: Optional[Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]] = None,
149
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
150
+ prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
151
+ max_sequence_length: int = 256,
152
+ image_latents: Optional[torch.Tensor] = None,
153
+ ):
154
+
155
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
156
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
157
+
158
+ # 1. Check inputs. Raise error if not correct
159
+ pipe.check_inputs(
160
+ prompt,
161
+ prompt_2,
162
+ height,
163
+ width,
164
+ prompt_embeds,
165
+ callback_on_step_end_tensor_inputs,
166
+ prompt_template,
167
+ )
168
+
169
+ pipe._guidance_scale = guidance_scale
170
+ pipe._attention_kwargs = attention_kwargs
171
+ pipe._current_timestep = None
172
+ pipe._interrupt = False
173
+
174
+ device = pipe._execution_device
175
+
176
+ # 2. Define call parameters
177
+ if prompt is not None and isinstance(prompt, str):
178
+ batch_size = 1
179
+ elif prompt is not None and isinstance(prompt, list):
180
+ batch_size = len(prompt)
181
+ else:
182
+ batch_size = prompt_embeds.shape[0]
183
+
184
+ # 3. Encode input prompt
185
+ prompt_embeds, pooled_prompt_embeds, prompt_attention_mask = pipe.encode_prompt(
186
+ prompt=prompt,
187
+ prompt_2=prompt_2,
188
+ prompt_template=prompt_template,
189
+ num_videos_per_prompt=num_videos_per_prompt,
190
+ prompt_embeds=prompt_embeds,
191
+ pooled_prompt_embeds=pooled_prompt_embeds,
192
+ prompt_attention_mask=prompt_attention_mask,
193
+ device=device,
194
+ max_sequence_length=max_sequence_length,
195
+ )
196
+
197
+ transformer_dtype = pipe.transformer.dtype
198
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
199
+ prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
200
+ if pooled_prompt_embeds is not None:
201
+ pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
202
+
203
+ # 4. Prepare timesteps
204
+ sigmas = np.linspace(1.0, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
205
+ timesteps, num_inference_steps = retrieve_timesteps(
206
+ pipe.scheduler,
207
+ num_inference_steps,
208
+ device,
209
+ sigmas=sigmas,
210
+ )
211
+
212
+ # 5. Prepare latent variables
213
+ num_channels_latents = pipe.transformer.config.in_channels
214
+ num_latent_frames = (num_frames - 1) // pipe.vae_scale_factor_temporal + 1
215
+ latents = pipe.prepare_latents(
216
+ batch_size * num_videos_per_prompt,
217
+ num_channels_latents,
218
+ height,
219
+ width,
220
+ num_latent_frames,
221
+ torch.float32,
222
+ device,
223
+ generator,
224
+ latents,
225
+ )
226
+
227
+ # 6. Prepare guidance condition
228
+ guidance = torch.tensor([guidance_scale] * latents.shape[0], dtype=transformer_dtype, device=device) * 1000.0
229
+
230
+ # 7. Denoising loop
231
+ num_warmup_steps = len(timesteps) - num_inference_steps * pipe.scheduler.order
232
+ pipe._num_timesteps = len(timesteps)
233
+
234
+ with pipe.progress_bar(total=num_inference_steps) as progress_bar:
235
+ for i, t in enumerate(timesteps):
236
+ if pipe.interrupt:
237
+ continue
238
+
239
+ pipe._current_timestep = t
240
+ latent_model_input = latents.to(transformer_dtype)
241
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
242
+
243
+ noise_pred = pipe.transformer(
244
+ hidden_states=torch.cat([latent_model_input, image_latents], dim=1),
245
+ timestep=timestep,
246
+ encoder_hidden_states=prompt_embeds,
247
+ encoder_attention_mask=prompt_attention_mask,
248
+ pooled_projections=pooled_prompt_embeds,
249
+ guidance=guidance,
250
+ attention_kwargs=attention_kwargs,
251
+ return_dict=False,
252
+ )[0]
253
+
254
+ # compute the previous noisy sample x_t -> x_t-1
255
+ latents = pipe.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
256
+
257
+ if callback_on_step_end is not None:
258
+ callback_kwargs = {}
259
+ for k in callback_on_step_end_tensor_inputs:
260
+ callback_kwargs[k] = locals()[k]
261
+ callback_outputs = callback_on_step_end(pipe, i, t, callback_kwargs)
262
+
263
+ latents = callback_outputs.pop("latents", latents)
264
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
265
+
266
+ # call the callback, if provided
267
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % pipe.scheduler.order == 0):
268
+ progress_bar.update()
269
+ pipe._current_timestep = None
270
+
271
+ if not output_type == "latent":
272
+ latents = latents.to(pipe.vae.dtype) / pipe.vae.config.scaling_factor
273
+ video = pipe.vae.decode(latents, return_dict=False)[0]
274
+ video = pipe.video_processor.postprocess_video(video, output_type=output_type)
275
+ else:
276
+ video = latents
277
+
278
+ # Offload all models
279
+ pipe.maybe_free_model_hooks()
280
+
281
+ if not return_dict:
282
+ return (video,)
283
+
284
+ return HunyuanVideoPipelineOutput(frames=video)
285
+
286
+
287
+ video = call_pipe(
288
+ pipe,
289
+ prompt=prompt,
290
+ num_frames=n_frames,
291
+ num_inference_steps=50,
292
+ image_latents=cond_latents,
293
+ width=width,
294
+ height=height,
295
+ guidance_scale=6.0,
296
+ generator=torch.Generator(device="cuda").manual_seed(0),
297
+ ).frames[0]
298
+
299
+ export_to_video(video, "output.mp4", fps=24)