Upload VideoX-Fun/examples
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- VideoX-Fun/examples/cogvideox_fun/app.py +73 -0
- VideoX-Fun/examples/cogvideox_fun/launch_api.py +90 -0
- VideoX-Fun/examples/cogvideox_fun/post_infer.py +150 -0
- VideoX-Fun/examples/cogvideox_fun/post_infer_queue.py +145 -0
- VideoX-Fun/examples/cogvideox_fun/predict_i2v.py +320 -0
- VideoX-Fun/examples/cogvideox_fun/predict_t2v.py +316 -0
- VideoX-Fun/examples/cogvideox_fun/predict_v2v.py +255 -0
- VideoX-Fun/examples/cogvideox_fun/predict_v2v_control.py +240 -0
- VideoX-Fun/examples/flux/predict_t2i.py +218 -0
- VideoX-Fun/examples/phantom/predict_s2v.py +300 -0
- VideoX-Fun/examples/qwenimage/predict_t2i.py +210 -0
- VideoX-Fun/examples/wan2.1/__pycache__/pred_ori.cpython-313.pyc +0 -0
- VideoX-Fun/examples/wan2.1/app.py +77 -0
- VideoX-Fun/examples/wan2.1/launch_api.py +91 -0
- VideoX-Fun/examples/wan2.1/post_infer.py +150 -0
- VideoX-Fun/examples/wan2.1/post_infer_queue.py +192 -0
- VideoX-Fun/examples/wan2.1/post_infer_queue_i2v.py +212 -0
- VideoX-Fun/examples/wan2.1/pred_ori.py +332 -0
- VideoX-Fun/examples/wan2.1/predict_i2v.py +301 -0
- VideoX-Fun/examples/wan2.1/predict_t2v.py +305 -0
- VideoX-Fun/examples/wan2.1/predict_t2v1.py +283 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_14B_vqref.py +354 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_fg.py +396 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val.py +283 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val1.py +361 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val2.py +367 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val3.py +374 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val4.py +406 -0
- VideoX-Fun/examples/wan2.1/predict_t2v_val_sd.py +368 -0
- VideoX-Fun/examples/wan2.1_fun/app.py +79 -0
- VideoX-Fun/examples/wan2.1_fun/launch_api.py +91 -0
- VideoX-Fun/examples/wan2.1_fun/post_infer.py +150 -0
- VideoX-Fun/examples/wan2.1_fun/post_infer_queue.py +192 -0
- VideoX-Fun/examples/wan2.1_fun/post_infer_queue_i2v.py +213 -0
- VideoX-Fun/examples/wan2.1_fun/post_infer_queue_v2v_control.py +230 -0
- VideoX-Fun/examples/wan2.1_fun/predict_i2v.py +302 -0
- VideoX-Fun/examples/wan2.1_fun/predict_t2v.py +321 -0
- VideoX-Fun/examples/wan2.1_fun/predict_v2v_control.py +333 -0
- VideoX-Fun/examples/wan2.1_fun/predict_v2v_control_camera.py +333 -0
- VideoX-Fun/examples/wan2.1_fun/predict_v2v_control_ref.py +333 -0
- VideoX-Fun/examples/wan2.2/app.py +79 -0
- VideoX-Fun/examples/wan2.2/launch_api.py +91 -0
- VideoX-Fun/examples/wan2.2/post_infer.py +169 -0
- VideoX-Fun/examples/wan2.2/post_infer_queue.py +191 -0
- VideoX-Fun/examples/wan2.2/post_infer_queue_i2v.py +212 -0
- VideoX-Fun/examples/wan2.2/predict_i2v.py +337 -0
- VideoX-Fun/examples/wan2.2/predict_s2v.py +361 -0
- VideoX-Fun/examples/wan2.2/predict_t2v.py +327 -0
- VideoX-Fun/examples/wan2.2/predict_ti2v.py +355 -0
- VideoX-Fun/examples/wan2.2_fun/app.py +79 -0
VideoX-Fun/examples/cogvideox_fun/app.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.api.api import (infer_forward_api,
|
| 13 |
+
update_diffusion_transformer_api)
|
| 14 |
+
from videox_fun.ui.controller import ddpm_scheduler_dict
|
| 15 |
+
from videox_fun.ui.cogvideox_fun_ui import ui, ui_client, ui_host
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
# Choose the ui mode
|
| 19 |
+
# "normal" refers to the standard UI, which allows users to click to switch models, change model types, and more.
|
| 20 |
+
# "host" represents the hosting mode, where the model is loaded directly at startup and can be accessed via
|
| 21 |
+
# the API to return generation results.
|
| 22 |
+
# "client" represents the client mode, offering a simple UI that sends requests to a remote API for generation.
|
| 23 |
+
ui_mode = "normal"
|
| 24 |
+
|
| 25 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 26 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
#
|
| 28 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 31 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 32 |
+
#
|
| 33 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 34 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 35 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 36 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 37 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 38 |
+
compile_dit = False
|
| 39 |
+
|
| 40 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 41 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 42 |
+
weight_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# Server ip
|
| 45 |
+
server_name = "0.0.0.0"
|
| 46 |
+
server_port = 7860
|
| 47 |
+
|
| 48 |
+
# Params below is used when ui_mode = "host"
|
| 49 |
+
model_name = "models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP"
|
| 50 |
+
# "Inpaint" or "Control"
|
| 51 |
+
model_type = "Inpaint"
|
| 52 |
+
|
| 53 |
+
if ui_mode == "host":
|
| 54 |
+
demo, controller = ui_host(GPU_memory_mode, ddpm_scheduler_dict, model_name, model_type, compile_dit, weight_dtype)
|
| 55 |
+
elif ui_mode == "client":
|
| 56 |
+
demo, controller = ui_client(ddpm_scheduler_dict, model_name)
|
| 57 |
+
else:
|
| 58 |
+
demo, controller = ui(GPU_memory_mode, ddpm_scheduler_dict, compile_dit, weight_dtype)
|
| 59 |
+
|
| 60 |
+
# launch gradio
|
| 61 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 62 |
+
server_name=server_name,
|
| 63 |
+
server_port=server_port,
|
| 64 |
+
prevent_thread_lock=True
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# launch api
|
| 68 |
+
infer_forward_api(None, app, controller)
|
| 69 |
+
update_diffusion_transformer_api(None, app, controller)
|
| 70 |
+
|
| 71 |
+
# not close the python
|
| 72 |
+
while True:
|
| 73 |
+
time.sleep(5)
|
VideoX-Fun/examples/cogvideox_fun/launch_api.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import ray
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.api.api_multi_nodes import (MultiNodesEngine,
|
| 16 |
+
multi_nodes_infer_forward_api)
|
| 17 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 18 |
+
from videox_fun.ui.cogvideox_fun_ui import CogVideoXFunController
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description='xDiT HTTP Service')
|
| 22 |
+
parser.add_argument('--world_size', type=int, default=8, help='Number of parallel workers')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--gpu_memory_mode', type=str, default="model_cpu_offload", help='''
|
| 25 |
+
GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8].
|
| 26 |
+
model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
|
| 28 |
+
model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 29 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 30 |
+
|
| 31 |
+
model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 32 |
+
|
| 33 |
+
model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 34 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
'''
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
'--compile_dit', action='store_true', help='''
|
| 39 |
+
Enable compile dit.
|
| 40 |
+
Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 41 |
+
The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 42 |
+
'''
|
| 43 |
+
)
|
| 44 |
+
parser.add_argument('--fsdp_dit', action='store_true', help="Use DIT FSDP to save more GPU memory in multi gpus.")
|
| 45 |
+
parser.add_argument('--fsdp_text_encoder', action='store_true', help="Use Text Encoder FSDP to save more GPU memory in multi gpus.")
|
| 46 |
+
parser.add_argument('--ulysses_degree', type=int, default=4, help='Degree of Ulysses configuration')
|
| 47 |
+
parser.add_argument('--ring_degree', type=int, default=2, help='Degree of Ring configuration')
|
| 48 |
+
parser.add_argument('--weight_dtype', type=str, default='bf16', help='Weight data type')
|
| 49 |
+
parser.add_argument('--server_name', type=str, default="0.0.0.0", help='Server IP address')
|
| 50 |
+
parser.add_argument('--server_port', type=int, default=7860, help='Server Port')
|
| 51 |
+
parser.add_argument('--model_name', type=str, default="models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP", help='Model path')
|
| 52 |
+
parser.add_argument('--model_type', type=str, default="Inpaint", help='Model type (Inpaint/Control)')
|
| 53 |
+
parser.add_argument('--savedir_sample', type=str, default=None, help='The save directory for samples')
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
|
| 56 |
+
weight_dtype = torch.float32
|
| 57 |
+
if args.weight_dtype == "bf16":
|
| 58 |
+
weight_dtype = torch.bfloat16
|
| 59 |
+
elif args.weight_dtype == "fp16":
|
| 60 |
+
weight_dtype = torch.float16
|
| 61 |
+
|
| 62 |
+
engine = MultiNodesEngine(
|
| 63 |
+
world_size=args.world_size, Controller=CogVideoXFunController,
|
| 64 |
+
GPU_memory_mode=args.gpu_memory_mode, scheduler_dict=flow_scheduler_dict, model_name=args.model_name, model_type=args.model_type, config_path=None,
|
| 65 |
+
ulysses_degree=args.ulysses_degree, ring_degree=args.ring_degree,
|
| 66 |
+
fsdp_dit=args.fsdp_dit, fsdp_text_encoder=args.fsdp_text_encoder, compile_dit=args.compile_dit,
|
| 67 |
+
weight_dtype=weight_dtype, savedir_sample=args.savedir_sample,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def gr_launch():
|
| 71 |
+
# launch gradio
|
| 72 |
+
with gr.Blocks() as demo:
|
| 73 |
+
gr.Markdown("")
|
| 74 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 75 |
+
server_name=args.server_name,
|
| 76 |
+
server_port=args.server_port,
|
| 77 |
+
prevent_thread_lock=True
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# launch api
|
| 81 |
+
multi_nodes_infer_forward_api(None, app, engine)
|
| 82 |
+
|
| 83 |
+
gr_launch()
|
| 84 |
+
|
| 85 |
+
# not close the python
|
| 86 |
+
while True:
|
| 87 |
+
time.sleep(5)
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
main()
|
VideoX-Fun/examples/cogvideox_fun/post_infer.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
import base64
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_diffusion_transformer(diffusion_transformer_path, url='http://127.0.0.1:7860'):
|
| 11 |
+
datas = json.dumps({
|
| 12 |
+
"diffusion_transformer_path": diffusion_transformer_path
|
| 13 |
+
})
|
| 14 |
+
r = requests.post(f'{url}/cogvideox_fun/update_diffusion_transformer', data=datas, timeout=1500)
|
| 15 |
+
data = r.content.decode('utf-8')
|
| 16 |
+
return data
|
| 17 |
+
|
| 18 |
+
def post_update_edition(edition, url='http://0.0.0.0:7860'):
|
| 19 |
+
datas = json.dumps({
|
| 20 |
+
"edition": edition
|
| 21 |
+
})
|
| 22 |
+
r = requests.post(f'{url}/cogvideox_fun/update_edition', data=datas, timeout=1500)
|
| 23 |
+
data = r.content.decode('utf-8')
|
| 24 |
+
return data
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def post_infer(
|
| 28 |
+
generation_method,
|
| 29 |
+
length_slider,
|
| 30 |
+
url='http://127.0.0.1:7860',
|
| 31 |
+
POST_TOKEN="",
|
| 32 |
+
timeout=5000,
|
| 33 |
+
base_model_path="none",
|
| 34 |
+
lora_model_path="none",
|
| 35 |
+
lora_alpha_slider=0.55,
|
| 36 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 37 |
+
negative_prompt_textbox="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion.",
|
| 38 |
+
sampler_dropdown="Flow",
|
| 39 |
+
sample_step_slider=50,
|
| 40 |
+
width_slider=672,
|
| 41 |
+
height_slider=384,
|
| 42 |
+
cfg_scale_slider=6,
|
| 43 |
+
seed_textbox=43
|
| 44 |
+
):
|
| 45 |
+
# Prepare the data payload
|
| 46 |
+
datas = json.dumps({
|
| 47 |
+
"base_model_path": base_model_path,
|
| 48 |
+
"lora_model_path": lora_model_path,
|
| 49 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 50 |
+
"prompt_textbox": prompt_textbox,
|
| 51 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 52 |
+
"sampler_dropdown": sampler_dropdown,
|
| 53 |
+
"sample_step_slider": sample_step_slider,
|
| 54 |
+
"width_slider": width_slider,
|
| 55 |
+
"height_slider": height_slider,
|
| 56 |
+
"generation_method": generation_method,
|
| 57 |
+
"length_slider": length_slider,
|
| 58 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 59 |
+
"seed_textbox": seed_textbox,
|
| 60 |
+
})
|
| 61 |
+
|
| 62 |
+
# Initialize session and set headers
|
| 63 |
+
session = requests.session()
|
| 64 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 65 |
+
|
| 66 |
+
# Send POST request
|
| 67 |
+
if url[-1] == "/":
|
| 68 |
+
url = url[:-1]
|
| 69 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 70 |
+
|
| 71 |
+
data = post_r.content.decode('utf-8')
|
| 72 |
+
return data
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
# initiate time
|
| 76 |
+
time_start = time.time()
|
| 77 |
+
|
| 78 |
+
# The Url you want to post
|
| 79 |
+
POST_URL = 'http://0.0.0.0:7860'
|
| 80 |
+
# Used in EAS. If you don't need Authorization, please set it to empty string.
|
| 81 |
+
TOKEN = ''
|
| 82 |
+
|
| 83 |
+
# -------------------------- #
|
| 84 |
+
# Step 1: update edition
|
| 85 |
+
# -------------------------- #
|
| 86 |
+
# diffusion_transformer_path = "models/Diffusion_Transformer/CogVideoX-Fun-2b-InP"
|
| 87 |
+
# outputs = post_diffusion_transformer(diffusion_transformer_path)
|
| 88 |
+
# print('Output update edition: ', outputs)
|
| 89 |
+
|
| 90 |
+
# -------------------------- #
|
| 91 |
+
# Step 2: infer
|
| 92 |
+
# -------------------------- #
|
| 93 |
+
# "Video Generation" and "Image Generation"
|
| 94 |
+
generation_method = "Video Generation"
|
| 95 |
+
# Video length
|
| 96 |
+
length_slider = 49
|
| 97 |
+
# Used in Lora models
|
| 98 |
+
lora_model_path = "none"
|
| 99 |
+
lora_alpha_slider = 0.55
|
| 100 |
+
# Prompts
|
| 101 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 102 |
+
negative_prompt_textbox = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 103 |
+
# Sampler name
|
| 104 |
+
sampler_dropdown = "Euler"
|
| 105 |
+
# Sampler steps
|
| 106 |
+
sample_step_slider = 50
|
| 107 |
+
# height and width
|
| 108 |
+
width_slider = 672
|
| 109 |
+
height_slider = 384
|
| 110 |
+
# cfg scale
|
| 111 |
+
cfg_scale_slider = 6
|
| 112 |
+
seed_textbox = 43
|
| 113 |
+
|
| 114 |
+
outputs = post_infer(
|
| 115 |
+
generation_method,
|
| 116 |
+
length_slider,
|
| 117 |
+
lora_model_path=lora_model_path,
|
| 118 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 119 |
+
prompt_textbox=prompt_textbox,
|
| 120 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 121 |
+
sampler_dropdown=sampler_dropdown,
|
| 122 |
+
sample_step_slider=sample_step_slider,
|
| 123 |
+
width_slider=width_slider,
|
| 124 |
+
height_slider=height_slider,
|
| 125 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 126 |
+
seed_textbox=seed_textbox,
|
| 127 |
+
url=POST_URL,
|
| 128 |
+
POST_TOKEN=TOKEN
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Get decoded data
|
| 132 |
+
outputs = json.loads(outputs)
|
| 133 |
+
base64_encoding = outputs["base64_encoding"]
|
| 134 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 135 |
+
|
| 136 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 137 |
+
if is_image or length_slider == 1:
|
| 138 |
+
file_path = "1.png"
|
| 139 |
+
else:
|
| 140 |
+
file_path = "1.mp4"
|
| 141 |
+
with open(file_path, "wb") as file:
|
| 142 |
+
file.write(decoded_data)
|
| 143 |
+
|
| 144 |
+
# End of record time
|
| 145 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 146 |
+
time_end = time.time()
|
| 147 |
+
time_sum = (time_end - time_start)
|
| 148 |
+
print('# --------------------------------------------------------- #')
|
| 149 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 150 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/cogvideox_fun/post_infer_queue.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def post_infer(
|
| 9 |
+
generation_method,
|
| 10 |
+
length_slider,
|
| 11 |
+
url='http://127.0.0.1:7860',
|
| 12 |
+
POST_TOKEN="",
|
| 13 |
+
timeout=5,
|
| 14 |
+
base_model_path="none",
|
| 15 |
+
lora_model_path="none",
|
| 16 |
+
lora_alpha_slider=0.55,
|
| 17 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 18 |
+
negative_prompt_textbox="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion.",
|
| 19 |
+
sampler_dropdown="Flow",
|
| 20 |
+
sample_step_slider=50,
|
| 21 |
+
width_slider=672,
|
| 22 |
+
height_slider=384,
|
| 23 |
+
cfg_scale_slider=6,
|
| 24 |
+
seed_textbox=43
|
| 25 |
+
):
|
| 26 |
+
# Prepare the data payload
|
| 27 |
+
datas = json.dumps({
|
| 28 |
+
"base_model_path": base_model_path,
|
| 29 |
+
"lora_model_path": lora_model_path,
|
| 30 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 31 |
+
"prompt_textbox": prompt_textbox,
|
| 32 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 33 |
+
"sampler_dropdown": sampler_dropdown,
|
| 34 |
+
"sample_step_slider": sample_step_slider,
|
| 35 |
+
"width_slider": width_slider,
|
| 36 |
+
"height_slider": height_slider,
|
| 37 |
+
"generation_method": generation_method,
|
| 38 |
+
"length_slider": length_slider,
|
| 39 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 40 |
+
"seed_textbox": seed_textbox,
|
| 41 |
+
})
|
| 42 |
+
|
| 43 |
+
# Initialize session and set headers
|
| 44 |
+
session = requests.session()
|
| 45 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 46 |
+
|
| 47 |
+
# Send POST request
|
| 48 |
+
if url[-1] == "/":
|
| 49 |
+
url = url[:-1]
|
| 50 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 51 |
+
|
| 52 |
+
# Extract request ID from POST response headers
|
| 53 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 54 |
+
|
| 55 |
+
# Prepare query parameters for GET request
|
| 56 |
+
query = {
|
| 57 |
+
'_index_': '0',
|
| 58 |
+
'_length_': '1',
|
| 59 |
+
'_timeout_': str(timeout),
|
| 60 |
+
'_raw_': 'false',
|
| 61 |
+
'_auto_delete_': 'true',
|
| 62 |
+
}
|
| 63 |
+
if request_id:
|
| 64 |
+
query['requestId'] = request_id
|
| 65 |
+
|
| 66 |
+
query_str = urllib.parse.urlencode(query)
|
| 67 |
+
|
| 68 |
+
# Polling GET request until status code is not 204
|
| 69 |
+
status_code = 204
|
| 70 |
+
while status_code == 204:
|
| 71 |
+
if query_str:
|
| 72 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 73 |
+
else:
|
| 74 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 75 |
+
status_code = get_r.status_code
|
| 76 |
+
# Decode and return the response content
|
| 77 |
+
data = get_r.content.decode('utf-8')
|
| 78 |
+
return data
|
| 79 |
+
|
| 80 |
+
if __name__ == '__main__':
|
| 81 |
+
# initiate time
|
| 82 |
+
time_start = time.time()
|
| 83 |
+
|
| 84 |
+
# EAS队列配置
|
| 85 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 86 |
+
# Use in EAS Queue
|
| 87 |
+
TOKEN = 'xxxxxxxx'
|
| 88 |
+
|
| 89 |
+
# "Video Generation" and "Image Generation"
|
| 90 |
+
generation_method = "Video Generation"
|
| 91 |
+
# Video length
|
| 92 |
+
length_slider = 49
|
| 93 |
+
# Used in Lora models
|
| 94 |
+
lora_model_path = "none"
|
| 95 |
+
lora_alpha_slider = 0.55
|
| 96 |
+
# Prompts
|
| 97 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 98 |
+
negative_prompt_textbox = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 99 |
+
# Sampler name
|
| 100 |
+
sampler_dropdown = "Euler"
|
| 101 |
+
# Sampler steps
|
| 102 |
+
sample_step_slider = 50
|
| 103 |
+
# height and width
|
| 104 |
+
width_slider = 672
|
| 105 |
+
height_slider = 384
|
| 106 |
+
# cfg scale
|
| 107 |
+
cfg_scale_slider = 6
|
| 108 |
+
seed_textbox = 43
|
| 109 |
+
|
| 110 |
+
outputs = post_infer(
|
| 111 |
+
generation_method,
|
| 112 |
+
length_slider,
|
| 113 |
+
lora_model_path=lora_model_path,
|
| 114 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 115 |
+
prompt_textbox=prompt_textbox,
|
| 116 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 117 |
+
sampler_dropdown=sampler_dropdown,
|
| 118 |
+
sample_step_slider=sample_step_slider,
|
| 119 |
+
width_slider=width_slider,
|
| 120 |
+
height_slider=height_slider,
|
| 121 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 122 |
+
seed_textbox=seed_textbox,
|
| 123 |
+
url=EAS_URL,
|
| 124 |
+
POST_TOKEN=TOKEN
|
| 125 |
+
)
|
| 126 |
+
# Get decoded data
|
| 127 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 128 |
+
base64_encoding = outputs["base64_encoding"]
|
| 129 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 130 |
+
|
| 131 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 132 |
+
if is_image or length_slider == 1:
|
| 133 |
+
file_path = "1.png"
|
| 134 |
+
else:
|
| 135 |
+
file_path = "1.mp4"
|
| 136 |
+
with open(file_path, "wb") as file:
|
| 137 |
+
file.write(decoded_data)
|
| 138 |
+
|
| 139 |
+
# End of record time
|
| 140 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 141 |
+
time_end = time.time()
|
| 142 |
+
time_sum = (time_end - time_start)
|
| 143 |
+
print('# --------------------------------------------------------- #')
|
| 144 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 145 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/cogvideox_fun/predict_i2v.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
|
| 7 |
+
DPMSolverMultistepScheduler,
|
| 8 |
+
EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
|
| 9 |
+
PNDMScheduler)
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
current_file_path = os.path.abspath(__file__)
|
| 13 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 14 |
+
for project_root in project_roots:
|
| 15 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 16 |
+
|
| 17 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 18 |
+
from videox_fun.models import (AutoencoderKLCogVideoX,
|
| 19 |
+
CogVideoXTransformer3DModel, T5EncoderModel,
|
| 20 |
+
T5Tokenizer)
|
| 21 |
+
from videox_fun.pipeline import (CogVideoXFunInpaintPipeline,
|
| 22 |
+
CogVideoXFunPipeline)
|
| 23 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 24 |
+
convert_weight_dtype_wrapper)
|
| 25 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 26 |
+
from videox_fun.utils.utils import get_image_to_video_latent, save_videos_grid
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# Config and model path
|
| 56 |
+
model_name = "models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP"
|
| 57 |
+
|
| 58 |
+
# Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
|
| 59 |
+
sampler_name = "DDIM_Origin"
|
| 60 |
+
|
| 61 |
+
# Load pretrained model if need
|
| 62 |
+
transformer_path = None
|
| 63 |
+
vae_path = None
|
| 64 |
+
lora_path = None
|
| 65 |
+
|
| 66 |
+
# Other params
|
| 67 |
+
sample_size = [384, 672]
|
| 68 |
+
# V1.0 and V1.1 support up to 49 frames of video generation,
|
| 69 |
+
# while V1.5 supports up to 85 frames.
|
| 70 |
+
video_length = 49
|
| 71 |
+
fps = 8
|
| 72 |
+
|
| 73 |
+
# If you want to generate ultra long videos, please set partial_video_length as the length of each sub video segment
|
| 74 |
+
partial_video_length = None
|
| 75 |
+
overlap_video_length = 4
|
| 76 |
+
|
| 77 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 78 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 79 |
+
weight_dtype = torch.bfloat16
|
| 80 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 81 |
+
validation_image_start = "asset/1.png"
|
| 82 |
+
validation_image_end = None
|
| 83 |
+
|
| 84 |
+
# prompts
|
| 85 |
+
prompt = "The dog is shaking head. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 86 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 87 |
+
guidance_scale = 6.0
|
| 88 |
+
seed = 43
|
| 89 |
+
num_inference_steps = 50
|
| 90 |
+
lora_weight = 0.55
|
| 91 |
+
save_path = "samples/cogvideox-fun-videos_i2v"
|
| 92 |
+
|
| 93 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 94 |
+
|
| 95 |
+
transformer = CogVideoXTransformer3DModel.from_pretrained(
|
| 96 |
+
model_name,
|
| 97 |
+
subfolder="transformer",
|
| 98 |
+
low_cpu_mem_usage=True,
|
| 99 |
+
torch_dtype=weight_dtype,
|
| 100 |
+
).to(weight_dtype)
|
| 101 |
+
|
| 102 |
+
if transformer_path is not None:
|
| 103 |
+
print(f"From checkpoint: {transformer_path}")
|
| 104 |
+
if transformer_path.endswith("safetensors"):
|
| 105 |
+
from safetensors.torch import load_file, safe_open
|
| 106 |
+
state_dict = load_file(transformer_path)
|
| 107 |
+
else:
|
| 108 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 109 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 110 |
+
|
| 111 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 112 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 113 |
+
|
| 114 |
+
# Get Vae
|
| 115 |
+
vae = AutoencoderKLCogVideoX.from_pretrained(
|
| 116 |
+
model_name,
|
| 117 |
+
subfolder="vae"
|
| 118 |
+
).to(weight_dtype)
|
| 119 |
+
|
| 120 |
+
if vae_path is not None:
|
| 121 |
+
print(f"From checkpoint: {vae_path}")
|
| 122 |
+
if vae_path.endswith("safetensors"):
|
| 123 |
+
from safetensors.torch import load_file, safe_open
|
| 124 |
+
state_dict = load_file(vae_path)
|
| 125 |
+
else:
|
| 126 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 127 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 128 |
+
|
| 129 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 130 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 131 |
+
|
| 132 |
+
# Get tokenizer and text_encoder
|
| 133 |
+
tokenizer = T5Tokenizer.from_pretrained(
|
| 134 |
+
model_name, subfolder="tokenizer"
|
| 135 |
+
)
|
| 136 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 137 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Get Scheduler
|
| 141 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 142 |
+
"Euler": EulerDiscreteScheduler,
|
| 143 |
+
"Euler A": EulerAncestralDiscreteScheduler,
|
| 144 |
+
"DPM++": DPMSolverMultistepScheduler,
|
| 145 |
+
"PNDM": PNDMScheduler,
|
| 146 |
+
"DDIM_Cog": CogVideoXDDIMScheduler,
|
| 147 |
+
"DDIM_Origin": DDIMScheduler,
|
| 148 |
+
}[sampler_name]
|
| 149 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 150 |
+
model_name,
|
| 151 |
+
subfolder="scheduler"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 155 |
+
pipeline = CogVideoXFunInpaintPipeline(
|
| 156 |
+
vae=vae,
|
| 157 |
+
tokenizer=tokenizer,
|
| 158 |
+
text_encoder=text_encoder,
|
| 159 |
+
transformer=transformer,
|
| 160 |
+
scheduler=scheduler,
|
| 161 |
+
)
|
| 162 |
+
else:
|
| 163 |
+
pipeline = CogVideoXFunPipeline(
|
| 164 |
+
vae=vae,
|
| 165 |
+
tokenizer=tokenizer,
|
| 166 |
+
text_encoder=text_encoder,
|
| 167 |
+
transformer=transformer,
|
| 168 |
+
scheduler=scheduler,
|
| 169 |
+
)
|
| 170 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 171 |
+
from functools import partial
|
| 172 |
+
transformer.enable_multi_gpus_inference()
|
| 173 |
+
if fsdp_dit:
|
| 174 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 175 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 176 |
+
print("Add FSDP DIT")
|
| 177 |
+
if fsdp_text_encoder:
|
| 178 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 179 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 180 |
+
print("Add FSDP TEXT ENCODER")
|
| 181 |
+
|
| 182 |
+
if compile_dit:
|
| 183 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 184 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 185 |
+
print("Add Compile")
|
| 186 |
+
|
| 187 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 188 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 189 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 190 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 191 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 192 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 193 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 194 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 195 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 196 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 197 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 198 |
+
pipeline.to(device=device)
|
| 199 |
+
else:
|
| 200 |
+
pipeline.to(device=device)
|
| 201 |
+
|
| 202 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 203 |
+
|
| 204 |
+
if lora_path is not None:
|
| 205 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 206 |
+
|
| 207 |
+
if partial_video_length is not None:
|
| 208 |
+
partial_video_length = int((partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 209 |
+
latent_frames = (partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 210 |
+
if partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 211 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 212 |
+
partial_video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 213 |
+
|
| 214 |
+
init_frames = 0
|
| 215 |
+
last_frames = init_frames + partial_video_length
|
| 216 |
+
while init_frames < video_length:
|
| 217 |
+
if last_frames >= video_length:
|
| 218 |
+
_partial_video_length = video_length - init_frames
|
| 219 |
+
_partial_video_length = int((_partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1
|
| 220 |
+
latent_frames = (_partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 221 |
+
if _partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 222 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 223 |
+
_partial_video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 224 |
+
|
| 225 |
+
if _partial_video_length <= 0:
|
| 226 |
+
break
|
| 227 |
+
else:
|
| 228 |
+
_partial_video_length = partial_video_length
|
| 229 |
+
|
| 230 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image, None, video_length=_partial_video_length, sample_size=sample_size)
|
| 231 |
+
|
| 232 |
+
with torch.no_grad():
|
| 233 |
+
sample = pipeline(
|
| 234 |
+
prompt,
|
| 235 |
+
num_frames = _partial_video_length,
|
| 236 |
+
negative_prompt = negative_prompt,
|
| 237 |
+
height = sample_size[0],
|
| 238 |
+
width = sample_size[1],
|
| 239 |
+
generator = generator,
|
| 240 |
+
guidance_scale = guidance_scale,
|
| 241 |
+
num_inference_steps = num_inference_steps,
|
| 242 |
+
|
| 243 |
+
video = input_video,
|
| 244 |
+
mask_video = input_video_mask
|
| 245 |
+
).videos
|
| 246 |
+
|
| 247 |
+
if init_frames != 0:
|
| 248 |
+
mix_ratio = torch.from_numpy(
|
| 249 |
+
np.array([float(_index) / float(overlap_video_length) for _index in range(overlap_video_length)], np.float32)
|
| 250 |
+
).unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
|
| 251 |
+
|
| 252 |
+
new_sample[:, :, -overlap_video_length:] = new_sample[:, :, -overlap_video_length:] * (1 - mix_ratio) + \
|
| 253 |
+
sample[:, :, :overlap_video_length] * mix_ratio
|
| 254 |
+
new_sample = torch.cat([new_sample, sample[:, :, overlap_video_length:]], dim = 2)
|
| 255 |
+
|
| 256 |
+
sample = new_sample
|
| 257 |
+
else:
|
| 258 |
+
new_sample = sample
|
| 259 |
+
|
| 260 |
+
if last_frames >= video_length:
|
| 261 |
+
break
|
| 262 |
+
|
| 263 |
+
validation_image = [
|
| 264 |
+
Image.fromarray(
|
| 265 |
+
(sample[0, :, _index].transpose(0, 1).transpose(1, 2) * 255).numpy().astype(np.uint8)
|
| 266 |
+
) for _index in range(-overlap_video_length, 0)
|
| 267 |
+
]
|
| 268 |
+
|
| 269 |
+
init_frames = init_frames + _partial_video_length - overlap_video_length
|
| 270 |
+
last_frames = init_frames + _partial_video_length
|
| 271 |
+
else:
|
| 272 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 273 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 274 |
+
if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 275 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 276 |
+
video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 277 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, validation_image_end, video_length=video_length, sample_size=sample_size)
|
| 278 |
+
|
| 279 |
+
with torch.no_grad():
|
| 280 |
+
sample = pipeline(
|
| 281 |
+
prompt,
|
| 282 |
+
num_frames = video_length,
|
| 283 |
+
negative_prompt = negative_prompt,
|
| 284 |
+
height = sample_size[0],
|
| 285 |
+
width = sample_size[1],
|
| 286 |
+
generator = generator,
|
| 287 |
+
guidance_scale = guidance_scale,
|
| 288 |
+
num_inference_steps = num_inference_steps,
|
| 289 |
+
|
| 290 |
+
video = input_video,
|
| 291 |
+
mask_video = input_video_mask
|
| 292 |
+
).videos
|
| 293 |
+
|
| 294 |
+
if lora_path is not None:
|
| 295 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 296 |
+
|
| 297 |
+
def save_results():
|
| 298 |
+
if not os.path.exists(save_path):
|
| 299 |
+
os.makedirs(save_path, exist_ok=True)
|
| 300 |
+
|
| 301 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 302 |
+
prefix = str(index).zfill(8)
|
| 303 |
+
if video_length == 1:
|
| 304 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 305 |
+
|
| 306 |
+
image = sample[0, :, 0]
|
| 307 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 308 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 309 |
+
image = Image.fromarray(image)
|
| 310 |
+
image.save(video_path)
|
| 311 |
+
else:
|
| 312 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 313 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 314 |
+
|
| 315 |
+
if ulysses_degree * ring_degree > 1:
|
| 316 |
+
import torch.distributed as dist
|
| 317 |
+
if dist.get_rank() == 0:
|
| 318 |
+
save_results()
|
| 319 |
+
else:
|
| 320 |
+
save_results()
|
VideoX-Fun/examples/cogvideox_fun/predict_t2v.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
|
| 7 |
+
DPMSolverMultistepScheduler,
|
| 8 |
+
EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
|
| 9 |
+
PNDMScheduler)
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from transformers import T5EncoderModel
|
| 12 |
+
|
| 13 |
+
current_file_path = os.path.abspath(__file__)
|
| 14 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 15 |
+
for project_root in project_roots:
|
| 16 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 17 |
+
|
| 18 |
+
from videox_fun.models import (AutoencoderKLCogVideoX,
|
| 19 |
+
CogVideoXTransformer3DModel, T5EncoderModel,
|
| 20 |
+
T5Tokenizer)
|
| 21 |
+
from videox_fun.pipeline import (CogVideoXFunPipeline,
|
| 22 |
+
CogVideoXFunInpaintPipeline)
|
| 23 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 24 |
+
convert_weight_dtype_wrapper)
|
| 25 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 26 |
+
from videox_fun.utils.utils import get_image_to_video_latent, save_videos_grid
|
| 27 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 28 |
+
import argparse
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
|
| 31 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 32 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 34 |
+
|
| 35 |
+
parser.add_argument("--save_folder", type=str, default='samples4', help="prompt file for inference")
|
| 36 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 37 |
+
|
| 38 |
+
parser.add_argument("--sample_height", type=list, default=512, help="prompt file for inference")
|
| 39 |
+
parser.add_argument("--sample_width", type=list, default=288, help="prompt file for inference")
|
| 40 |
+
|
| 41 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 42 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 43 |
+
# parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 44 |
+
|
| 45 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 46 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 47 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 48 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 52 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 53 |
+
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 56 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 57 |
+
#
|
| 58 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 59 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 60 |
+
#
|
| 61 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 62 |
+
#
|
| 63 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 64 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 65 |
+
#
|
| 66 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 67 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 68 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 69 |
+
# Multi GPUs config
|
| 70 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 71 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 72 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 73 |
+
ulysses_degree = 1
|
| 74 |
+
ring_degree = 1
|
| 75 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 76 |
+
fsdp_dit = False
|
| 77 |
+
fsdp_text_encoder = True
|
| 78 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 79 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 80 |
+
compile_dit = False
|
| 81 |
+
|
| 82 |
+
# model path
|
| 83 |
+
model_name = "models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP"
|
| 84 |
+
|
| 85 |
+
# Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
|
| 86 |
+
sampler_name = "DDIM_Origin"
|
| 87 |
+
|
| 88 |
+
# Load pretrained model if need
|
| 89 |
+
transformer_path = None
|
| 90 |
+
vae_path = None
|
| 91 |
+
lora_path = args.lora_path
|
| 92 |
+
|
| 93 |
+
# Other params
|
| 94 |
+
sample_size = [256, 256]
|
| 95 |
+
# V1.0 and V1.1 support up to 49 frames of video generation,
|
| 96 |
+
# while V1.5 supports up to 85 frames.
|
| 97 |
+
video_length = 49
|
| 98 |
+
fps = 8
|
| 99 |
+
|
| 100 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 101 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 102 |
+
weight_dtype = torch.bfloat16
|
| 103 |
+
prompt_list_path = args.prompt_list_path
|
| 104 |
+
num_generated_videos = args.num_generated_videos
|
| 105 |
+
|
| 106 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 107 |
+
guidance_scale = 6.0
|
| 108 |
+
seed = -1
|
| 109 |
+
num_inference_steps = 40
|
| 110 |
+
lora_weight = 0.55
|
| 111 |
+
# save_path = args.save_path
|
| 112 |
+
|
| 113 |
+
if lora_path:
|
| 114 |
+
import pdb
|
| 115 |
+
# pdb.set_trace()
|
| 116 |
+
sub_path = lora_path.split('/')[-2]
|
| 117 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 118 |
+
save_path = f'{args.save_folder}/{sub_path}/steps_{itr}'
|
| 119 |
+
else:
|
| 120 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-seed{seed}/output_pretrain'
|
| 121 |
+
|
| 122 |
+
prompt_list = []
|
| 123 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 124 |
+
for line in file:
|
| 125 |
+
# 去除行末的换行符
|
| 126 |
+
prompt_list.append(line.strip())
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 130 |
+
|
| 131 |
+
transformer = CogVideoXTransformer3DModel.from_pretrained(
|
| 132 |
+
model_name,
|
| 133 |
+
subfolder="transformer",
|
| 134 |
+
low_cpu_mem_usage=True,
|
| 135 |
+
torch_dtype=weight_dtype,
|
| 136 |
+
).to(weight_dtype)
|
| 137 |
+
|
| 138 |
+
if transformer_path is not None:
|
| 139 |
+
print(f"From checkpoint: {transformer_path}")
|
| 140 |
+
if transformer_path.endswith("safetensors"):
|
| 141 |
+
from safetensors.torch import load_file, safe_open
|
| 142 |
+
state_dict = load_file(transformer_path)
|
| 143 |
+
else:
|
| 144 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 145 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 146 |
+
|
| 147 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 148 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 149 |
+
|
| 150 |
+
# Get Vae
|
| 151 |
+
vae = AutoencoderKLCogVideoX.from_pretrained(
|
| 152 |
+
model_name,
|
| 153 |
+
subfolder="vae"
|
| 154 |
+
).to(weight_dtype)
|
| 155 |
+
|
| 156 |
+
if vae_path is not None:
|
| 157 |
+
print(f"From checkpoint: {vae_path}")
|
| 158 |
+
if vae_path.endswith("safetensors"):
|
| 159 |
+
from safetensors.torch import load_file, safe_open
|
| 160 |
+
state_dict = load_file(vae_path)
|
| 161 |
+
else:
|
| 162 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 163 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 164 |
+
|
| 165 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 166 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 167 |
+
|
| 168 |
+
# Get tokenizer and text_encoder
|
| 169 |
+
tokenizer = T5Tokenizer.from_pretrained(
|
| 170 |
+
model_name, subfolder="tokenizer"
|
| 171 |
+
)
|
| 172 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 173 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Get Scheduler
|
| 177 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 178 |
+
"Euler": EulerDiscreteScheduler,
|
| 179 |
+
"Euler A": EulerAncestralDiscreteScheduler,
|
| 180 |
+
"DPM++": DPMSolverMultistepScheduler,
|
| 181 |
+
"PNDM": PNDMScheduler,
|
| 182 |
+
"DDIM_Cog": CogVideoXDDIMScheduler,
|
| 183 |
+
"DDIM_Origin": DDIMScheduler,
|
| 184 |
+
}[sampler_name]
|
| 185 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 186 |
+
model_name,
|
| 187 |
+
subfolder="scheduler"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 191 |
+
pipeline = CogVideoXFunInpaintPipeline(
|
| 192 |
+
vae=vae,
|
| 193 |
+
tokenizer=tokenizer,
|
| 194 |
+
text_encoder=text_encoder,
|
| 195 |
+
transformer=transformer,
|
| 196 |
+
scheduler=scheduler,
|
| 197 |
+
)
|
| 198 |
+
else:
|
| 199 |
+
pipeline = CogVideoXFunPipeline(
|
| 200 |
+
vae=vae,
|
| 201 |
+
tokenizer=tokenizer,
|
| 202 |
+
text_encoder=text_encoder,
|
| 203 |
+
transformer=transformer,
|
| 204 |
+
scheduler=scheduler,
|
| 205 |
+
)
|
| 206 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 207 |
+
from functools import partial
|
| 208 |
+
transformer.enable_multi_gpus_inference()
|
| 209 |
+
if fsdp_dit:
|
| 210 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 211 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 212 |
+
print("Add FSDP DIT")
|
| 213 |
+
if fsdp_text_encoder:
|
| 214 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 215 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 216 |
+
print("Add FSDP TEXT ENCODER")
|
| 217 |
+
|
| 218 |
+
if compile_dit:
|
| 219 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 220 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 221 |
+
print("Add Compile")
|
| 222 |
+
|
| 223 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 224 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 225 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 226 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 227 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 228 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 229 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 230 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 231 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 232 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 233 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 234 |
+
pipeline.to(device=device)
|
| 235 |
+
else:
|
| 236 |
+
pipeline.to(device=device)
|
| 237 |
+
|
| 238 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 239 |
+
if seed == -1:
|
| 240 |
+
generator = None
|
| 241 |
+
else:
|
| 242 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 243 |
+
|
| 244 |
+
if lora_path is not None:
|
| 245 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 246 |
+
|
| 247 |
+
if num_generated_videos == -1:
|
| 248 |
+
num_generated_videos = len(prompt_list)
|
| 249 |
+
|
| 250 |
+
# for prompt in prompt_list[:num_generated_videos]:
|
| 251 |
+
for i in range(len(prompt_list[:num_generated_videos])):
|
| 252 |
+
|
| 253 |
+
prompt = prompt_list[:num_generated_videos][i]
|
| 254 |
+
|
| 255 |
+
with torch.no_grad():
|
| 256 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 257 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 258 |
+
if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 259 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 260 |
+
video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 261 |
+
|
| 262 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 263 |
+
input_video, input_video_mask, _ = get_image_to_video_latent(None, None, video_length=video_length, sample_size=sample_size)
|
| 264 |
+
|
| 265 |
+
sample = pipeline(
|
| 266 |
+
prompt,
|
| 267 |
+
num_frames = video_length,
|
| 268 |
+
negative_prompt = negative_prompt,
|
| 269 |
+
height = sample_size[0],
|
| 270 |
+
width = sample_size[1],
|
| 271 |
+
generator = generator,
|
| 272 |
+
guidance_scale = guidance_scale,
|
| 273 |
+
num_inference_steps = num_inference_steps,
|
| 274 |
+
|
| 275 |
+
video = input_video,
|
| 276 |
+
mask_video = input_video_mask,
|
| 277 |
+
).videos
|
| 278 |
+
else:
|
| 279 |
+
sample = pipeline(
|
| 280 |
+
prompt,
|
| 281 |
+
num_frames = video_length,
|
| 282 |
+
negative_prompt = negative_prompt,
|
| 283 |
+
height = sample_size[0],
|
| 284 |
+
width = sample_size[1],
|
| 285 |
+
generator = generator,
|
| 286 |
+
guidance_scale = guidance_scale,
|
| 287 |
+
num_inference_steps = num_inference_steps,
|
| 288 |
+
).videos
|
| 289 |
+
|
| 290 |
+
# if lora_path is not None:
|
| 291 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 292 |
+
|
| 293 |
+
def save_results():
|
| 294 |
+
if not os.path.exists(save_path):
|
| 295 |
+
os.makedirs(save_path, exist_ok=True)
|
| 296 |
+
|
| 297 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 298 |
+
prefix = str(index).zfill(8)
|
| 299 |
+
if video_length == 1:
|
| 300 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 301 |
+
|
| 302 |
+
image = sample[0, :, 0]
|
| 303 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 304 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 305 |
+
image = Image.fromarray(image)
|
| 306 |
+
image.save(video_path)
|
| 307 |
+
else:
|
| 308 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 309 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 310 |
+
|
| 311 |
+
if ulysses_degree * ring_degree > 1:
|
| 312 |
+
import torch.distributed as dist
|
| 313 |
+
if dist.get_rank() == 0:
|
| 314 |
+
save_results()
|
| 315 |
+
else:
|
| 316 |
+
save_results()
|
VideoX-Fun/examples/cogvideox_fun/predict_v2v.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
|
| 7 |
+
DPMSolverMultistepScheduler,
|
| 8 |
+
EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
|
| 9 |
+
PNDMScheduler)
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
current_file_path = os.path.abspath(__file__)
|
| 13 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 14 |
+
for project_root in project_roots:
|
| 15 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 16 |
+
|
| 17 |
+
from videox_fun.models import (AutoencoderKLCogVideoX,
|
| 18 |
+
CogVideoXTransformer3DModel, T5EncoderModel,
|
| 19 |
+
T5Tokenizer)
|
| 20 |
+
from videox_fun.pipeline import (CogVideoXFunPipeline,
|
| 21 |
+
CogVideoXFunInpaintPipeline)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 24 |
+
convert_weight_dtype_wrapper)
|
| 25 |
+
from videox_fun.utils.utils import get_video_to_video_latent, save_videos_grid
|
| 26 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# model path
|
| 56 |
+
model_name = "models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP"
|
| 57 |
+
|
| 58 |
+
# Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
|
| 59 |
+
sampler_name = "DDIM_Origin"
|
| 60 |
+
|
| 61 |
+
# Load pretrained model if need
|
| 62 |
+
transformer_path = None
|
| 63 |
+
vae_path = None
|
| 64 |
+
lora_path = None
|
| 65 |
+
# Other params
|
| 66 |
+
sample_size = [384, 672]
|
| 67 |
+
# V1.0 and V1.1 support up to 49 frames of video generation,
|
| 68 |
+
# while V1.5 supports up to 85 frames.
|
| 69 |
+
video_length = 49
|
| 70 |
+
fps = 8
|
| 71 |
+
|
| 72 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 73 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 74 |
+
weight_dtype = torch.bfloat16
|
| 75 |
+
# If you are preparing to redraw the reference video, set validation_video and validation_video_mask.
|
| 76 |
+
# If you do not use validation_video_mask, the entire video will be redrawn;
|
| 77 |
+
# if you use validation_video_mask, only a portion of the video will be redrawn.
|
| 78 |
+
# Please set a larger denoise_strength when using validation_video_mask, such as 1.00 instead of 0.70
|
| 79 |
+
validation_video = "asset/1.mp4"
|
| 80 |
+
validation_video_mask = None
|
| 81 |
+
denoise_strength = 0.70
|
| 82 |
+
|
| 83 |
+
# prompts
|
| 84 |
+
prompt = "A cute cat is playing the guitar. "
|
| 85 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 86 |
+
guidance_scale = 6.0
|
| 87 |
+
seed = 43
|
| 88 |
+
num_inference_steps = 50
|
| 89 |
+
lora_weight = 0.55
|
| 90 |
+
save_path = "samples/cogvideox-fun-videos_v2v"
|
| 91 |
+
|
| 92 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 93 |
+
|
| 94 |
+
transformer = CogVideoXTransformer3DModel.from_pretrained(
|
| 95 |
+
model_name,
|
| 96 |
+
subfolder="transformer",
|
| 97 |
+
low_cpu_mem_usage=True,
|
| 98 |
+
torch_dtype=weight_dtype,
|
| 99 |
+
).to(weight_dtype)
|
| 100 |
+
|
| 101 |
+
if transformer_path is not None:
|
| 102 |
+
print(f"From checkpoint: {transformer_path}")
|
| 103 |
+
if transformer_path.endswith("safetensors"):
|
| 104 |
+
from safetensors.torch import load_file, safe_open
|
| 105 |
+
state_dict = load_file(transformer_path)
|
| 106 |
+
else:
|
| 107 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 108 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 109 |
+
|
| 110 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 111 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 112 |
+
|
| 113 |
+
# Get Vae
|
| 114 |
+
vae = AutoencoderKLCogVideoX.from_pretrained(
|
| 115 |
+
model_name,
|
| 116 |
+
subfolder="vae"
|
| 117 |
+
).to(weight_dtype)
|
| 118 |
+
|
| 119 |
+
if vae_path is not None:
|
| 120 |
+
print(f"From checkpoint: {vae_path}")
|
| 121 |
+
if vae_path.endswith("safetensors"):
|
| 122 |
+
from safetensors.torch import load_file, safe_open
|
| 123 |
+
state_dict = load_file(vae_path)
|
| 124 |
+
else:
|
| 125 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 126 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 127 |
+
|
| 128 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 129 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 130 |
+
|
| 131 |
+
# Get tokenizer and text_encoder
|
| 132 |
+
tokenizer = T5Tokenizer.from_pretrained(
|
| 133 |
+
model_name, subfolder="tokenizer"
|
| 134 |
+
)
|
| 135 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 136 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# Get Scheduler
|
| 140 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 141 |
+
"Euler": EulerDiscreteScheduler,
|
| 142 |
+
"Euler A": EulerAncestralDiscreteScheduler,
|
| 143 |
+
"DPM++": DPMSolverMultistepScheduler,
|
| 144 |
+
"PNDM": PNDMScheduler,
|
| 145 |
+
"DDIM_Cog": CogVideoXDDIMScheduler,
|
| 146 |
+
"DDIM_Origin": DDIMScheduler,
|
| 147 |
+
}[sampler_name]
|
| 148 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 149 |
+
model_name,
|
| 150 |
+
subfolder="scheduler"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 154 |
+
pipeline = CogVideoXFunInpaintPipeline(
|
| 155 |
+
vae=vae,
|
| 156 |
+
tokenizer=tokenizer,
|
| 157 |
+
text_encoder=text_encoder,
|
| 158 |
+
transformer=transformer,
|
| 159 |
+
scheduler=scheduler,
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
pipeline = CogVideoXFunPipeline(
|
| 163 |
+
vae=vae,
|
| 164 |
+
tokenizer=tokenizer,
|
| 165 |
+
text_encoder=text_encoder,
|
| 166 |
+
transformer=transformer,
|
| 167 |
+
scheduler=scheduler,
|
| 168 |
+
)
|
| 169 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 170 |
+
from functools import partial
|
| 171 |
+
transformer.enable_multi_gpus_inference()
|
| 172 |
+
if fsdp_dit:
|
| 173 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 174 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 175 |
+
print("Add FSDP DIT")
|
| 176 |
+
if fsdp_text_encoder:
|
| 177 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 178 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 179 |
+
print("Add FSDP TEXT ENCODER")
|
| 180 |
+
|
| 181 |
+
if compile_dit:
|
| 182 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 183 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 184 |
+
print("Add Compile")
|
| 185 |
+
|
| 186 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 187 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 188 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 189 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 190 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 191 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 192 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 193 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 194 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 195 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 196 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 197 |
+
pipeline.to(device=device)
|
| 198 |
+
else:
|
| 199 |
+
pipeline.to(device=device)
|
| 200 |
+
|
| 201 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 202 |
+
|
| 203 |
+
if lora_path is not None:
|
| 204 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 205 |
+
|
| 206 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 207 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 208 |
+
if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 209 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 210 |
+
video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 211 |
+
input_video, input_video_mask, ref_image, clip_image = get_video_to_video_latent(validation_video, video_length=video_length, sample_size=sample_size, validation_video_mask=validation_video_mask, fps=fps)
|
| 212 |
+
|
| 213 |
+
with torch.no_grad():
|
| 214 |
+
sample = pipeline(
|
| 215 |
+
prompt,
|
| 216 |
+
num_frames = video_length,
|
| 217 |
+
negative_prompt = negative_prompt,
|
| 218 |
+
height = sample_size[0],
|
| 219 |
+
width = sample_size[1],
|
| 220 |
+
generator = generator,
|
| 221 |
+
guidance_scale = guidance_scale,
|
| 222 |
+
num_inference_steps = num_inference_steps,
|
| 223 |
+
|
| 224 |
+
video = input_video,
|
| 225 |
+
mask_video = input_video_mask,
|
| 226 |
+
strength = denoise_strength,
|
| 227 |
+
).videos
|
| 228 |
+
|
| 229 |
+
if lora_path is not None:
|
| 230 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 231 |
+
|
| 232 |
+
def save_results():
|
| 233 |
+
if not os.path.exists(save_path):
|
| 234 |
+
os.makedirs(save_path, exist_ok=True)
|
| 235 |
+
|
| 236 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 237 |
+
prefix = str(index).zfill(8)
|
| 238 |
+
if video_length == 1:
|
| 239 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 240 |
+
|
| 241 |
+
image = sample[0, :, 0]
|
| 242 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 243 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 244 |
+
image = Image.fromarray(image)
|
| 245 |
+
image.save(video_path)
|
| 246 |
+
else:
|
| 247 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 248 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 249 |
+
|
| 250 |
+
if ulysses_degree * ring_degree > 1:
|
| 251 |
+
import torch.distributed as dist
|
| 252 |
+
if dist.get_rank() == 0:
|
| 253 |
+
save_results()
|
| 254 |
+
else:
|
| 255 |
+
save_results()
|
VideoX-Fun/examples/cogvideox_fun/predict_v2v_control.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
|
| 8 |
+
DPMSolverMultistepScheduler,
|
| 9 |
+
EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
|
| 10 |
+
PNDMScheduler)
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from transformers import T5EncoderModel
|
| 13 |
+
|
| 14 |
+
current_file_path = os.path.abspath(__file__)
|
| 15 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 16 |
+
for project_root in project_roots:
|
| 17 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 18 |
+
|
| 19 |
+
from videox_fun.models import (AutoencoderKLCogVideoX,
|
| 20 |
+
CogVideoXTransformer3DModel, T5EncoderModel,
|
| 21 |
+
T5Tokenizer)
|
| 22 |
+
from videox_fun.pipeline import (CogVideoXFunControlPipeline,
|
| 23 |
+
CogVideoXFunInpaintPipeline)
|
| 24 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 25 |
+
convert_weight_dtype_wrapper)
|
| 26 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 27 |
+
from videox_fun.utils.utils import get_video_to_video_latent, save_videos_grid
|
| 28 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 29 |
+
|
| 30 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 31 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 32 |
+
#
|
| 33 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 34 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 39 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 40 |
+
#
|
| 41 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 42 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 43 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 44 |
+
# Multi GPUs config
|
| 45 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 46 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 47 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 48 |
+
ulysses_degree = 1
|
| 49 |
+
ring_degree = 1
|
| 50 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 51 |
+
fsdp_dit = False
|
| 52 |
+
fsdp_text_encoder = True
|
| 53 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 54 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 55 |
+
compile_dit = False
|
| 56 |
+
|
| 57 |
+
# model path
|
| 58 |
+
model_name = "models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-Pose"
|
| 59 |
+
|
| 60 |
+
# Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
|
| 61 |
+
sampler_name = "DDIM_Origin"
|
| 62 |
+
|
| 63 |
+
# Load pretrained model if need
|
| 64 |
+
transformer_path = None
|
| 65 |
+
vae_path = None
|
| 66 |
+
lora_path = None
|
| 67 |
+
# Other params
|
| 68 |
+
sample_size = [672, 384]
|
| 69 |
+
# V1.0 and V1.1 support up to 49 frames of video generation,
|
| 70 |
+
# while V1.5 supports up to 85 frames.
|
| 71 |
+
video_length = 49
|
| 72 |
+
fps = 8
|
| 73 |
+
|
| 74 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 75 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 76 |
+
weight_dtype = torch.bfloat16
|
| 77 |
+
control_video = "asset/pose.mp4"
|
| 78 |
+
|
| 79 |
+
# prompts
|
| 80 |
+
prompt = "A young woman with beautiful face, dressed in white, is moving her body. "
|
| 81 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 82 |
+
guidance_scale = 6.0
|
| 83 |
+
seed = 43
|
| 84 |
+
num_inference_steps = 50
|
| 85 |
+
lora_weight = 0.55
|
| 86 |
+
save_path = "samples/cogvideox-fun-videos_control"
|
| 87 |
+
|
| 88 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 89 |
+
|
| 90 |
+
transformer = CogVideoXTransformer3DModel.from_pretrained(
|
| 91 |
+
model_name,
|
| 92 |
+
subfolder="transformer",
|
| 93 |
+
low_cpu_mem_usage=True,
|
| 94 |
+
torch_dtype=weight_dtype,
|
| 95 |
+
).to(weight_dtype)
|
| 96 |
+
|
| 97 |
+
if transformer_path is not None:
|
| 98 |
+
print(f"From checkpoint: {transformer_path}")
|
| 99 |
+
if transformer_path.endswith("safetensors"):
|
| 100 |
+
from safetensors.torch import load_file, safe_open
|
| 101 |
+
state_dict = load_file(transformer_path)
|
| 102 |
+
else:
|
| 103 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 104 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 105 |
+
|
| 106 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 107 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 108 |
+
|
| 109 |
+
# Get Vae
|
| 110 |
+
vae = AutoencoderKLCogVideoX.from_pretrained(
|
| 111 |
+
model_name,
|
| 112 |
+
subfolder="vae"
|
| 113 |
+
).to(weight_dtype)
|
| 114 |
+
|
| 115 |
+
if vae_path is not None:
|
| 116 |
+
print(f"From checkpoint: {vae_path}")
|
| 117 |
+
if vae_path.endswith("safetensors"):
|
| 118 |
+
from safetensors.torch import load_file, safe_open
|
| 119 |
+
state_dict = load_file(vae_path)
|
| 120 |
+
else:
|
| 121 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 122 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 123 |
+
|
| 124 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 125 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 126 |
+
|
| 127 |
+
# Get tokenizer and text_encoder
|
| 128 |
+
tokenizer = T5Tokenizer.from_pretrained(
|
| 129 |
+
model_name, subfolder="tokenizer"
|
| 130 |
+
)
|
| 131 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 132 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Get Scheduler
|
| 136 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 137 |
+
"Euler": EulerDiscreteScheduler,
|
| 138 |
+
"Euler A": EulerAncestralDiscreteScheduler,
|
| 139 |
+
"DPM++": DPMSolverMultistepScheduler,
|
| 140 |
+
"PNDM": PNDMScheduler,
|
| 141 |
+
"DDIM_Cog": CogVideoXDDIMScheduler,
|
| 142 |
+
"DDIM_Origin": DDIMScheduler,
|
| 143 |
+
}[sampler_name]
|
| 144 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 145 |
+
model_name,
|
| 146 |
+
subfolder="scheduler"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
pipeline = CogVideoXFunControlPipeline(
|
| 150 |
+
vae=vae,
|
| 151 |
+
tokenizer=tokenizer,
|
| 152 |
+
text_encoder=text_encoder,
|
| 153 |
+
transformer=transformer,
|
| 154 |
+
scheduler=scheduler,
|
| 155 |
+
)
|
| 156 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 157 |
+
from functools import partial
|
| 158 |
+
transformer.enable_multi_gpus_inference()
|
| 159 |
+
if fsdp_dit:
|
| 160 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 161 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 162 |
+
print("Add FSDP DIT")
|
| 163 |
+
if fsdp_text_encoder:
|
| 164 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 165 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 166 |
+
print("Add FSDP TEXT ENCODER")
|
| 167 |
+
|
| 168 |
+
if compile_dit:
|
| 169 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 170 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 171 |
+
print("Add Compile")
|
| 172 |
+
|
| 173 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 174 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 175 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 176 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 177 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 178 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 179 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 180 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 181 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 182 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 183 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 184 |
+
pipeline.to(device=device)
|
| 185 |
+
else:
|
| 186 |
+
pipeline.to(device=device)
|
| 187 |
+
|
| 188 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 189 |
+
|
| 190 |
+
if lora_path is not None:
|
| 191 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 192 |
+
|
| 193 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 194 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 195 |
+
if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 196 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 197 |
+
video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 198 |
+
input_video, input_video_mask, ref_image, clip_image = get_video_to_video_latent(control_video, video_length=video_length, sample_size=sample_size, fps=fps)
|
| 199 |
+
|
| 200 |
+
with torch.no_grad():
|
| 201 |
+
sample = pipeline(
|
| 202 |
+
prompt,
|
| 203 |
+
num_frames = video_length,
|
| 204 |
+
negative_prompt = negative_prompt,
|
| 205 |
+
height = sample_size[0],
|
| 206 |
+
width = sample_size[1],
|
| 207 |
+
generator = generator,
|
| 208 |
+
guidance_scale = guidance_scale,
|
| 209 |
+
num_inference_steps = num_inference_steps,
|
| 210 |
+
|
| 211 |
+
control_video = input_video,
|
| 212 |
+
).videos
|
| 213 |
+
|
| 214 |
+
if lora_path is not None:
|
| 215 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 216 |
+
|
| 217 |
+
def save_results():
|
| 218 |
+
if not os.path.exists(save_path):
|
| 219 |
+
os.makedirs(save_path, exist_ok=True)
|
| 220 |
+
|
| 221 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 222 |
+
prefix = str(index).zfill(8)
|
| 223 |
+
if video_length == 1:
|
| 224 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 225 |
+
|
| 226 |
+
image = sample[0, :, 0]
|
| 227 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 228 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 229 |
+
image = Image.fromarray(image)
|
| 230 |
+
image.save(video_path)
|
| 231 |
+
else:
|
| 232 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 233 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 234 |
+
|
| 235 |
+
if ulysses_degree * ring_degree > 1:
|
| 236 |
+
import torch.distributed as dist
|
| 237 |
+
if dist.get_rank() == 0:
|
| 238 |
+
save_results()
|
| 239 |
+
else:
|
| 240 |
+
save_results()
|
VideoX-Fun/examples/flux/predict_t2i.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 13 |
+
from videox_fun.models import (AutoencoderKL, CLIPTextModel, CLIPTokenizer,
|
| 14 |
+
FluxTransformer2DModel, T5EncoderModel,
|
| 15 |
+
T5TokenizerFast)
|
| 16 |
+
from videox_fun.pipeline import FluxPipeline
|
| 17 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 18 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 19 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 20 |
+
convert_weight_dtype_wrapper)
|
| 21 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 22 |
+
|
| 23 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 24 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 25 |
+
#
|
| 26 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 27 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 28 |
+
#
|
| 29 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 30 |
+
#
|
| 31 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 35 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 36 |
+
GPU_memory_mode = "model_cpu_offload_and_qfloat8"
|
| 37 |
+
# Multi GPUs config
|
| 38 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 39 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 40 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 41 |
+
ulysses_degree = 1
|
| 42 |
+
ring_degree = 1
|
| 43 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 44 |
+
fsdp_dit = False
|
| 45 |
+
fsdp_text_encoder = False
|
| 46 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 47 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 48 |
+
compile_dit = False
|
| 49 |
+
|
| 50 |
+
# model path
|
| 51 |
+
model_name = "models/Diffusion_Transformer/FLUX.1-dev"
|
| 52 |
+
|
| 53 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 54 |
+
sampler_name = "Flow"
|
| 55 |
+
|
| 56 |
+
# Load pretrained model if need
|
| 57 |
+
transformer_path = None
|
| 58 |
+
vae_path = None
|
| 59 |
+
lora_path = None
|
| 60 |
+
|
| 61 |
+
# Other params
|
| 62 |
+
sample_size = [1344, 768]
|
| 63 |
+
|
| 64 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 65 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 66 |
+
weight_dtype = torch.bfloat16
|
| 67 |
+
prompt = "1girl, black_hair, brown_eyes, earrings, freckles, grey_background, jewelry, lips, long_hair, looking_at_viewer, nose, piercing, realistic, red_lips, solo, upper_body"
|
| 68 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 69 |
+
guidance_scale = 1.0
|
| 70 |
+
seed = 43
|
| 71 |
+
num_inference_steps = 50
|
| 72 |
+
lora_weight = 0.70
|
| 73 |
+
save_path = "samples/flux-t2i"
|
| 74 |
+
|
| 75 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 76 |
+
|
| 77 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 78 |
+
model_name,
|
| 79 |
+
subfolder="transformer",
|
| 80 |
+
low_cpu_mem_usage=True,
|
| 81 |
+
torch_dtype=weight_dtype,
|
| 82 |
+
).to(weight_dtype)
|
| 83 |
+
|
| 84 |
+
if transformer_path is not None:
|
| 85 |
+
print(f"From checkpoint: {transformer_path}")
|
| 86 |
+
if transformer_path.endswith("safetensors"):
|
| 87 |
+
from safetensors.torch import load_file, safe_open
|
| 88 |
+
state_dict = load_file(transformer_path)
|
| 89 |
+
else:
|
| 90 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 91 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 92 |
+
|
| 93 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 94 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 95 |
+
|
| 96 |
+
# Get Vae
|
| 97 |
+
vae = AutoencoderKL.from_pretrained(
|
| 98 |
+
model_name,
|
| 99 |
+
subfolder="vae"
|
| 100 |
+
).to(weight_dtype)
|
| 101 |
+
|
| 102 |
+
if vae_path is not None:
|
| 103 |
+
print(f"From checkpoint: {vae_path}")
|
| 104 |
+
if vae_path.endswith("safetensors"):
|
| 105 |
+
from safetensors.torch import load_file, safe_open
|
| 106 |
+
state_dict = load_file(vae_path)
|
| 107 |
+
else:
|
| 108 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 109 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 110 |
+
|
| 111 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 112 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 113 |
+
|
| 114 |
+
# Get tokenizer and text_encoder
|
| 115 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 116 |
+
model_name, subfolder="tokenizer"
|
| 117 |
+
)
|
| 118 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 119 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
tokenizer_2 = T5TokenizerFast.from_pretrained(
|
| 123 |
+
model_name, subfolder="tokenizer_2"
|
| 124 |
+
)
|
| 125 |
+
text_encoder_2 = T5EncoderModel.from_pretrained(
|
| 126 |
+
model_name, subfolder="text_encoder_2", torch_dtype=weight_dtype
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Get Scheduler
|
| 130 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 131 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 132 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 133 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 134 |
+
}[sampler_name]
|
| 135 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 136 |
+
model_name,
|
| 137 |
+
subfolder="scheduler"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
pipeline = FluxPipeline(
|
| 141 |
+
vae=vae,
|
| 142 |
+
tokenizer=tokenizer,
|
| 143 |
+
text_encoder=text_encoder,
|
| 144 |
+
tokenizer_2=tokenizer_2,
|
| 145 |
+
text_encoder_2=text_encoder_2,
|
| 146 |
+
transformer=transformer,
|
| 147 |
+
scheduler=scheduler,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 151 |
+
from functools import partial
|
| 152 |
+
transformer.enable_multi_gpus_inference()
|
| 153 |
+
if fsdp_dit:
|
| 154 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 155 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 156 |
+
print("Add FSDP DIT")
|
| 157 |
+
if fsdp_text_encoder:
|
| 158 |
+
from functools import partial
|
| 159 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 160 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype, module_to_wrapper=text_encoder.language_model.layers)
|
| 161 |
+
text_encoder = shard_fn(text_encoder)
|
| 162 |
+
print("Add FSDP TEXT ENCODER")
|
| 163 |
+
|
| 164 |
+
if compile_dit:
|
| 165 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 166 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 167 |
+
print("Add Compile")
|
| 168 |
+
|
| 169 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 170 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 171 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 172 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["img_in", "txt_in", "timestep"], device=device)
|
| 173 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 174 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 175 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 176 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 177 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 178 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["img_in", "txt_in", "timestep"], device=device)
|
| 179 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 180 |
+
pipeline.to(device=device)
|
| 181 |
+
else:
|
| 182 |
+
pipeline.to(device=device)
|
| 183 |
+
|
| 184 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 185 |
+
|
| 186 |
+
if lora_path is not None:
|
| 187 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 188 |
+
|
| 189 |
+
with torch.no_grad():
|
| 190 |
+
sample = pipeline(
|
| 191 |
+
prompt,
|
| 192 |
+
negative_prompt = negative_prompt,
|
| 193 |
+
height = sample_size[0],
|
| 194 |
+
width = sample_size[1],
|
| 195 |
+
generator = generator,
|
| 196 |
+
true_cfg_scale = guidance_scale,
|
| 197 |
+
num_inference_steps = num_inference_steps,
|
| 198 |
+
).images
|
| 199 |
+
|
| 200 |
+
if lora_path is not None:
|
| 201 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 202 |
+
|
| 203 |
+
def save_results():
|
| 204 |
+
if not os.path.exists(save_path):
|
| 205 |
+
os.makedirs(save_path, exist_ok=True)
|
| 206 |
+
|
| 207 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 208 |
+
prefix = str(index).zfill(8)
|
| 209 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 210 |
+
image = sample[0]
|
| 211 |
+
image.save(video_path)
|
| 212 |
+
|
| 213 |
+
if ulysses_degree * ring_degree > 1:
|
| 214 |
+
import torch.distributed as dist
|
| 215 |
+
if dist.get_rank() == 0:
|
| 216 |
+
save_results()
|
| 217 |
+
else:
|
| 218 |
+
save_results()
|
VideoX-Fun/examples/phantom/predict_s2v.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, AutoTokenizer,
|
| 18 |
+
WanT5EncoderModel, WanTransformer3DModel)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanFunPhantomPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 22 |
+
convert_weight_dtype_wrapper,
|
| 23 |
+
replace_parameters_by_name)
|
| 24 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 25 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_latent,
|
| 26 |
+
save_videos_grid)
|
| 27 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 28 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 29 |
+
|
| 30 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 31 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 32 |
+
#
|
| 33 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 34 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 39 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 40 |
+
#
|
| 41 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 42 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 43 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 44 |
+
# Multi GPUs config
|
| 45 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 46 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 47 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 48 |
+
ulysses_degree = 1
|
| 49 |
+
ring_degree = 1
|
| 50 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 51 |
+
fsdp_dit = False
|
| 52 |
+
fsdp_text_encoder = True
|
| 53 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 54 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 55 |
+
compile_dit = False
|
| 56 |
+
|
| 57 |
+
# Support TeaCache.
|
| 58 |
+
enable_teacache = True
|
| 59 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 60 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 61 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 62 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 63 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 64 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 65 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 66 |
+
teacache_threshold = 0.10
|
| 67 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 68 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 69 |
+
num_skip_start_steps = 5
|
| 70 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 71 |
+
teacache_offload = False
|
| 72 |
+
|
| 73 |
+
# Skip some cfg steps in inference
|
| 74 |
+
# Recommended to be set between 0.00 and 0.25
|
| 75 |
+
cfg_skip_ratio = 0
|
| 76 |
+
|
| 77 |
+
# Riflex config
|
| 78 |
+
enable_riflex = False
|
| 79 |
+
# Index of intrinsic frequency
|
| 80 |
+
riflex_k = 6
|
| 81 |
+
|
| 82 |
+
# Config and model path
|
| 83 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 84 |
+
# model path
|
| 85 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 86 |
+
|
| 87 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 88 |
+
sampler_name = "Flow_Unipc"
|
| 89 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 90 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 91 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 92 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 93 |
+
shift = 3
|
| 94 |
+
|
| 95 |
+
# Load pretrained model if need
|
| 96 |
+
transformer_path = "models/Personalized_Model/Phantom-Wan-1.3B.safetensors"
|
| 97 |
+
vae_path = None
|
| 98 |
+
lora_path = None
|
| 99 |
+
|
| 100 |
+
# Other params
|
| 101 |
+
sample_size = [480, 832]
|
| 102 |
+
video_length = 81
|
| 103 |
+
fps = 16
|
| 104 |
+
|
| 105 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 106 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 107 |
+
weight_dtype = torch.bfloat16
|
| 108 |
+
subject_ref_images = ["asset/ref_1.png", "asset/ref_2.png"]
|
| 109 |
+
|
| 110 |
+
# 使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性
|
| 111 |
+
# 在neg prompt中添加"安静,固定"等词语可以增加动态性。
|
| 112 |
+
prompt = "暖阳漫过草地,扎着双马尾、头戴绿色蝴蝶结、身穿浅绿色连衣裙的小女孩蹲在盛开的雏菊旁。她身旁一只棕白相间的狗狗吐着舌头,毛茸茸尾巴欢快摇晃。小女孩笑着举起黄红配色、带有蓝色按钮的玩具相机,将和狗狗的欢乐瞬间定格。"
|
| 113 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 114 |
+
|
| 115 |
+
# Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability
|
| 116 |
+
# Adding words such as "quiet, solid" to the neg prompt can increase dynamism.
|
| 117 |
+
# prompt = "A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical."
|
| 118 |
+
# negative_prompt = "Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code."
|
| 119 |
+
guidance_scale = 6.0
|
| 120 |
+
seed = 43
|
| 121 |
+
num_inference_steps = 50
|
| 122 |
+
lora_weight = 0.55
|
| 123 |
+
save_path = "samples/wan-videos-phantom"
|
| 124 |
+
|
| 125 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 126 |
+
config = OmegaConf.load(config_path)
|
| 127 |
+
|
| 128 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 129 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 130 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 131 |
+
low_cpu_mem_usage=True,
|
| 132 |
+
torch_dtype=weight_dtype,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
if transformer_path is not None:
|
| 136 |
+
print(f"From checkpoint: {transformer_path}")
|
| 137 |
+
if transformer_path.endswith("safetensors"):
|
| 138 |
+
from safetensors.torch import load_file, safe_open
|
| 139 |
+
state_dict = load_file(transformer_path)
|
| 140 |
+
else:
|
| 141 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 142 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 143 |
+
|
| 144 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 145 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 146 |
+
|
| 147 |
+
# Get Vae
|
| 148 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 149 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 150 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 151 |
+
).to(weight_dtype)
|
| 152 |
+
|
| 153 |
+
if vae_path is not None:
|
| 154 |
+
print(f"From checkpoint: {vae_path}")
|
| 155 |
+
if vae_path.endswith("safetensors"):
|
| 156 |
+
from safetensors.torch import load_file, safe_open
|
| 157 |
+
state_dict = load_file(vae_path)
|
| 158 |
+
else:
|
| 159 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 160 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 161 |
+
|
| 162 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 163 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 164 |
+
|
| 165 |
+
# Get Tokenizer
|
| 166 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 167 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Get Text encoder
|
| 171 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 172 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 173 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 174 |
+
low_cpu_mem_usage=True,
|
| 175 |
+
torch_dtype=weight_dtype,
|
| 176 |
+
)
|
| 177 |
+
text_encoder = text_encoder.eval()
|
| 178 |
+
|
| 179 |
+
# Get Scheduler
|
| 180 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 181 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 182 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 183 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 184 |
+
}[sampler_name]
|
| 185 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 186 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 187 |
+
scheduler = Chosen_Scheduler(
|
| 188 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Get Pipeline
|
| 192 |
+
pipeline = WanFunPhantomPipeline(
|
| 193 |
+
transformer=transformer,
|
| 194 |
+
vae=vae,
|
| 195 |
+
tokenizer=tokenizer,
|
| 196 |
+
text_encoder=text_encoder,
|
| 197 |
+
scheduler=scheduler
|
| 198 |
+
)
|
| 199 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 200 |
+
from functools import partial
|
| 201 |
+
transformer.enable_multi_gpus_inference()
|
| 202 |
+
if fsdp_dit:
|
| 203 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 204 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 205 |
+
print("Add FSDP DIT")
|
| 206 |
+
if fsdp_text_encoder:
|
| 207 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 208 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 209 |
+
print("Add FSDP TEXT ENCODER")
|
| 210 |
+
|
| 211 |
+
if compile_dit:
|
| 212 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 213 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 214 |
+
print("Add Compile")
|
| 215 |
+
|
| 216 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 217 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 218 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 219 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 220 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 221 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 222 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 223 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 224 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 225 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 226 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 227 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 228 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 229 |
+
pipeline.to(device=device)
|
| 230 |
+
else:
|
| 231 |
+
pipeline.to(device=device)
|
| 232 |
+
|
| 233 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 234 |
+
if coefficients is not None:
|
| 235 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 236 |
+
pipeline.transformer.enable_teacache(
|
| 237 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if cfg_skip_ratio is not None:
|
| 241 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 242 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 243 |
+
|
| 244 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 245 |
+
|
| 246 |
+
if lora_path is not None:
|
| 247 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 248 |
+
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 251 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 252 |
+
|
| 253 |
+
if enable_riflex:
|
| 254 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 255 |
+
|
| 256 |
+
if subject_ref_images is not None:
|
| 257 |
+
subject_ref_images = [get_image_latent(_subject_ref_image, sample_size=sample_size, padding=True) for _subject_ref_image in subject_ref_images]
|
| 258 |
+
subject_ref_images = torch.cat(subject_ref_images, dim=2)
|
| 259 |
+
|
| 260 |
+
sample = pipeline(
|
| 261 |
+
prompt,
|
| 262 |
+
num_frames = video_length,
|
| 263 |
+
negative_prompt = negative_prompt,
|
| 264 |
+
height = sample_size[0],
|
| 265 |
+
width = sample_size[1],
|
| 266 |
+
generator = generator,
|
| 267 |
+
guidance_scale = guidance_scale,
|
| 268 |
+
num_inference_steps = num_inference_steps,
|
| 269 |
+
|
| 270 |
+
subject_ref_images = subject_ref_images,
|
| 271 |
+
shift = shift,
|
| 272 |
+
).videos
|
| 273 |
+
|
| 274 |
+
if lora_path is not None:
|
| 275 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 276 |
+
|
| 277 |
+
def save_results():
|
| 278 |
+
if not os.path.exists(save_path):
|
| 279 |
+
os.makedirs(save_path, exist_ok=True)
|
| 280 |
+
|
| 281 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 282 |
+
prefix = str(index).zfill(8)
|
| 283 |
+
if video_length == 1:
|
| 284 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 285 |
+
|
| 286 |
+
image = sample[0, :, 0]
|
| 287 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 288 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 289 |
+
image = Image.fromarray(image)
|
| 290 |
+
image.save(video_path)
|
| 291 |
+
else:
|
| 292 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 293 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 294 |
+
|
| 295 |
+
if ulysses_degree * ring_degree > 1:
|
| 296 |
+
import torch.distributed as dist
|
| 297 |
+
if dist.get_rank() == 0:
|
| 298 |
+
save_results()
|
| 299 |
+
else:
|
| 300 |
+
save_results()
|
VideoX-Fun/examples/qwenimage/predict_t2i.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from diffusers import (FlowMatchEulerDiscreteScheduler)
|
| 7 |
+
|
| 8 |
+
current_file_path = os.path.abspath(__file__)
|
| 9 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 10 |
+
for project_root in project_roots:
|
| 11 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 12 |
+
|
| 13 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 14 |
+
from videox_fun.models import (AutoencoderKLQwenImage,
|
| 15 |
+
Qwen2_5_VLForConditionalGeneration,
|
| 16 |
+
Qwen2Tokenizer, QwenImageTransformer2DModel)
|
| 17 |
+
from videox_fun.pipeline import QwenImagePipeline
|
| 18 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 19 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
|
| 24 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 25 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 26 |
+
#
|
| 27 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 28 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 31 |
+
#
|
| 32 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 33 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 34 |
+
#
|
| 35 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 36 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 37 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 38 |
+
# Multi GPUs config
|
| 39 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 40 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 41 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 42 |
+
ulysses_degree = 1
|
| 43 |
+
ring_degree = 1
|
| 44 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 45 |
+
fsdp_dit = False
|
| 46 |
+
fsdp_text_encoder = False
|
| 47 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 48 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 49 |
+
compile_dit = False
|
| 50 |
+
|
| 51 |
+
# model path
|
| 52 |
+
model_name = "models/Diffusion_Transformer/Qwen-Image"
|
| 53 |
+
|
| 54 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 55 |
+
sampler_name = "Flow"
|
| 56 |
+
|
| 57 |
+
# Load pretrained model if need
|
| 58 |
+
transformer_path = None
|
| 59 |
+
vae_path = None
|
| 60 |
+
lora_path = None
|
| 61 |
+
|
| 62 |
+
# Other params
|
| 63 |
+
sample_size = [1344, 768]
|
| 64 |
+
|
| 65 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 66 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 67 |
+
weight_dtype = torch.bfloat16
|
| 68 |
+
prompt = "1girl, black_hair, brown_eyes, earrings, freckles, grey_background, jewelry, lips, long_hair, looking_at_viewer, nose, piercing, realistic, red_lips, solo, upper_body"
|
| 69 |
+
negative_prompt = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion. "
|
| 70 |
+
guidance_scale = 6.0
|
| 71 |
+
seed = 43
|
| 72 |
+
num_inference_steps = 50
|
| 73 |
+
lora_weight = 0.55
|
| 74 |
+
save_path = "samples/qwenimage-t2i"
|
| 75 |
+
|
| 76 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 77 |
+
|
| 78 |
+
transformer = QwenImageTransformer2DModel.from_pretrained(
|
| 79 |
+
model_name,
|
| 80 |
+
subfolder="transformer",
|
| 81 |
+
low_cpu_mem_usage=True,
|
| 82 |
+
torch_dtype=weight_dtype,
|
| 83 |
+
).to(weight_dtype)
|
| 84 |
+
|
| 85 |
+
if transformer_path is not None:
|
| 86 |
+
print(f"From checkpoint: {transformer_path}")
|
| 87 |
+
if transformer_path.endswith("safetensors"):
|
| 88 |
+
from safetensors.torch import load_file, safe_open
|
| 89 |
+
state_dict = load_file(transformer_path)
|
| 90 |
+
else:
|
| 91 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 92 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 93 |
+
|
| 94 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 95 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 96 |
+
|
| 97 |
+
# Get Vae
|
| 98 |
+
vae = AutoencoderKLQwenImage.from_pretrained(
|
| 99 |
+
model_name,
|
| 100 |
+
subfolder="vae"
|
| 101 |
+
).to(weight_dtype)
|
| 102 |
+
|
| 103 |
+
if vae_path is not None:
|
| 104 |
+
print(f"From checkpoint: {vae_path}")
|
| 105 |
+
if vae_path.endswith("safetensors"):
|
| 106 |
+
from safetensors.torch import load_file, safe_open
|
| 107 |
+
state_dict = load_file(vae_path)
|
| 108 |
+
else:
|
| 109 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 110 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 111 |
+
|
| 112 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 113 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 114 |
+
|
| 115 |
+
# Get tokenizer and text_encoder
|
| 116 |
+
tokenizer = Qwen2Tokenizer.from_pretrained(
|
| 117 |
+
model_name, subfolder="tokenizer"
|
| 118 |
+
)
|
| 119 |
+
text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 120 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Get Scheduler
|
| 124 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 125 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 126 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 127 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 128 |
+
}[sampler_name]
|
| 129 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 130 |
+
model_name,
|
| 131 |
+
subfolder="scheduler"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
pipeline = QwenImagePipeline(
|
| 135 |
+
vae=vae,
|
| 136 |
+
tokenizer=tokenizer,
|
| 137 |
+
text_encoder=text_encoder,
|
| 138 |
+
transformer=transformer,
|
| 139 |
+
scheduler=scheduler,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 143 |
+
from functools import partial
|
| 144 |
+
transformer.enable_multi_gpus_inference()
|
| 145 |
+
if fsdp_dit:
|
| 146 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 147 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 148 |
+
print("Add FSDP DIT")
|
| 149 |
+
if fsdp_text_encoder:
|
| 150 |
+
from functools import partial
|
| 151 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 152 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype, module_to_wrapper=text_encoder.language_model.layers)
|
| 153 |
+
text_encoder = shard_fn(text_encoder)
|
| 154 |
+
print("Add FSDP TEXT ENCODER")
|
| 155 |
+
|
| 156 |
+
if compile_dit:
|
| 157 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 158 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 159 |
+
print("Add Compile")
|
| 160 |
+
|
| 161 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 162 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 163 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 164 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["img_in", "txt_in", "timestep"], device=device)
|
| 165 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 166 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 167 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 168 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 169 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 170 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["img_in", "txt_in", "timestep"], device=device)
|
| 171 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 172 |
+
pipeline.to(device=device)
|
| 173 |
+
else:
|
| 174 |
+
pipeline.to(device=device)
|
| 175 |
+
|
| 176 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 177 |
+
|
| 178 |
+
if lora_path is not None:
|
| 179 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 180 |
+
|
| 181 |
+
with torch.no_grad():
|
| 182 |
+
sample = pipeline(
|
| 183 |
+
prompt,
|
| 184 |
+
negative_prompt = negative_prompt,
|
| 185 |
+
height = sample_size[0],
|
| 186 |
+
width = sample_size[1],
|
| 187 |
+
generator = generator,
|
| 188 |
+
true_cfg_scale = guidance_scale,
|
| 189 |
+
num_inference_steps = num_inference_steps,
|
| 190 |
+
).images
|
| 191 |
+
|
| 192 |
+
if lora_path is not None:
|
| 193 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 194 |
+
|
| 195 |
+
def save_results():
|
| 196 |
+
if not os.path.exists(save_path):
|
| 197 |
+
os.makedirs(save_path, exist_ok=True)
|
| 198 |
+
|
| 199 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 200 |
+
prefix = str(index).zfill(8)
|
| 201 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 202 |
+
image = sample[0]
|
| 203 |
+
image.save(video_path)
|
| 204 |
+
|
| 205 |
+
if ulysses_degree * ring_degree > 1:
|
| 206 |
+
import torch.distributed as dist
|
| 207 |
+
if dist.get_rank() == 0:
|
| 208 |
+
save_results()
|
| 209 |
+
else:
|
| 210 |
+
save_results()
|
VideoX-Fun/examples/wan2.1/__pycache__/pred_ori.cpython-313.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
VideoX-Fun/examples/wan2.1/app.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.api.api import (infer_forward_api,
|
| 13 |
+
update_diffusion_transformer_api)
|
| 14 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 15 |
+
from videox_fun.ui.wan_ui import ui, ui_client, ui_host
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
# Choose the ui mode
|
| 19 |
+
# "normal" refers to the standard UI, which allows users to click to switch models, change model types, and more.
|
| 20 |
+
# "host" represents the hosting mode, where the model is loaded directly at startup and can be accessed via
|
| 21 |
+
# the API to return generation results.
|
| 22 |
+
# "client" represents the client mode, offering a simple UI that sends requests to a remote API for generation.
|
| 23 |
+
ui_mode = "normal"
|
| 24 |
+
|
| 25 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 26 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
#
|
| 28 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 31 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 32 |
+
#
|
| 33 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 34 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 35 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 36 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 37 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 38 |
+
compile_dit = False
|
| 39 |
+
|
| 40 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 41 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 42 |
+
weight_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# Server ip
|
| 45 |
+
server_name = "0.0.0.0"
|
| 46 |
+
server_port = 7860
|
| 47 |
+
|
| 48 |
+
# Config path
|
| 49 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 50 |
+
# Params below is used when ui_mode = "host"
|
| 51 |
+
# Model path of the pretrained model
|
| 52 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-I2V-14B-480P"
|
| 53 |
+
|
| 54 |
+
if ui_mode == "host":
|
| 55 |
+
demo, controller = ui_host(GPU_memory_mode, flow_scheduler_dict, model_name, "Inpaint", config_path, compile_dit, weight_dtype)
|
| 56 |
+
elif ui_mode == "client":
|
| 57 |
+
demo, controller = ui_client(flow_scheduler_dict, model_name)
|
| 58 |
+
else:
|
| 59 |
+
demo, controller = ui(GPU_memory_mode, flow_scheduler_dict, config_path, compile_dit, weight_dtype)
|
| 60 |
+
|
| 61 |
+
def gr_launch():
|
| 62 |
+
# launch gradio
|
| 63 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 64 |
+
server_name=server_name,
|
| 65 |
+
server_port=server_port,
|
| 66 |
+
prevent_thread_lock=True
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# launch api
|
| 70 |
+
infer_forward_api(None, app, controller)
|
| 71 |
+
update_diffusion_transformer_api(None, app, controller)
|
| 72 |
+
|
| 73 |
+
gr_launch()
|
| 74 |
+
|
| 75 |
+
# not close the python
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(5)
|
VideoX-Fun/examples/wan2.1/launch_api.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import ray
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.api.api_multi_nodes import (MultiNodesEngine,
|
| 16 |
+
multi_nodes_infer_forward_api)
|
| 17 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 18 |
+
from videox_fun.ui.wan_ui import Wan_Controller
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description='xDiT HTTP Service')
|
| 22 |
+
parser.add_argument('--world_size', type=int, default=8, help='Number of parallel workers')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--gpu_memory_mode', type=str, default="model_cpu_offload", help='''
|
| 25 |
+
GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8].
|
| 26 |
+
model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
|
| 28 |
+
model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 29 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 30 |
+
|
| 31 |
+
model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 32 |
+
|
| 33 |
+
model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 34 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
'''
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument('--ulysses_degree', type=int, default=4, help='Degree of Ulysses configuration')
|
| 38 |
+
parser.add_argument('--ring_degree', type=int, default=2, help='Degree of Ring configuration')
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
'--compile_dit', action='store_true', help='''
|
| 41 |
+
Enable compile dit.
|
| 42 |
+
Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 43 |
+
The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 44 |
+
'''
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument('--fsdp_dit', action='store_true', help="Use DIT FSDP to save more GPU memory in multi gpus.")
|
| 47 |
+
parser.add_argument('--fsdp_text_encoder', action='store_true', help="Use Text Encoder FSDP to save more GPU memory in multi gpus.")
|
| 48 |
+
parser.add_argument('--weight_dtype', type=str, default='bf16', help='Weight data type')
|
| 49 |
+
parser.add_argument('--server_name', type=str, default="0.0.0.0", help='Server IP address')
|
| 50 |
+
parser.add_argument('--server_port', type=int, default=7860, help='Server Port')
|
| 51 |
+
parser.add_argument('--config_path', type=str, default="config/wan2.1/wan_civitai.yaml", help='Path to config file')
|
| 52 |
+
parser.add_argument('--model_name', type=str, default="models/Diffusion_Transformer/Wan2.1-T2V-1.3B", help='Model path')
|
| 53 |
+
parser.add_argument('--model_type', type=str, default="Inpaint", help='Model type (Inpaint/Control)')
|
| 54 |
+
parser.add_argument('--savedir_sample', type=str, default=None, help='The save directory for samples')
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
weight_dtype = torch.float32
|
| 58 |
+
if args.weight_dtype == "bf16":
|
| 59 |
+
weight_dtype = torch.bfloat16
|
| 60 |
+
elif args.weight_dtype == "fp16":
|
| 61 |
+
weight_dtype = torch.float16
|
| 62 |
+
|
| 63 |
+
engine = MultiNodesEngine(
|
| 64 |
+
world_size=args.world_size, Controller=Wan_Controller,
|
| 65 |
+
GPU_memory_mode=args.gpu_memory_mode, scheduler_dict=flow_scheduler_dict, model_name=args.model_name, model_type=args.model_type, config_path=args.config_path,
|
| 66 |
+
ulysses_degree=args.ulysses_degree, ring_degree=args.ring_degree,
|
| 67 |
+
fsdp_dit=args.fsdp_dit, fsdp_text_encoder=args.fsdp_text_encoder, compile_dit=args.compile_dit,
|
| 68 |
+
weight_dtype=weight_dtype, savedir_sample=args.savedir_sample,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def gr_launch():
|
| 72 |
+
# launch gradio
|
| 73 |
+
with gr.Blocks() as demo:
|
| 74 |
+
gr.Markdown("")
|
| 75 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 76 |
+
server_name=args.server_name,
|
| 77 |
+
server_port=args.server_port,
|
| 78 |
+
prevent_thread_lock=True
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# launch api
|
| 82 |
+
multi_nodes_infer_forward_api(None, app, engine)
|
| 83 |
+
|
| 84 |
+
gr_launch()
|
| 85 |
+
|
| 86 |
+
# not close the python
|
| 87 |
+
while True:
|
| 88 |
+
time.sleep(5)
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|
VideoX-Fun/examples/wan2.1/post_infer.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
import base64
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_diffusion_transformer(diffusion_transformer_path, url='http://127.0.0.1:7860'):
|
| 11 |
+
datas = json.dumps({
|
| 12 |
+
"diffusion_transformer_path": diffusion_transformer_path
|
| 13 |
+
})
|
| 14 |
+
r = requests.post(f'{url}/cogvideox_fun/update_diffusion_transformer', data=datas, timeout=1500)
|
| 15 |
+
data = r.content.decode('utf-8')
|
| 16 |
+
return data
|
| 17 |
+
|
| 18 |
+
def post_update_edition(edition, url='http://0.0.0.0:7860'):
|
| 19 |
+
datas = json.dumps({
|
| 20 |
+
"edition": edition
|
| 21 |
+
})
|
| 22 |
+
r = requests.post(f'{url}/cogvideox_fun/update_edition', data=datas, timeout=1500)
|
| 23 |
+
data = r.content.decode('utf-8')
|
| 24 |
+
return data
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def post_infer(
|
| 28 |
+
generation_method,
|
| 29 |
+
length_slider,
|
| 30 |
+
url='http://127.0.0.1:7860',
|
| 31 |
+
POST_TOKEN="",
|
| 32 |
+
timeout=5000,
|
| 33 |
+
base_model_path="none",
|
| 34 |
+
lora_model_path="none",
|
| 35 |
+
lora_alpha_slider=0.55,
|
| 36 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 37 |
+
negative_prompt_textbox="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion.",
|
| 38 |
+
sampler_dropdown="Flow",
|
| 39 |
+
sample_step_slider=50,
|
| 40 |
+
width_slider=672,
|
| 41 |
+
height_slider=384,
|
| 42 |
+
cfg_scale_slider=6,
|
| 43 |
+
seed_textbox=43
|
| 44 |
+
):
|
| 45 |
+
# Prepare the data payload
|
| 46 |
+
datas = json.dumps({
|
| 47 |
+
"base_model_path": base_model_path,
|
| 48 |
+
"lora_model_path": lora_model_path,
|
| 49 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 50 |
+
"prompt_textbox": prompt_textbox,
|
| 51 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 52 |
+
"sampler_dropdown": sampler_dropdown,
|
| 53 |
+
"sample_step_slider": sample_step_slider,
|
| 54 |
+
"width_slider": width_slider,
|
| 55 |
+
"height_slider": height_slider,
|
| 56 |
+
"generation_method": generation_method,
|
| 57 |
+
"length_slider": length_slider,
|
| 58 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 59 |
+
"seed_textbox": seed_textbox,
|
| 60 |
+
})
|
| 61 |
+
|
| 62 |
+
# Initialize session and set headers
|
| 63 |
+
session = requests.session()
|
| 64 |
+
if url[-1] == "/":
|
| 65 |
+
url = url[:-1]
|
| 66 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 67 |
+
|
| 68 |
+
# Send POST request
|
| 69 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 70 |
+
|
| 71 |
+
data = post_r.content.decode('utf-8')
|
| 72 |
+
return data
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
# initiate time
|
| 76 |
+
time_start = time.time()
|
| 77 |
+
|
| 78 |
+
# The Url you want to post
|
| 79 |
+
POST_URL = 'http://0.0.0.0:7860'
|
| 80 |
+
# Used in EAS. If you don't need Authorization, please set it to empty string.
|
| 81 |
+
TOKEN = ''
|
| 82 |
+
|
| 83 |
+
# -------------------------- #
|
| 84 |
+
# Step 1: update edition
|
| 85 |
+
# -------------------------- #
|
| 86 |
+
# diffusion_transformer_path = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 87 |
+
# outputs = post_diffusion_transformer(diffusion_transformer_path)
|
| 88 |
+
# print('Output update edition: ', outputs)
|
| 89 |
+
|
| 90 |
+
# -------------------------- #
|
| 91 |
+
# Step 2: infer
|
| 92 |
+
# -------------------------- #
|
| 93 |
+
# "Video Generation" and "Image Generation"
|
| 94 |
+
generation_method = "Video Generation"
|
| 95 |
+
# Video length
|
| 96 |
+
length_slider = 49
|
| 97 |
+
# Used in Lora models
|
| 98 |
+
lora_model_path = "none"
|
| 99 |
+
lora_alpha_slider = 0.55
|
| 100 |
+
# Prompts
|
| 101 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 102 |
+
negative_prompt_textbox = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 103 |
+
# Sampler name
|
| 104 |
+
sampler_dropdown = "Flow_Unipc"
|
| 105 |
+
# Sampler steps
|
| 106 |
+
sample_step_slider = 50
|
| 107 |
+
# height and width
|
| 108 |
+
width_slider = 832
|
| 109 |
+
height_slider = 480
|
| 110 |
+
# cfg scale
|
| 111 |
+
cfg_scale_slider = 6
|
| 112 |
+
seed_textbox = 43
|
| 113 |
+
|
| 114 |
+
outputs = post_infer(
|
| 115 |
+
generation_method,
|
| 116 |
+
length_slider,
|
| 117 |
+
lora_model_path=lora_model_path,
|
| 118 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 119 |
+
prompt_textbox=prompt_textbox,
|
| 120 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 121 |
+
sampler_dropdown=sampler_dropdown,
|
| 122 |
+
sample_step_slider=sample_step_slider,
|
| 123 |
+
width_slider=width_slider,
|
| 124 |
+
height_slider=height_slider,
|
| 125 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 126 |
+
seed_textbox=seed_textbox,
|
| 127 |
+
url=POST_URL,
|
| 128 |
+
POST_TOKEN=TOKEN
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Get decoded data
|
| 132 |
+
outputs = json.loads(outputs)
|
| 133 |
+
base64_encoding = outputs["base64_encoding"]
|
| 134 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 135 |
+
|
| 136 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 137 |
+
if is_image or length_slider == 1:
|
| 138 |
+
file_path = "1.png"
|
| 139 |
+
else:
|
| 140 |
+
file_path = "1.mp4"
|
| 141 |
+
with open(file_path, "wb") as file:
|
| 142 |
+
file.write(decoded_data)
|
| 143 |
+
|
| 144 |
+
# End of record time
|
| 145 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 146 |
+
time_end = time.time()
|
| 147 |
+
time_sum = (time_end - time_start)
|
| 148 |
+
print('# --------------------------------------------------------- #')
|
| 149 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 150 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1/post_infer_queue.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def post_infer(
|
| 9 |
+
generation_method,
|
| 10 |
+
length_slider,
|
| 11 |
+
url='http://127.0.0.1:7860',
|
| 12 |
+
POST_TOKEN="",
|
| 13 |
+
timeout=5,
|
| 14 |
+
base_model_path="none",
|
| 15 |
+
lora_model_path="none",
|
| 16 |
+
lora_alpha_slider=0.55,
|
| 17 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 18 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 19 |
+
sampler_dropdown="Flow",
|
| 20 |
+
sample_step_slider=50,
|
| 21 |
+
width_slider=672,
|
| 22 |
+
height_slider=384,
|
| 23 |
+
cfg_scale_slider=6,
|
| 24 |
+
seed_textbox=43,
|
| 25 |
+
enable_teacache = None,
|
| 26 |
+
teacache_threshold = None,
|
| 27 |
+
num_skip_start_steps = None,
|
| 28 |
+
teacache_offload = None,
|
| 29 |
+
cfg_skip_ratio = None,
|
| 30 |
+
enable_riflex = None,
|
| 31 |
+
riflex_k = None,
|
| 32 |
+
):
|
| 33 |
+
# Prepare the data payload
|
| 34 |
+
datas = json.dumps({
|
| 35 |
+
"base_model_path": base_model_path,
|
| 36 |
+
"lora_model_path": lora_model_path,
|
| 37 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 38 |
+
"prompt_textbox": prompt_textbox,
|
| 39 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 40 |
+
"sampler_dropdown": sampler_dropdown,
|
| 41 |
+
"sample_step_slider": sample_step_slider,
|
| 42 |
+
"width_slider": width_slider,
|
| 43 |
+
"height_slider": height_slider,
|
| 44 |
+
"generation_method": generation_method,
|
| 45 |
+
"length_slider": length_slider,
|
| 46 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 47 |
+
"seed_textbox": seed_textbox,
|
| 48 |
+
|
| 49 |
+
"enable_teacache": enable_teacache,
|
| 50 |
+
"teacache_threshold": teacache_threshold,
|
| 51 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 52 |
+
"teacache_offload": teacache_offload,
|
| 53 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 54 |
+
"enable_riflex": enable_riflex,
|
| 55 |
+
"riflex_k": riflex_k,
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
# Initialize session and set headers
|
| 59 |
+
session = requests.session()
|
| 60 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 61 |
+
|
| 62 |
+
# Send POST request
|
| 63 |
+
if url[-1] == "/":
|
| 64 |
+
url = url[:-1]
|
| 65 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 66 |
+
|
| 67 |
+
# Extract request ID from POST response headers
|
| 68 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 69 |
+
|
| 70 |
+
# Prepare query parameters for GET request
|
| 71 |
+
query = {
|
| 72 |
+
'_index_': '0',
|
| 73 |
+
'_length_': '1',
|
| 74 |
+
'_timeout_': str(timeout),
|
| 75 |
+
'_raw_': 'false',
|
| 76 |
+
'_auto_delete_': 'true',
|
| 77 |
+
}
|
| 78 |
+
if request_id:
|
| 79 |
+
query['requestId'] = request_id
|
| 80 |
+
|
| 81 |
+
query_str = urllib.parse.urlencode(query)
|
| 82 |
+
|
| 83 |
+
# Polling GET request until status code is not 204
|
| 84 |
+
status_code = 204
|
| 85 |
+
while status_code == 204:
|
| 86 |
+
if query_str:
|
| 87 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 88 |
+
else:
|
| 89 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 90 |
+
status_code = get_r.status_code
|
| 91 |
+
# Decode and return the response content
|
| 92 |
+
data = get_r.content.decode('utf-8')
|
| 93 |
+
return data
|
| 94 |
+
|
| 95 |
+
if __name__ == '__main__':
|
| 96 |
+
# initiate time
|
| 97 |
+
time_start = time.time()
|
| 98 |
+
|
| 99 |
+
# EAS队列配置
|
| 100 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 101 |
+
# Use in EAS Queue
|
| 102 |
+
TOKEN = 'xxxxxxxx'
|
| 103 |
+
|
| 104 |
+
# Support TeaCache.
|
| 105 |
+
enable_teacache = True
|
| 106 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 107 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 108 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 109 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 110 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 111 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 112 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 113 |
+
teacache_threshold = 0.10
|
| 114 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 115 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 116 |
+
num_skip_start_steps = 5
|
| 117 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 118 |
+
teacache_offload = False
|
| 119 |
+
|
| 120 |
+
# Skip some cfg steps in inference
|
| 121 |
+
# Recommended to be set between 0.00 and 0.25
|
| 122 |
+
cfg_skip_ratio = 0
|
| 123 |
+
|
| 124 |
+
# Riflex config
|
| 125 |
+
enable_riflex = False
|
| 126 |
+
# Index of intrinsic frequency
|
| 127 |
+
riflex_k = 6
|
| 128 |
+
|
| 129 |
+
# "Video Generation" and "Image Generation"
|
| 130 |
+
generation_method = "Video Generation"
|
| 131 |
+
# Video length
|
| 132 |
+
length_slider = 81
|
| 133 |
+
# Used in Lora models
|
| 134 |
+
lora_model_path = "none"
|
| 135 |
+
lora_alpha_slider = 0.55
|
| 136 |
+
# Prompts
|
| 137 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 138 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 139 |
+
# Sampler name
|
| 140 |
+
sampler_dropdown = "Flow_Unipc"
|
| 141 |
+
# Sampler steps
|
| 142 |
+
sample_step_slider = 50
|
| 143 |
+
# height and width
|
| 144 |
+
width_slider = 832
|
| 145 |
+
height_slider = 480
|
| 146 |
+
# cfg scale
|
| 147 |
+
cfg_scale_slider = 6
|
| 148 |
+
seed_textbox = 43
|
| 149 |
+
|
| 150 |
+
outputs = post_infer(
|
| 151 |
+
generation_method,
|
| 152 |
+
length_slider,
|
| 153 |
+
lora_model_path=lora_model_path,
|
| 154 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 155 |
+
prompt_textbox=prompt_textbox,
|
| 156 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 157 |
+
sampler_dropdown=sampler_dropdown,
|
| 158 |
+
sample_step_slider=sample_step_slider,
|
| 159 |
+
width_slider=width_slider,
|
| 160 |
+
height_slider=height_slider,
|
| 161 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 162 |
+
seed_textbox=seed_textbox,
|
| 163 |
+
enable_teacache = enable_teacache,
|
| 164 |
+
teacache_threshold = teacache_threshold,
|
| 165 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 166 |
+
teacache_offload = teacache_offload,
|
| 167 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 168 |
+
enable_riflex = enable_riflex,
|
| 169 |
+
riflex_k = riflex_k,
|
| 170 |
+
url=EAS_URL,
|
| 171 |
+
POST_TOKEN=TOKEN
|
| 172 |
+
)
|
| 173 |
+
# Get decoded data
|
| 174 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 175 |
+
base64_encoding = outputs["base64_encoding"]
|
| 176 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 177 |
+
|
| 178 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 179 |
+
if is_image or length_slider == 1:
|
| 180 |
+
file_path = "1.png"
|
| 181 |
+
else:
|
| 182 |
+
file_path = "1.mp4"
|
| 183 |
+
with open(file_path, "wb") as file:
|
| 184 |
+
file.write(decoded_data)
|
| 185 |
+
|
| 186 |
+
# End of record time
|
| 187 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 188 |
+
time_end = time.time()
|
| 189 |
+
time_sum = (time_end - time_start)
|
| 190 |
+
print('# --------------------------------------------------------- #')
|
| 191 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 192 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1/post_infer_queue_i2v.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_infer(
|
| 11 |
+
generation_method,
|
| 12 |
+
length_slider,
|
| 13 |
+
url='http://127.0.0.1:7860',
|
| 14 |
+
POST_TOKEN="",
|
| 15 |
+
timeout=5,
|
| 16 |
+
base_model_path="none",
|
| 17 |
+
lora_model_path="none",
|
| 18 |
+
lora_alpha_slider=0.55,
|
| 19 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 20 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 21 |
+
sampler_dropdown="Flow",
|
| 22 |
+
sample_step_slider=50,
|
| 23 |
+
width_slider=672,
|
| 24 |
+
height_slider=384,
|
| 25 |
+
cfg_scale_slider=6,
|
| 26 |
+
seed_textbox=43,
|
| 27 |
+
enable_teacache = None,
|
| 28 |
+
teacache_threshold = None,
|
| 29 |
+
num_skip_start_steps = None,
|
| 30 |
+
teacache_offload = None,
|
| 31 |
+
cfg_skip_ratio = None,
|
| 32 |
+
enable_riflex = None,
|
| 33 |
+
riflex_k = None,
|
| 34 |
+
start_image=None
|
| 35 |
+
):
|
| 36 |
+
if start_image:
|
| 37 |
+
try:
|
| 38 |
+
if not start_image.startswith("http"):
|
| 39 |
+
image = Image.open(start_image).convert("RGB")
|
| 40 |
+
# 将图片转换为 Base64 编码
|
| 41 |
+
buffered = BytesIO()
|
| 42 |
+
image.save(buffered, format="JPEG")
|
| 43 |
+
start_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error processing start_image: {e}")
|
| 46 |
+
raise
|
| 47 |
+
|
| 48 |
+
# Prepare the data payload
|
| 49 |
+
datas = json.dumps({
|
| 50 |
+
"base_model_path": base_model_path,
|
| 51 |
+
"lora_model_path": lora_model_path,
|
| 52 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 53 |
+
"prompt_textbox": prompt_textbox,
|
| 54 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 55 |
+
"sampler_dropdown": sampler_dropdown,
|
| 56 |
+
"sample_step_slider": sample_step_slider,
|
| 57 |
+
"width_slider": width_slider,
|
| 58 |
+
"height_slider": height_slider,
|
| 59 |
+
"generation_method": generation_method,
|
| 60 |
+
"length_slider": length_slider,
|
| 61 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 62 |
+
"seed_textbox": seed_textbox,
|
| 63 |
+
|
| 64 |
+
"enable_teacache": enable_teacache,
|
| 65 |
+
"teacache_threshold": teacache_threshold,
|
| 66 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 67 |
+
"teacache_offload": teacache_offload,
|
| 68 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 69 |
+
"enable_riflex": enable_riflex,
|
| 70 |
+
"riflex_k": riflex_k,
|
| 71 |
+
"start_image": start_image
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# Initialize session and set headers
|
| 75 |
+
session = requests.session()
|
| 76 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 77 |
+
|
| 78 |
+
# Send POST request
|
| 79 |
+
if url[-1] == "/":
|
| 80 |
+
url = url[:-1]
|
| 81 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 82 |
+
|
| 83 |
+
# Extract request ID from POST response headers
|
| 84 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 85 |
+
|
| 86 |
+
# Prepare query parameters for GET request
|
| 87 |
+
query = {
|
| 88 |
+
'_index_': '0',
|
| 89 |
+
'_length_': '1',
|
| 90 |
+
'_timeout_': str(timeout),
|
| 91 |
+
'_raw_': 'false',
|
| 92 |
+
'_auto_delete_': 'true',
|
| 93 |
+
}
|
| 94 |
+
if request_id:
|
| 95 |
+
query['requestId'] = request_id
|
| 96 |
+
|
| 97 |
+
query_str = urllib.parse.urlencode(query)
|
| 98 |
+
|
| 99 |
+
# Polling GET request until status code is not 204
|
| 100 |
+
status_code = 204
|
| 101 |
+
while status_code == 204:
|
| 102 |
+
if query_str:
|
| 103 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 104 |
+
else:
|
| 105 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 106 |
+
status_code = get_r.status_code
|
| 107 |
+
# Decode and return the response content
|
| 108 |
+
data = get_r.content.decode('utf-8')
|
| 109 |
+
return data
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
# initiate time
|
| 113 |
+
time_start = time.time()
|
| 114 |
+
|
| 115 |
+
# EAS队列配置
|
| 116 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 117 |
+
# Use in EAS Queue
|
| 118 |
+
TOKEN = 'xxxxxxxx'
|
| 119 |
+
|
| 120 |
+
# Support TeaCache.
|
| 121 |
+
enable_teacache = True
|
| 122 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 123 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 124 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 125 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 126 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 127 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 128 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 129 |
+
teacache_threshold = 0.10
|
| 130 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 131 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 132 |
+
num_skip_start_steps = 5
|
| 133 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 134 |
+
teacache_offload = False
|
| 135 |
+
|
| 136 |
+
# Skip some cfg steps in inference
|
| 137 |
+
# Recommended to be set between 0.00 and 0.25
|
| 138 |
+
cfg_skip_ratio = 0
|
| 139 |
+
|
| 140 |
+
# Riflex config
|
| 141 |
+
enable_riflex = False
|
| 142 |
+
# Index of intrinsic frequency
|
| 143 |
+
riflex_k = 6
|
| 144 |
+
|
| 145 |
+
# "Video Generation" and "Image Generation"
|
| 146 |
+
generation_method = "Video Generation"
|
| 147 |
+
# Video length
|
| 148 |
+
length_slider = 81
|
| 149 |
+
# Used in Lora models
|
| 150 |
+
lora_model_path = "none"
|
| 151 |
+
lora_alpha_slider = 0.55
|
| 152 |
+
# Prompts
|
| 153 |
+
prompt_textbox = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 154 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 155 |
+
# Sampler name
|
| 156 |
+
sampler_dropdown = "Flow_Unipc"
|
| 157 |
+
# Sampler steps
|
| 158 |
+
sample_step_slider = 50
|
| 159 |
+
# height and width
|
| 160 |
+
width_slider = 832
|
| 161 |
+
height_slider = 480
|
| 162 |
+
# cfg scale
|
| 163 |
+
cfg_scale_slider = 6
|
| 164 |
+
seed_textbox = 43
|
| 165 |
+
|
| 166 |
+
# 起始图片路径
|
| 167 |
+
start_image_path = "asset/1.png" # 替换为实际的图片路径
|
| 168 |
+
|
| 169 |
+
outputs = post_infer(
|
| 170 |
+
generation_method,
|
| 171 |
+
length_slider,
|
| 172 |
+
lora_model_path=lora_model_path,
|
| 173 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 174 |
+
prompt_textbox=prompt_textbox,
|
| 175 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 176 |
+
sampler_dropdown=sampler_dropdown,
|
| 177 |
+
sample_step_slider=sample_step_slider,
|
| 178 |
+
width_slider=width_slider,
|
| 179 |
+
height_slider=height_slider,
|
| 180 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 181 |
+
seed_textbox=seed_textbox,
|
| 182 |
+
enable_teacache = enable_teacache,
|
| 183 |
+
teacache_threshold = teacache_threshold,
|
| 184 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 185 |
+
teacache_offload = teacache_offload,
|
| 186 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 187 |
+
enable_riflex = enable_riflex,
|
| 188 |
+
riflex_k = riflex_k,
|
| 189 |
+
url=EAS_URL,
|
| 190 |
+
POST_TOKEN=TOKEN,
|
| 191 |
+
start_image=start_image_path # 传递起始图片路径
|
| 192 |
+
)
|
| 193 |
+
# Get decoded data
|
| 194 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 195 |
+
base64_encoding = outputs["base64_encoding"]
|
| 196 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 197 |
+
|
| 198 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 199 |
+
if is_image or length_slider == 1:
|
| 200 |
+
file_path = "1.png"
|
| 201 |
+
else:
|
| 202 |
+
file_path = "1.mp4"
|
| 203 |
+
with open(file_path, "wb") as file:
|
| 204 |
+
file.write(decoded_data)
|
| 205 |
+
|
| 206 |
+
# End of record time
|
| 207 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 208 |
+
time_end = time.time()
|
| 209 |
+
time_sum = (time_end - time_start)
|
| 210 |
+
print('# --------------------------------------------------------- #')
|
| 211 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 212 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1/pred_ori.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import argparse
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 9 |
+
from omegaconf import OmegaConf
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
current_file_path = os.path.abspath(__file__)
|
| 13 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 14 |
+
for project_root in project_roots:
|
| 15 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 16 |
+
|
| 17 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 18 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 19 |
+
WanTransformer3DModel)
|
| 20 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 21 |
+
from videox_fun.pipeline import WanPipeline
|
| 22 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 23 |
+
convert_weight_dtype_wrapper)
|
| 24 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 25 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 26 |
+
save_videos_grid)
|
| 27 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 28 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 29 |
+
|
| 30 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 31 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 32 |
+
#
|
| 33 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 34 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 39 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 40 |
+
#
|
| 41 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 42 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 43 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 44 |
+
# Multi GPUs config
|
| 45 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 46 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 47 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 48 |
+
ulysses_degree = 1
|
| 49 |
+
ring_degree = 1
|
| 50 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 51 |
+
fsdp_dit = False
|
| 52 |
+
fsdp_text_encoder = True
|
| 53 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 54 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 55 |
+
compile_dit = False
|
| 56 |
+
|
| 57 |
+
# TeaCache config
|
| 58 |
+
enable_teacache = True
|
| 59 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 60 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 61 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 62 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 63 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 64 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 65 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 66 |
+
teacache_threshold = 0.10
|
| 67 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 68 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 69 |
+
num_skip_start_steps = 5
|
| 70 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 71 |
+
teacache_offload = False
|
| 72 |
+
|
| 73 |
+
# Skip some cfg steps in inference
|
| 74 |
+
# Recommended to be set between 0.00 and 0.25
|
| 75 |
+
cfg_skip_ratio = 0
|
| 76 |
+
|
| 77 |
+
# Riflex config
|
| 78 |
+
enable_riflex = False
|
| 79 |
+
# Index of intrinsic frequency
|
| 80 |
+
riflex_k = 6
|
| 81 |
+
|
| 82 |
+
# Config and model path
|
| 83 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 84 |
+
# model path
|
| 85 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 86 |
+
|
| 87 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 88 |
+
sampler_name = "Flow"
|
| 89 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 90 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 91 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 92 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 93 |
+
shift = 3
|
| 94 |
+
|
| 95 |
+
# Load pretrained model if need
|
| 96 |
+
transformer_path = None
|
| 97 |
+
vae_path = None
|
| 98 |
+
lora_path = None
|
| 99 |
+
|
| 100 |
+
# Other params
|
| 101 |
+
sample_size = [512, 288]
|
| 102 |
+
video_length = 49
|
| 103 |
+
fps = 12
|
| 104 |
+
|
| 105 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 106 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 107 |
+
weight_dtype = torch.bfloat16
|
| 108 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 109 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 110 |
+
guidance_scale = 6.0
|
| 111 |
+
seed = 43
|
| 112 |
+
num_inference_steps = 50
|
| 113 |
+
lora_weight = 0.55
|
| 114 |
+
save_path = "samples/wan-videos-t2v"
|
| 115 |
+
|
| 116 |
+
def parse_args():
|
| 117 |
+
parser = argparse.ArgumentParser()
|
| 118 |
+
parser.add_argument("--prompt", type=str, default=None, help="Single prompt text.")
|
| 119 |
+
parser.add_argument("--prompt_txt", type=str, default=None, help="A txt file with one prompt per line.")
|
| 120 |
+
parser.add_argument("--seed", type=int, default=seed, help="Random seed.")
|
| 121 |
+
parser.add_argument("--num_inference_steps", type=int, default=num_inference_steps, help="Inference steps.")
|
| 122 |
+
parser.add_argument("--save_path", type=str, default=save_path, help="Output directory.")
|
| 123 |
+
parser.add_argument("--transformer_path", type=str, default=transformer_path, help="Transformer checkpoint path.")
|
| 124 |
+
return parser.parse_args()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def load_prompts(prompt_txt_path, default_prompt):
|
| 128 |
+
if not prompt_txt_path:
|
| 129 |
+
return [default_prompt]
|
| 130 |
+
prompts = []
|
| 131 |
+
with open(prompt_txt_path, "r", encoding="utf-8") as f:
|
| 132 |
+
for line in f:
|
| 133 |
+
p = line.strip()
|
| 134 |
+
if not p:
|
| 135 |
+
continue
|
| 136 |
+
prompts.append(p)
|
| 137 |
+
if len(prompts) == 0:
|
| 138 |
+
raise ValueError(f"No valid prompts found in {prompt_txt_path}")
|
| 139 |
+
return prompts
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def build_ckpt_subdir_name(transformer_ckpt_path):
|
| 143 |
+
if not transformer_ckpt_path:
|
| 144 |
+
return None
|
| 145 |
+
norm = os.path.normpath(transformer_ckpt_path)
|
| 146 |
+
m = re.search(r"/output_([^/]+)/checkpoint-([^/]+)(?:/|$)", norm)
|
| 147 |
+
if m:
|
| 148 |
+
return f"{m.group(1)}-{m.group(2)}"
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
args = parse_args()
|
| 153 |
+
if args.prompt is not None:
|
| 154 |
+
prompt = args.prompt
|
| 155 |
+
seed = args.seed
|
| 156 |
+
num_inference_steps = args.num_inference_steps
|
| 157 |
+
save_path = args.save_path
|
| 158 |
+
transformer_path = args.transformer_path
|
| 159 |
+
save_subdir = build_ckpt_subdir_name(transformer_path)
|
| 160 |
+
if save_subdir is not None:
|
| 161 |
+
save_path = os.path.join(save_path, save_subdir)
|
| 162 |
+
prompts = load_prompts(args.prompt_txt, prompt)
|
| 163 |
+
|
| 164 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 165 |
+
config = OmegaConf.load(config_path)
|
| 166 |
+
|
| 167 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 168 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 169 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 170 |
+
low_cpu_mem_usage=True,
|
| 171 |
+
torch_dtype=weight_dtype,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if transformer_path is not None:
|
| 175 |
+
print(f"From checkpoint: {transformer_path}")
|
| 176 |
+
if transformer_path.endswith("safetensors"):
|
| 177 |
+
from safetensors.torch import load_file, safe_open
|
| 178 |
+
state_dict = load_file(transformer_path)
|
| 179 |
+
else:
|
| 180 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 181 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 182 |
+
|
| 183 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 184 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 185 |
+
|
| 186 |
+
# Get Vae
|
| 187 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 188 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 189 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 190 |
+
).to(weight_dtype)
|
| 191 |
+
|
| 192 |
+
if vae_path is not None:
|
| 193 |
+
print(f"From checkpoint: {vae_path}")
|
| 194 |
+
if vae_path.endswith("safetensors"):
|
| 195 |
+
from safetensors.torch import load_file, safe_open
|
| 196 |
+
state_dict = load_file(vae_path)
|
| 197 |
+
else:
|
| 198 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 199 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 200 |
+
|
| 201 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 202 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 203 |
+
|
| 204 |
+
# Get Tokenizer
|
| 205 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 206 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Get Text encoder
|
| 210 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 211 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 212 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 213 |
+
low_cpu_mem_usage=True,
|
| 214 |
+
torch_dtype=weight_dtype,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Get Scheduler
|
| 218 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 219 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 220 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 221 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 222 |
+
}[sampler_name]
|
| 223 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 224 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 225 |
+
scheduler = Chosen_Scheduler(
|
| 226 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Get Pipeline
|
| 230 |
+
pipeline = WanPipeline(
|
| 231 |
+
transformer=transformer,
|
| 232 |
+
vae=vae,
|
| 233 |
+
tokenizer=tokenizer,
|
| 234 |
+
text_encoder=text_encoder,
|
| 235 |
+
scheduler=scheduler,
|
| 236 |
+
)
|
| 237 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 238 |
+
from functools import partial
|
| 239 |
+
transformer.enable_multi_gpus_inference()
|
| 240 |
+
if fsdp_dit:
|
| 241 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 242 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 243 |
+
print("Add FSDP DIT")
|
| 244 |
+
if fsdp_text_encoder:
|
| 245 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 246 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 247 |
+
print("Add FSDP TEXT ENCODER")
|
| 248 |
+
|
| 249 |
+
if compile_dit:
|
| 250 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 251 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 252 |
+
print("Add Compile")
|
| 253 |
+
|
| 254 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 255 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 256 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 257 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 258 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 259 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 260 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 261 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 262 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 263 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 264 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 265 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 266 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 267 |
+
pipeline.to(device=device)
|
| 268 |
+
else:
|
| 269 |
+
pipeline.to(device=device)
|
| 270 |
+
|
| 271 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 272 |
+
if coefficients is not None:
|
| 273 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 274 |
+
pipeline.transformer.enable_teacache(
|
| 275 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if cfg_skip_ratio is not None:
|
| 279 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 280 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 281 |
+
|
| 282 |
+
if lora_path is not None:
|
| 283 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
| 284 |
+
|
| 285 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 286 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 287 |
+
|
| 288 |
+
if enable_riflex:
|
| 289 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 290 |
+
|
| 291 |
+
def save_results(sample):
|
| 292 |
+
if not os.path.exists(save_path):
|
| 293 |
+
os.makedirs(save_path, exist_ok=True)
|
| 294 |
+
|
| 295 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 296 |
+
prefix = str(index).zfill(8)
|
| 297 |
+
if video_length == 1:
|
| 298 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 299 |
+
|
| 300 |
+
image = sample[0, :, 0]
|
| 301 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 302 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 303 |
+
image = Image.fromarray(image)
|
| 304 |
+
image.save(video_path)
|
| 305 |
+
else:
|
| 306 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 307 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 308 |
+
|
| 309 |
+
for i, one_prompt in enumerate(prompts):
|
| 310 |
+
local_generator = torch.Generator(device=device).manual_seed(seed + i)
|
| 311 |
+
with torch.no_grad():
|
| 312 |
+
sample = pipeline(
|
| 313 |
+
one_prompt,
|
| 314 |
+
num_frames = video_length,
|
| 315 |
+
negative_prompt = negative_prompt,
|
| 316 |
+
height = sample_size[0],
|
| 317 |
+
width = sample_size[1],
|
| 318 |
+
generator = local_generator,
|
| 319 |
+
guidance_scale = guidance_scale,
|
| 320 |
+
num_inference_steps = num_inference_steps,
|
| 321 |
+
shift = shift,
|
| 322 |
+
).videos
|
| 323 |
+
|
| 324 |
+
if ulysses_degree * ring_degree > 1:
|
| 325 |
+
import torch.distributed as dist
|
| 326 |
+
if dist.get_rank() == 0:
|
| 327 |
+
save_results(sample)
|
| 328 |
+
else:
|
| 329 |
+
save_results(sample)
|
| 330 |
+
|
| 331 |
+
if lora_path is not None:
|
| 332 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
VideoX-Fun/examples/wan2.1/predict_i2v.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, AutoTokenizer, CLIPModel,
|
| 18 |
+
WanT5EncoderModel, WanTransformer3DModel)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanI2VPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 30 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 31 |
+
#
|
| 32 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 33 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 34 |
+
#
|
| 35 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 36 |
+
#
|
| 37 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 38 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 41 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 42 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 43 |
+
# Multi GPUs config
|
| 44 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 45 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 46 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 47 |
+
ulysses_degree = 1
|
| 48 |
+
ring_degree = 1
|
| 49 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 50 |
+
fsdp_dit = False
|
| 51 |
+
fsdp_text_encoder = True
|
| 52 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 53 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 54 |
+
compile_dit = False
|
| 55 |
+
|
| 56 |
+
# Support TeaCache.
|
| 57 |
+
enable_teacache = True
|
| 58 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 59 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 60 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 61 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 62 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 63 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 64 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 65 |
+
teacache_threshold = 0.10
|
| 66 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 67 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 68 |
+
num_skip_start_steps = 5
|
| 69 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 70 |
+
teacache_offload = False
|
| 71 |
+
|
| 72 |
+
# Skip some cfg steps in inference
|
| 73 |
+
# Recommended to be set between 0.00 and 0.25
|
| 74 |
+
cfg_skip_ratio = 0
|
| 75 |
+
|
| 76 |
+
# Riflex config
|
| 77 |
+
enable_riflex = False
|
| 78 |
+
# Index of intrinsic frequency
|
| 79 |
+
riflex_k = 6
|
| 80 |
+
|
| 81 |
+
# Config and model path
|
| 82 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 83 |
+
# model path
|
| 84 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-I2V-14B-480P"
|
| 85 |
+
|
| 86 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 87 |
+
sampler_name = "Flow_Unipc"
|
| 88 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 89 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 90 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 91 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 92 |
+
shift = 3
|
| 93 |
+
|
| 94 |
+
# Load pretrained model if need
|
| 95 |
+
transformer_path = None
|
| 96 |
+
vae_path = None
|
| 97 |
+
lora_path = None
|
| 98 |
+
|
| 99 |
+
# Other params
|
| 100 |
+
sample_size = [480, 832]
|
| 101 |
+
video_length = 81
|
| 102 |
+
fps = 16
|
| 103 |
+
|
| 104 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 105 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 106 |
+
weight_dtype = torch.bfloat16
|
| 107 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 108 |
+
validation_image_start = "asset/1.png"
|
| 109 |
+
|
| 110 |
+
# prompts
|
| 111 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 112 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 113 |
+
guidance_scale = 6.0
|
| 114 |
+
seed = 43
|
| 115 |
+
num_inference_steps = 50
|
| 116 |
+
lora_weight = 0.55
|
| 117 |
+
save_path = "samples/wan-videos-i2v"
|
| 118 |
+
|
| 119 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 120 |
+
config = OmegaConf.load(config_path)
|
| 121 |
+
|
| 122 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 123 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 124 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 125 |
+
low_cpu_mem_usage=True,
|
| 126 |
+
torch_dtype=weight_dtype,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if transformer_path is not None:
|
| 130 |
+
print(f"From checkpoint: {transformer_path}")
|
| 131 |
+
if transformer_path.endswith("safetensors"):
|
| 132 |
+
from safetensors.torch import load_file, safe_open
|
| 133 |
+
state_dict = load_file(transformer_path)
|
| 134 |
+
else:
|
| 135 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 136 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 137 |
+
|
| 138 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 139 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 140 |
+
|
| 141 |
+
# Get Vae
|
| 142 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 143 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 144 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 145 |
+
).to(weight_dtype)
|
| 146 |
+
|
| 147 |
+
if vae_path is not None:
|
| 148 |
+
print(f"From checkpoint: {vae_path}")
|
| 149 |
+
if vae_path.endswith("safetensors"):
|
| 150 |
+
from safetensors.torch import load_file, safe_open
|
| 151 |
+
state_dict = load_file(vae_path)
|
| 152 |
+
else:
|
| 153 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 154 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 155 |
+
|
| 156 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 157 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 158 |
+
|
| 159 |
+
# Get Tokenizer
|
| 160 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 161 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Get Text encoder
|
| 165 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 166 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 167 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 168 |
+
low_cpu_mem_usage=True,
|
| 169 |
+
torch_dtype=weight_dtype,
|
| 170 |
+
)
|
| 171 |
+
text_encoder = text_encoder.eval()
|
| 172 |
+
|
| 173 |
+
# Get Clip Image Encoder
|
| 174 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 175 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 176 |
+
).to(weight_dtype)
|
| 177 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 178 |
+
|
| 179 |
+
# Get Scheduler
|
| 180 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 181 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 182 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 183 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 184 |
+
}[sampler_name]
|
| 185 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 186 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 187 |
+
scheduler = Chosen_Scheduler(
|
| 188 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Get Pipeline
|
| 192 |
+
pipeline = WanI2VPipeline(
|
| 193 |
+
transformer=transformer,
|
| 194 |
+
vae=vae,
|
| 195 |
+
tokenizer=tokenizer,
|
| 196 |
+
text_encoder=text_encoder,
|
| 197 |
+
scheduler=scheduler,
|
| 198 |
+
clip_image_encoder=clip_image_encoder
|
| 199 |
+
)
|
| 200 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 201 |
+
from functools import partial
|
| 202 |
+
transformer.enable_multi_gpus_inference()
|
| 203 |
+
if fsdp_dit:
|
| 204 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 205 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 206 |
+
print("Add FSDP DIT")
|
| 207 |
+
if fsdp_text_encoder:
|
| 208 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 209 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 210 |
+
print("Add FSDP TEXT ENCODER")
|
| 211 |
+
|
| 212 |
+
if compile_dit:
|
| 213 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 214 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 215 |
+
print("Add Compile")
|
| 216 |
+
|
| 217 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 218 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 219 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 220 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 221 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 222 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 223 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 224 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 225 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 226 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 227 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 228 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 229 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 230 |
+
pipeline.to(device=device)
|
| 231 |
+
else:
|
| 232 |
+
pipeline.to(device=device)
|
| 233 |
+
|
| 234 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 235 |
+
if coefficients is not None:
|
| 236 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 237 |
+
pipeline.transformer.enable_teacache(
|
| 238 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if cfg_skip_ratio is not None:
|
| 242 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 243 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 244 |
+
|
| 245 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 246 |
+
|
| 247 |
+
if lora_path is not None:
|
| 248 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 249 |
+
|
| 250 |
+
with torch.no_grad():
|
| 251 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 252 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 253 |
+
|
| 254 |
+
if enable_riflex:
|
| 255 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 256 |
+
|
| 257 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, None, video_length=video_length, sample_size=sample_size)
|
| 258 |
+
|
| 259 |
+
sample = pipeline(
|
| 260 |
+
prompt,
|
| 261 |
+
num_frames = video_length,
|
| 262 |
+
negative_prompt = negative_prompt,
|
| 263 |
+
height = sample_size[0],
|
| 264 |
+
width = sample_size[1],
|
| 265 |
+
generator = generator,
|
| 266 |
+
guidance_scale = guidance_scale,
|
| 267 |
+
num_inference_steps = num_inference_steps,
|
| 268 |
+
|
| 269 |
+
video = input_video,
|
| 270 |
+
mask_video = input_video_mask,
|
| 271 |
+
clip_image = clip_image,
|
| 272 |
+
shift = shift,
|
| 273 |
+
).videos
|
| 274 |
+
|
| 275 |
+
if lora_path is not None:
|
| 276 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 277 |
+
|
| 278 |
+
def save_results():
|
| 279 |
+
if not os.path.exists(save_path):
|
| 280 |
+
os.makedirs(save_path, exist_ok=True)
|
| 281 |
+
|
| 282 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 283 |
+
prefix = str(index).zfill(8)
|
| 284 |
+
if video_length == 1:
|
| 285 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 286 |
+
|
| 287 |
+
image = sample[0, :, 0]
|
| 288 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 289 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 290 |
+
image = Image.fromarray(image)
|
| 291 |
+
image.save(video_path)
|
| 292 |
+
else:
|
| 293 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 294 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 295 |
+
|
| 296 |
+
if ulysses_degree * ring_degree > 1:
|
| 297 |
+
import torch.distributed as dist
|
| 298 |
+
if dist.get_rank() == 0:
|
| 299 |
+
save_results()
|
| 300 |
+
else:
|
| 301 |
+
save_results()
|
VideoX-Fun/examples/wan2.1/predict_t2v.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
WanTransformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import WanPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
|
| 42 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 43 |
+
# Multi GPUs config
|
| 44 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 45 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 46 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 47 |
+
ulysses_degree = 1
|
| 48 |
+
ring_degree = 1
|
| 49 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 50 |
+
fsdp_dit = False
|
| 51 |
+
fsdp_text_encoder = True
|
| 52 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 53 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 54 |
+
compile_dit = False
|
| 55 |
+
|
| 56 |
+
# TeaCache config
|
| 57 |
+
enable_teacache = True
|
| 58 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 59 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 60 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 61 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 62 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 63 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 64 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 65 |
+
teacache_threshold = 0.10
|
| 66 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 67 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 68 |
+
num_skip_start_steps = 5
|
| 69 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 70 |
+
teacache_offload = False
|
| 71 |
+
|
| 72 |
+
# Skip some cfg steps in inference
|
| 73 |
+
# Recommended to be set between 0.00 and 0.25
|
| 74 |
+
cfg_skip_ratio = 0
|
| 75 |
+
|
| 76 |
+
# Riflex config
|
| 77 |
+
enable_riflex = False
|
| 78 |
+
# Index of intrinsic frequency
|
| 79 |
+
riflex_k = 6
|
| 80 |
+
|
| 81 |
+
# Config and model path
|
| 82 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 83 |
+
# model path
|
| 84 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 85 |
+
|
| 86 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 87 |
+
sampler_name = "Flow_Unipc"
|
| 88 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 89 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 90 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 91 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 92 |
+
shift = 3
|
| 93 |
+
|
| 94 |
+
# Load pretrained model if need
|
| 95 |
+
transformer_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_full/output_Oct9/checkpoint-3900/transformer/diffusion_pytorch_model.safetensors'
|
| 96 |
+
vae_path = None
|
| 97 |
+
lora_path = None
|
| 98 |
+
|
| 99 |
+
# Other params
|
| 100 |
+
sample_size = [512, 288]
|
| 101 |
+
video_length = 49
|
| 102 |
+
fps = 16
|
| 103 |
+
|
| 104 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 105 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 106 |
+
prompt_list_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt'
|
| 107 |
+
num_generated_videos = 20
|
| 108 |
+
weight_dtype = torch.bfloat16
|
| 109 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 110 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 111 |
+
guidance_scale = 6.0
|
| 112 |
+
seed = 42
|
| 113 |
+
num_inference_steps = 25
|
| 114 |
+
lora_weight = 0.55
|
| 115 |
+
save_path = f"samples/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}"
|
| 116 |
+
|
| 117 |
+
# if lora_path:
|
| 118 |
+
# import pdb
|
| 119 |
+
# # pdb.set_trace()
|
| 120 |
+
# sub_path = lora_path.split('/')[-2]
|
| 121 |
+
# itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 122 |
+
# save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 123 |
+
# else:
|
| 124 |
+
# save_path = f'{save_path}/output_pretrain'
|
| 125 |
+
|
| 126 |
+
save_path = f'{save_path}/output_debug3'
|
| 127 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 128 |
+
config = OmegaConf.load(config_path)
|
| 129 |
+
|
| 130 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 131 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 132 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 133 |
+
low_cpu_mem_usage=True,
|
| 134 |
+
torch_dtype=weight_dtype,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
if transformer_path is not None:
|
| 138 |
+
print(f"From checkpoint: {transformer_path}")
|
| 139 |
+
if transformer_path.endswith("safetensors"):
|
| 140 |
+
from safetensors.torch import load_file, safe_open
|
| 141 |
+
state_dict = load_file(transformer_path)
|
| 142 |
+
else:
|
| 143 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 144 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 145 |
+
|
| 146 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 147 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 148 |
+
|
| 149 |
+
# Get Vae
|
| 150 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 151 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 152 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 153 |
+
).to(weight_dtype)
|
| 154 |
+
|
| 155 |
+
if vae_path is not None:
|
| 156 |
+
print(f"From checkpoint: {vae_path}")
|
| 157 |
+
if vae_path.endswith("safetensors"):
|
| 158 |
+
from safetensors.torch import load_file, safe_open
|
| 159 |
+
state_dict = load_file(vae_path)
|
| 160 |
+
else:
|
| 161 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 162 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 163 |
+
|
| 164 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 165 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 166 |
+
|
| 167 |
+
# Get Tokenizer
|
| 168 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 169 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# Get Text encoder
|
| 173 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 174 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 175 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 176 |
+
low_cpu_mem_usage=True,
|
| 177 |
+
torch_dtype=weight_dtype,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Get Scheduler
|
| 181 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 182 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 183 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 184 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 185 |
+
}[sampler_name]
|
| 186 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 187 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 188 |
+
scheduler = Chosen_Scheduler(
|
| 189 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# Get Pipeline
|
| 193 |
+
pipeline = WanPipeline(
|
| 194 |
+
transformer=transformer,
|
| 195 |
+
vae=vae,
|
| 196 |
+
tokenizer=tokenizer,
|
| 197 |
+
text_encoder=text_encoder,
|
| 198 |
+
scheduler=scheduler,
|
| 199 |
+
)
|
| 200 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 201 |
+
from functools import partial
|
| 202 |
+
transformer.enable_multi_gpus_inference()
|
| 203 |
+
if fsdp_dit:
|
| 204 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 205 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 206 |
+
print("Add FSDP DIT")
|
| 207 |
+
if fsdp_text_encoder:
|
| 208 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 209 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 210 |
+
print("Add FSDP TEXT ENCODER")
|
| 211 |
+
|
| 212 |
+
if compile_dit:
|
| 213 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 214 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 215 |
+
print("Add Compile")
|
| 216 |
+
|
| 217 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 218 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 219 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 220 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 221 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 222 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 223 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 224 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 225 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 226 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 227 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 228 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 229 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 230 |
+
pipeline.to(device=device)
|
| 231 |
+
else:
|
| 232 |
+
pipeline.to(device=device)
|
| 233 |
+
|
| 234 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 235 |
+
if coefficients is not None:
|
| 236 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 237 |
+
pipeline.transformer.enable_teacache(
|
| 238 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if cfg_skip_ratio is not None:
|
| 242 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 243 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 244 |
+
|
| 245 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 246 |
+
|
| 247 |
+
prompt_list = []
|
| 248 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 249 |
+
for line in file:
|
| 250 |
+
# 去除行末的换行符
|
| 251 |
+
prompt_list.append(line.strip())
|
| 252 |
+
|
| 253 |
+
if lora_path is not None:
|
| 254 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 255 |
+
|
| 256 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 257 |
+
for prompt in prompt_list[:50]:
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 260 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 261 |
+
|
| 262 |
+
if enable_riflex:
|
| 263 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 264 |
+
|
| 265 |
+
sample = pipeline(
|
| 266 |
+
prompt,
|
| 267 |
+
num_frames = video_length,
|
| 268 |
+
negative_prompt = negative_prompt,
|
| 269 |
+
height = sample_size[0],
|
| 270 |
+
width = sample_size[1],
|
| 271 |
+
generator = generator,
|
| 272 |
+
guidance_scale = guidance_scale,
|
| 273 |
+
num_inference_steps = num_inference_steps,
|
| 274 |
+
shift = shift,
|
| 275 |
+
).videos
|
| 276 |
+
|
| 277 |
+
if lora_path is not None:
|
| 278 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 279 |
+
|
| 280 |
+
def save_results():
|
| 281 |
+
if not os.path.exists(save_path):
|
| 282 |
+
os.makedirs(save_path, exist_ok=True)
|
| 283 |
+
|
| 284 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 285 |
+
prefix = str(index).zfill(8)
|
| 286 |
+
if video_length == 1:
|
| 287 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 288 |
+
|
| 289 |
+
image = sample[0, :, 0]
|
| 290 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 291 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 292 |
+
image = Image.fromarray(image)
|
| 293 |
+
image.save(video_path)
|
| 294 |
+
else:
|
| 295 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 296 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 297 |
+
|
| 298 |
+
if ulysses_degree * ring_degree > 1:
|
| 299 |
+
import torch.distributed as dist
|
| 300 |
+
if dist.get_rank() == 0:
|
| 301 |
+
save_results()
|
| 302 |
+
else:
|
| 303 |
+
save_results()
|
| 304 |
+
|
| 305 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v1.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
WanTransformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import WanPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = True
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 62 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 63 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 64 |
+
teacache_threshold = 0.10
|
| 65 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 66 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 67 |
+
num_skip_start_steps = 5
|
| 68 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 69 |
+
teacache_offload = False
|
| 70 |
+
|
| 71 |
+
# Skip some cfg steps in inference
|
| 72 |
+
# Recommended to be set between 0.00 and 0.25
|
| 73 |
+
cfg_skip_ratio = 0
|
| 74 |
+
|
| 75 |
+
# Riflex config
|
| 76 |
+
enable_riflex = False
|
| 77 |
+
# Index of intrinsic frequency
|
| 78 |
+
riflex_k = 6
|
| 79 |
+
|
| 80 |
+
# Config and model path
|
| 81 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 82 |
+
# model path
|
| 83 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 84 |
+
|
| 85 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 86 |
+
sampler_name = "Flow"
|
| 87 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 88 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 89 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 90 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 91 |
+
shift = 5
|
| 92 |
+
|
| 93 |
+
# Load pretrained model if need
|
| 94 |
+
transformer_path = None
|
| 95 |
+
vae_path = None
|
| 96 |
+
lora_path = None
|
| 97 |
+
|
| 98 |
+
# Other params
|
| 99 |
+
sample_size = [512, 288]
|
| 100 |
+
video_length = 49
|
| 101 |
+
fps = 16
|
| 102 |
+
|
| 103 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 104 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 105 |
+
weight_dtype = torch.bfloat16
|
| 106 |
+
prompt = "A corgi vlogging itself in tropical Maui."
|
| 107 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 108 |
+
#negative_prompt = ""
|
| 109 |
+
guidance_scale = 6.0
|
| 110 |
+
seed = 42
|
| 111 |
+
num_inference_steps = 30
|
| 112 |
+
lora_weight = 0.55
|
| 113 |
+
save_path = "samples/wan-videos-t2v/debug"
|
| 114 |
+
|
| 115 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 116 |
+
config = OmegaConf.load(config_path)
|
| 117 |
+
|
| 118 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 119 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 120 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 121 |
+
low_cpu_mem_usage=True,
|
| 122 |
+
torch_dtype=weight_dtype,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if transformer_path is not None:
|
| 126 |
+
print(f"From checkpoint: {transformer_path}")
|
| 127 |
+
if transformer_path.endswith("safetensors"):
|
| 128 |
+
from safetensors.torch import load_file, safe_open
|
| 129 |
+
state_dict = load_file(transformer_path)
|
| 130 |
+
else:
|
| 131 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 132 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 133 |
+
|
| 134 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 135 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 136 |
+
|
| 137 |
+
# Get Vae
|
| 138 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 139 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 140 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 141 |
+
).to(weight_dtype)
|
| 142 |
+
|
| 143 |
+
if vae_path is not None:
|
| 144 |
+
print(f"From checkpoint: {vae_path}")
|
| 145 |
+
if vae_path.endswith("safetensors"):
|
| 146 |
+
from safetensors.torch import load_file, safe_open
|
| 147 |
+
state_dict = load_file(vae_path)
|
| 148 |
+
else:
|
| 149 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 150 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 151 |
+
|
| 152 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 153 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 154 |
+
|
| 155 |
+
# Get Tokenizer
|
| 156 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 157 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Get Text encoder
|
| 161 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 162 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 163 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 164 |
+
low_cpu_mem_usage=True,
|
| 165 |
+
torch_dtype=weight_dtype,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Get Scheduler
|
| 169 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 170 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 171 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 172 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 173 |
+
}[sampler_name]
|
| 174 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 175 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 176 |
+
scheduler = Chosen_Scheduler(
|
| 177 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Get Pipeline
|
| 181 |
+
pipeline = WanPipeline(
|
| 182 |
+
transformer=transformer,
|
| 183 |
+
vae=vae,
|
| 184 |
+
tokenizer=tokenizer,
|
| 185 |
+
text_encoder=text_encoder,
|
| 186 |
+
scheduler=scheduler,
|
| 187 |
+
)
|
| 188 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 189 |
+
from functools import partial
|
| 190 |
+
transformer.enable_multi_gpus_inference()
|
| 191 |
+
if fsdp_dit:
|
| 192 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 193 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 194 |
+
print("Add FSDP DIT")
|
| 195 |
+
if fsdp_text_encoder:
|
| 196 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 197 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 198 |
+
print("Add FSDP TEXT ENCODER")
|
| 199 |
+
|
| 200 |
+
if compile_dit:
|
| 201 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 202 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 203 |
+
print("Add Compile")
|
| 204 |
+
|
| 205 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 206 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 207 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 208 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 209 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 210 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 211 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 212 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 213 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 214 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 215 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 216 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 217 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 218 |
+
pipeline.to(device=device)
|
| 219 |
+
else:
|
| 220 |
+
pipeline.to(device=device)
|
| 221 |
+
|
| 222 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 223 |
+
if coefficients is not None:
|
| 224 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 225 |
+
pipeline.transformer.enable_teacache(
|
| 226 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
if cfg_skip_ratio is not None:
|
| 230 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 231 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 232 |
+
|
| 233 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 234 |
+
|
| 235 |
+
if lora_path is not None:
|
| 236 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
| 237 |
+
|
| 238 |
+
with torch.no_grad():
|
| 239 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 240 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 241 |
+
|
| 242 |
+
if enable_riflex:
|
| 243 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 244 |
+
|
| 245 |
+
sample = pipeline(
|
| 246 |
+
prompt,
|
| 247 |
+
num_frames = video_length,
|
| 248 |
+
negative_prompt = negative_prompt,
|
| 249 |
+
height = sample_size[0],
|
| 250 |
+
width = sample_size[1],
|
| 251 |
+
generator = generator,
|
| 252 |
+
guidance_scale = guidance_scale,
|
| 253 |
+
num_inference_steps = num_inference_steps,
|
| 254 |
+
shift = shift,
|
| 255 |
+
).videos
|
| 256 |
+
|
| 257 |
+
if lora_path is not None:
|
| 258 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
| 259 |
+
|
| 260 |
+
def save_results():
|
| 261 |
+
if not os.path.exists(save_path):
|
| 262 |
+
os.makedirs(save_path, exist_ok=True)
|
| 263 |
+
|
| 264 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 265 |
+
prefix = str(index).zfill(8)
|
| 266 |
+
if video_length == 1:
|
| 267 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 268 |
+
|
| 269 |
+
image = sample[0, :, 0]
|
| 270 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 271 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 272 |
+
image = Image.fromarray(image)
|
| 273 |
+
image.save(video_path)
|
| 274 |
+
else:
|
| 275 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 276 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 277 |
+
|
| 278 |
+
if ulysses_degree * ring_degree > 1:
|
| 279 |
+
import torch.distributed as dist
|
| 280 |
+
if dist.get_rank() == 0:
|
| 281 |
+
save_results()
|
| 282 |
+
else:
|
| 283 |
+
save_results()
|
VideoX-Fun/examples/wan2.1/predict_t2v_14B_vqref.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
|
| 32 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--prompt_list_path", type=str, default='MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 35 |
+
|
| 36 |
+
parser.add_argument("--save_folder", type=str, default='samples4', help="prompt file for inference")
|
| 37 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--sample_size", type=list, default=[512, 288], help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 41 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 42 |
+
|
| 43 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 44 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 45 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 46 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 50 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 51 |
+
|
| 52 |
+
args = parser.parse_args()
|
| 53 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 54 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 55 |
+
#
|
| 56 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 57 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 58 |
+
#
|
| 59 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 60 |
+
#
|
| 61 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 62 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 63 |
+
#
|
| 64 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 65 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 66 |
+
|
| 67 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 68 |
+
# Multi GPUs config
|
| 69 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 70 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 71 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 72 |
+
ulysses_degree = 1
|
| 73 |
+
ring_degree = 1
|
| 74 |
+
|
| 75 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 76 |
+
fsdp_dit = False
|
| 77 |
+
fsdp_text_encoder = True
|
| 78 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 79 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 80 |
+
compile_dit = False
|
| 81 |
+
|
| 82 |
+
# TeaCache config
|
| 83 |
+
enable_teacache = True
|
| 84 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 85 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 86 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 87 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 88 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 89 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 90 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 91 |
+
teacache_threshold = 0.10
|
| 92 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 93 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 94 |
+
num_skip_start_steps = 5
|
| 95 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 96 |
+
teacache_offload = False
|
| 97 |
+
|
| 98 |
+
# Skip some cfg steps in inference
|
| 99 |
+
# Recommended to be set between 0.00 and 0.25
|
| 100 |
+
cfg_skip_ratio = 0
|
| 101 |
+
|
| 102 |
+
# Riflex config
|
| 103 |
+
enable_riflex = False
|
| 104 |
+
# Index of intrinsic frequency
|
| 105 |
+
riflex_k = 6
|
| 106 |
+
|
| 107 |
+
# Config and model path
|
| 108 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 109 |
+
# model path
|
| 110 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-14B"
|
| 111 |
+
|
| 112 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 113 |
+
sampler_name = args.sampler_name
|
| 114 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 115 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 116 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 117 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 118 |
+
shift = 3
|
| 119 |
+
|
| 120 |
+
# Load pretrained model if need
|
| 121 |
+
transformer_path = args.transformer_path
|
| 122 |
+
vae_path = None
|
| 123 |
+
|
| 124 |
+
lora_path = args.lora_path
|
| 125 |
+
# pdb.set_trace()
|
| 126 |
+
# Other params
|
| 127 |
+
sample_size = [512, 288]
|
| 128 |
+
video_length = 49
|
| 129 |
+
fps = 16
|
| 130 |
+
|
| 131 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 132 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 133 |
+
prompt_list_path = args.prompt_list_path
|
| 134 |
+
|
| 135 |
+
weight_dtype = torch.bfloat16
|
| 136 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 137 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 138 |
+
guidance_scale = 6.0
|
| 139 |
+
seed = 42
|
| 140 |
+
num_inference_steps = args.num_inference_steps
|
| 141 |
+
lora_weight = 1.0
|
| 142 |
+
|
| 143 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}"
|
| 144 |
+
|
| 145 |
+
# if use_h3ae:
|
| 146 |
+
# # pdb.set_trace()
|
| 147 |
+
# save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 148 |
+
# import pdb
|
| 149 |
+
# pdb.set_trace()
|
| 150 |
+
if seed != 42:
|
| 151 |
+
save_path= f"{save_path}-seed{seed}"
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if lora_path:
|
| 155 |
+
import pdb
|
| 156 |
+
# pdb.set_trace()
|
| 157 |
+
sub_path = lora_path.split('/')[-2]
|
| 158 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 159 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 160 |
+
elif transformer_path:
|
| 161 |
+
sub_path = transformer_path.split('/')[-4]
|
| 162 |
+
itr = transformer_path.split('/')[-3].split('-')[-1]
|
| 163 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 164 |
+
# pdb.set_trace()
|
| 165 |
+
else:
|
| 166 |
+
|
| 167 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}/output_pretrain'
|
| 168 |
+
|
| 169 |
+
if args.debug:
|
| 170 |
+
lora_path = None
|
| 171 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 172 |
+
|
| 173 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 174 |
+
config = OmegaConf.load(config_path)
|
| 175 |
+
|
| 176 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 177 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 178 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 179 |
+
low_cpu_mem_usage=True,
|
| 180 |
+
torch_dtype=weight_dtype,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if transformer_path is not None:
|
| 184 |
+
print(f"From checkpoint: {transformer_path}")
|
| 185 |
+
if transformer_path.endswith("safetensors"):
|
| 186 |
+
from safetensors.torch import load_file, safe_open
|
| 187 |
+
state_dict = load_file(transformer_path)
|
| 188 |
+
else:
|
| 189 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 190 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 191 |
+
# pdb.set_trace()
|
| 192 |
+
|
| 193 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 194 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 195 |
+
# pdb.set_trace()
|
| 196 |
+
|
| 197 |
+
# Get Vae
|
| 198 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 199 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 200 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 201 |
+
).to(weight_dtype)
|
| 202 |
+
|
| 203 |
+
if vae_path is not None:
|
| 204 |
+
print(f"From checkpoint: {vae_path}")
|
| 205 |
+
if vae_path.endswith("safetensors"):
|
| 206 |
+
from safetensors.torch import load_file, safe_open
|
| 207 |
+
state_dict = load_file(vae_path)
|
| 208 |
+
else:
|
| 209 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 210 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 211 |
+
|
| 212 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 213 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 214 |
+
|
| 215 |
+
# Get Tokenizer
|
| 216 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 217 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# Get Text encoder
|
| 221 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 222 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 223 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 224 |
+
low_cpu_mem_usage=True,
|
| 225 |
+
torch_dtype=weight_dtype,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Get Scheduler
|
| 229 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 230 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 231 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 232 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 233 |
+
}[sampler_name]
|
| 234 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 235 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 236 |
+
scheduler = Chosen_Scheduler(
|
| 237 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
# Get Pipeline
|
| 241 |
+
pipeline = WanPipeline(
|
| 242 |
+
transformer=transformer,
|
| 243 |
+
vae=vae,
|
| 244 |
+
tokenizer=tokenizer,
|
| 245 |
+
text_encoder=text_encoder,
|
| 246 |
+
scheduler=scheduler,
|
| 247 |
+
)
|
| 248 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 249 |
+
from functools import partial
|
| 250 |
+
transformer.enable_multi_gpus_inference()
|
| 251 |
+
if fsdp_dit:
|
| 252 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 253 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 254 |
+
print("Add FSDP DIT")
|
| 255 |
+
if fsdp_text_encoder:
|
| 256 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 257 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 258 |
+
print("Add FSDP TEXT ENCODER")
|
| 259 |
+
|
| 260 |
+
if compile_dit:
|
| 261 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 262 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 263 |
+
print("Add Compile")
|
| 264 |
+
|
| 265 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 266 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 267 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 268 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 269 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 270 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 271 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 272 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 273 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 274 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 275 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 276 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 277 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 278 |
+
pipeline.to(device=device)
|
| 279 |
+
else:
|
| 280 |
+
pipeline.to(device=device)
|
| 281 |
+
|
| 282 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 283 |
+
if coefficients is not None:
|
| 284 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 285 |
+
pipeline.transformer.enable_teacache(
|
| 286 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if cfg_skip_ratio is not None:
|
| 290 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 291 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 292 |
+
|
| 293 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 294 |
+
|
| 295 |
+
prompt_list = []
|
| 296 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 297 |
+
for line in file:
|
| 298 |
+
# 去除行末的换行符
|
| 299 |
+
prompt_list.append(line.strip())
|
| 300 |
+
|
| 301 |
+
if lora_path is not None:
|
| 302 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 303 |
+
|
| 304 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 305 |
+
|
| 306 |
+
for prompt in prompt_list:
|
| 307 |
+
with torch.no_grad():
|
| 308 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 309 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 310 |
+
|
| 311 |
+
if enable_riflex:
|
| 312 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 313 |
+
|
| 314 |
+
sample = pipeline(
|
| 315 |
+
prompt,
|
| 316 |
+
num_frames = video_length,
|
| 317 |
+
negative_prompt = negative_prompt,
|
| 318 |
+
height = sample_size[0],
|
| 319 |
+
width = sample_size[1],
|
| 320 |
+
generator = generator,
|
| 321 |
+
guidance_scale = guidance_scale,
|
| 322 |
+
num_inference_steps = num_inference_steps,
|
| 323 |
+
shift = shift,
|
| 324 |
+
).videos
|
| 325 |
+
|
| 326 |
+
# if lora_path is not None:
|
| 327 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 328 |
+
|
| 329 |
+
def save_results():
|
| 330 |
+
if not os.path.exists(save_path):
|
| 331 |
+
os.makedirs(save_path, exist_ok=True)
|
| 332 |
+
|
| 333 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 334 |
+
prefix = str(index).zfill(8)
|
| 335 |
+
if video_length == 1:
|
| 336 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 337 |
+
|
| 338 |
+
image = sample[0, :, 0]
|
| 339 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 340 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 341 |
+
image = Image.fromarray(image)
|
| 342 |
+
image.save(video_path)
|
| 343 |
+
else:
|
| 344 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 345 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 346 |
+
|
| 347 |
+
if ulysses_degree * ring_degree > 1:
|
| 348 |
+
import torch.distributed as dist
|
| 349 |
+
if dist.get_rank() == 0:
|
| 350 |
+
save_results()
|
| 351 |
+
else:
|
| 352 |
+
save_results()
|
| 353 |
+
|
| 354 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_fg.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
from peft import LoraConfig, get_peft_model, set_peft_model_state_dict, PeftModel
|
| 29 |
+
|
| 30 |
+
import argparse
|
| 31 |
+
parser = argparse.ArgumentParser()
|
| 32 |
+
|
| 33 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 35 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 36 |
+
|
| 37 |
+
parser.add_argument("--save_folder", type=str, default=None, help="prompt file for inference")
|
| 38 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 39 |
+
|
| 40 |
+
parser.add_argument("--sample_height", type=list, default=512, help="prompt file for inference")
|
| 41 |
+
parser.add_argument("--sample_width", type=list, default=288, help="prompt file for inference")
|
| 42 |
+
|
| 43 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 44 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 45 |
+
# parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 46 |
+
|
| 47 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 48 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 49 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 50 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 54 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 55 |
+
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 58 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 59 |
+
#
|
| 60 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 61 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 62 |
+
#
|
| 63 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 64 |
+
#
|
| 65 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 66 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 67 |
+
#
|
| 68 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 69 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 70 |
+
|
| 71 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 72 |
+
# Multi GPUs config
|
| 73 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 74 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 75 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 76 |
+
ulysses_degree = 1
|
| 77 |
+
ring_degree = 1
|
| 78 |
+
|
| 79 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 80 |
+
fsdp_dit = False
|
| 81 |
+
fsdp_text_encoder = True
|
| 82 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 83 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 84 |
+
compile_dit = False
|
| 85 |
+
|
| 86 |
+
# TeaCache config
|
| 87 |
+
enable_teacache = True
|
| 88 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 89 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 90 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 91 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 92 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 93 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 94 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 95 |
+
teacache_threshold = 0.10
|
| 96 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 97 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 98 |
+
num_skip_start_steps = 5
|
| 99 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 100 |
+
teacache_offload = False
|
| 101 |
+
|
| 102 |
+
# Skip some cfg steps in inference
|
| 103 |
+
# Recommended to be set between 0.00 and 0.25
|
| 104 |
+
cfg_skip_ratio = 0
|
| 105 |
+
|
| 106 |
+
# Riflex config
|
| 107 |
+
enable_riflex = False
|
| 108 |
+
# Index of intrinsic frequency
|
| 109 |
+
riflex_k = 6
|
| 110 |
+
|
| 111 |
+
# Config and model path
|
| 112 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 113 |
+
# model path
|
| 114 |
+
model_name = '/nfs/hub/Wan2.1-T2V-1.3B-Diffusers'
|
| 115 |
+
|
| 116 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 117 |
+
sampler_name = args.sampler_name
|
| 118 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 119 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 120 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 121 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 122 |
+
shift = args.shift
|
| 123 |
+
|
| 124 |
+
# Load pretrained model if need
|
| 125 |
+
transformer_path = args.transformer_path
|
| 126 |
+
vae_path = None
|
| 127 |
+
|
| 128 |
+
lora_path = args.lora_path
|
| 129 |
+
# pdb.set_trace()
|
| 130 |
+
# Other params
|
| 131 |
+
sample_size = [args.sample_height, args.sample_width]
|
| 132 |
+
video_length = 49
|
| 133 |
+
fps = 16
|
| 134 |
+
|
| 135 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 136 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 137 |
+
prompt_list_path = args.prompt_list_path
|
| 138 |
+
num_generated_videos = args.num_generated_videos
|
| 139 |
+
weight_dtype = torch.bfloat16
|
| 140 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 141 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 142 |
+
guidance_scale = 6.0
|
| 143 |
+
seed = args.seed
|
| 144 |
+
num_inference_steps = args.num_inference_steps
|
| 145 |
+
lora_weight = 1.0
|
| 146 |
+
|
| 147 |
+
ckpt = args.lora_path.split('/')[-2]
|
| 148 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}/{ckpt}"
|
| 149 |
+
|
| 150 |
+
# if use_h3ae:
|
| 151 |
+
# # pdb.set_trace()
|
| 152 |
+
# save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 153 |
+
# import pdb
|
| 154 |
+
# pdb.set_trace()
|
| 155 |
+
if seed != 42:
|
| 156 |
+
save_path= f"{save_path}-seed{seed}"
|
| 157 |
+
|
| 158 |
+
# if seed == -1:
|
| 159 |
+
# save_path= f"{save_path}-randomseed"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# if lora_path:
|
| 163 |
+
# import pdb
|
| 164 |
+
# # pdb.set_trace()
|
| 165 |
+
# sub_path = lora_path.split('/')[-2]
|
| 166 |
+
# itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 167 |
+
# save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 168 |
+
# elif transformer_path:
|
| 169 |
+
# sub_path = transformer_path.split('/')[-4]
|
| 170 |
+
# itr = transformer_path.split('/')[-3].split('-')[-1]
|
| 171 |
+
# save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 172 |
+
# # pdb.set_trace()
|
| 173 |
+
# else:
|
| 174 |
+
# save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-seed{seed}/output_pretrain'
|
| 175 |
+
|
| 176 |
+
# if args.debug:
|
| 177 |
+
# lora_path = None
|
| 178 |
+
# save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 179 |
+
|
| 180 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 181 |
+
config = OmegaConf.load(config_path)
|
| 182 |
+
|
| 183 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 184 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 185 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 186 |
+
low_cpu_mem_usage=True,
|
| 187 |
+
torch_dtype=weight_dtype,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if transformer_path is not None:
|
| 191 |
+
print(f"From checkpoint: {transformer_path}")
|
| 192 |
+
if transformer_path.endswith("safetensors"):
|
| 193 |
+
from safetensors.torch import load_file, safe_open
|
| 194 |
+
state_dict = load_file(transformer_path)
|
| 195 |
+
else:
|
| 196 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 197 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 198 |
+
# pdb.set_trace()
|
| 199 |
+
|
| 200 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 201 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 202 |
+
# pdb.set_trace()
|
| 203 |
+
|
| 204 |
+
# Get Vae
|
| 205 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 206 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 207 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 208 |
+
).to(weight_dtype)
|
| 209 |
+
|
| 210 |
+
if vae_path is not None:
|
| 211 |
+
print(f"From checkpoint: {vae_path}")
|
| 212 |
+
if vae_path.endswith("safetensors"):
|
| 213 |
+
from safetensors.torch import load_file, safe_open
|
| 214 |
+
state_dict = load_file(vae_path)
|
| 215 |
+
else:
|
| 216 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 217 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 218 |
+
|
| 219 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 220 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 221 |
+
|
| 222 |
+
# Get Tokenizer
|
| 223 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 224 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Get Text encoder
|
| 228 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 229 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 230 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 231 |
+
low_cpu_mem_usage=True,
|
| 232 |
+
torch_dtype=weight_dtype,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# Get Scheduler
|
| 236 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 237 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 238 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 239 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 240 |
+
}[sampler_name]
|
| 241 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 242 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 243 |
+
scheduler = Chosen_Scheduler(
|
| 244 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Get Pipeline
|
| 248 |
+
pipeline = WanPipeline(
|
| 249 |
+
transformer=transformer,
|
| 250 |
+
vae=vae,
|
| 251 |
+
tokenizer=tokenizer,
|
| 252 |
+
text_encoder=text_encoder,
|
| 253 |
+
scheduler=scheduler,
|
| 254 |
+
)
|
| 255 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 256 |
+
from functools import partial
|
| 257 |
+
transformer.enable_multi_gpus_inference()
|
| 258 |
+
if fsdp_dit:
|
| 259 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 260 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 261 |
+
print("Add FSDP DIT")
|
| 262 |
+
if fsdp_text_encoder:
|
| 263 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 264 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 265 |
+
print("Add FSDP TEXT ENCODER")
|
| 266 |
+
|
| 267 |
+
if compile_dit:
|
| 268 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 269 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 270 |
+
print("Add Compile")
|
| 271 |
+
|
| 272 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 273 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 274 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 275 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 276 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 277 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 278 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 279 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 280 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 281 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 282 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 283 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 284 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 285 |
+
pipeline.to(device=device)
|
| 286 |
+
else:
|
| 287 |
+
pipeline.to(device=device)
|
| 288 |
+
|
| 289 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 290 |
+
if coefficients is not None:
|
| 291 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 292 |
+
pipeline.transformer.enable_teacache(
|
| 293 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
if cfg_skip_ratio is not None:
|
| 297 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 298 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 302 |
+
if seed == -1:
|
| 303 |
+
generator = None
|
| 304 |
+
|
| 305 |
+
prompt_list = []
|
| 306 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 307 |
+
for line in file:
|
| 308 |
+
# 去除行末的换行符
|
| 309 |
+
prompt_list.append(line.strip())
|
| 310 |
+
|
| 311 |
+
if args.lora_path:
|
| 312 |
+
# Set correct lora layers
|
| 313 |
+
target_modules = [
|
| 314 |
+
"add_k_proj",
|
| 315 |
+
"add_q_proj",
|
| 316 |
+
"add_v_proj",
|
| 317 |
+
"to_add_out",
|
| 318 |
+
"to_k",
|
| 319 |
+
"to_out.0",
|
| 320 |
+
"to_q",
|
| 321 |
+
"to_v",
|
| 322 |
+
]
|
| 323 |
+
transformer_lora_config = LoraConfig(
|
| 324 |
+
r=32,
|
| 325 |
+
lora_alpha=64,
|
| 326 |
+
init_lora_weights="gaussian",
|
| 327 |
+
target_modules=target_modules,
|
| 328 |
+
)
|
| 329 |
+
if args.lora_path:
|
| 330 |
+
pipeline.transformer = PeftModel.from_pretrained(pipeline.transformer, args.lora_path)
|
| 331 |
+
# 使用PeftModel.from_pretrained load后所有参数的requires_grad都是False,需要set_adapter来使得adapter参数梯度为True
|
| 332 |
+
pipeline.transformer.set_adapter("default")
|
| 333 |
+
else:
|
| 334 |
+
pipeline.transformer = get_peft_model(pipeline.transformer, transformer_lora_config)
|
| 335 |
+
|
| 336 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 337 |
+
if num_generated_videos == -1:
|
| 338 |
+
num_generated_videos = len(prompt_list)
|
| 339 |
+
|
| 340 |
+
# for prompt in prompt_list[:num_generated_videos]:
|
| 341 |
+
for i in range(len(prompt_list[:num_generated_videos])):
|
| 342 |
+
prompt = prompt_list[:num_generated_videos][i]
|
| 343 |
+
prefix = str(i+1).zfill(8)
|
| 344 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 345 |
+
if os.path.exists(video_path):
|
| 346 |
+
continue
|
| 347 |
+
|
| 348 |
+
with torch.no_grad():
|
| 349 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 350 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 351 |
+
|
| 352 |
+
if enable_riflex:
|
| 353 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 354 |
+
|
| 355 |
+
sample = pipeline(
|
| 356 |
+
prompt,
|
| 357 |
+
num_frames = video_length,
|
| 358 |
+
negative_prompt = negative_prompt,
|
| 359 |
+
height = sample_size[0],
|
| 360 |
+
width = sample_size[1],
|
| 361 |
+
generator = generator,
|
| 362 |
+
guidance_scale = guidance_scale,
|
| 363 |
+
num_inference_steps = num_inference_steps,
|
| 364 |
+
shift = shift,
|
| 365 |
+
).videos
|
| 366 |
+
|
| 367 |
+
# if lora_path is not None:
|
| 368 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 369 |
+
|
| 370 |
+
def save_results():
|
| 371 |
+
if not os.path.exists(save_path):
|
| 372 |
+
os.makedirs(save_path, exist_ok=True)
|
| 373 |
+
|
| 374 |
+
# index = len([path for path in os.listdir(save_path)]) + 1
|
| 375 |
+
# prefix = str(index).zfill(8)
|
| 376 |
+
if video_length == 1:
|
| 377 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 378 |
+
|
| 379 |
+
image = sample[0, :, 0]
|
| 380 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 381 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 382 |
+
image = Image.fromarray(image)
|
| 383 |
+
image.save(video_path)
|
| 384 |
+
else:
|
| 385 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 386 |
+
print(f'saved to {video_path}')
|
| 387 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 388 |
+
|
| 389 |
+
if ulysses_degree * ring_degree > 1:
|
| 390 |
+
import torch.distributed as dist
|
| 391 |
+
if dist.get_rank() == 0:
|
| 392 |
+
save_results()
|
| 393 |
+
else:
|
| 394 |
+
save_results()
|
| 395 |
+
|
| 396 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_val.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
WanTransformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import WanPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = False
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 62 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 63 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 64 |
+
teacache_threshold = 0.10
|
| 65 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 66 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 67 |
+
num_skip_start_steps = 5
|
| 68 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 69 |
+
teacache_offload = False
|
| 70 |
+
|
| 71 |
+
# Skip some cfg steps in inference
|
| 72 |
+
# Recommended to be set between 0.00 and 0.25
|
| 73 |
+
cfg_skip_ratio = 0
|
| 74 |
+
|
| 75 |
+
# Riflex config
|
| 76 |
+
enable_riflex = False
|
| 77 |
+
# Index of intrinsic frequency
|
| 78 |
+
riflex_k = 6
|
| 79 |
+
|
| 80 |
+
# Config and model path
|
| 81 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 82 |
+
# model path
|
| 83 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 84 |
+
|
| 85 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 86 |
+
sampler_name = "Flow_Unipc"
|
| 87 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 88 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 89 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 90 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 91 |
+
shift = 5
|
| 92 |
+
|
| 93 |
+
# Load pretrained model if need
|
| 94 |
+
# transformer_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_full/output_Oct31_1/checkpoint-1000/transformer/diffusion_pytorch_model.safetensors'
|
| 95 |
+
transformer_path = None
|
| 96 |
+
vae_path = None
|
| 97 |
+
lora_path = None
|
| 98 |
+
|
| 99 |
+
# Other params
|
| 100 |
+
sample_size = [512, 288]
|
| 101 |
+
video_length = 49
|
| 102 |
+
fps = 16
|
| 103 |
+
|
| 104 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 105 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 106 |
+
weight_dtype = torch.bfloat16
|
| 107 |
+
prompt = "In the video, a young boy and girl are seated at a dining table, engaged in a cooking activity. The boy is holding a jar of cream, while the girl is holding a bowl. On the table, there are several ingredients, including lemons, a vase with flowers, and a bottle of oil. The table is covered with a white tablecloth, and there are chairs around it. The setting appears to be a kitchen or dining area, and the atmosphere is casual and relaxed. The children seem to be enjoying their time together, and the video captures a moment of creativity and learning."
|
| 108 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 109 |
+
guidance_scale = 6.0
|
| 110 |
+
seed = 43
|
| 111 |
+
num_inference_steps = 30
|
| 112 |
+
# lora_weight = 0.55
|
| 113 |
+
save_path = "samples/fig3"
|
| 114 |
+
|
| 115 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 116 |
+
config = OmegaConf.load(config_path)
|
| 117 |
+
|
| 118 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 119 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 120 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 121 |
+
low_cpu_mem_usage=True,
|
| 122 |
+
torch_dtype=weight_dtype,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if transformer_path is not None:
|
| 126 |
+
print(f"From checkpoint: {transformer_path}")
|
| 127 |
+
if transformer_path.endswith("safetensors"):
|
| 128 |
+
from safetensors.torch import load_file, safe_open
|
| 129 |
+
state_dict = load_file(transformer_path)
|
| 130 |
+
else:
|
| 131 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 132 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 133 |
+
|
| 134 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 135 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 136 |
+
|
| 137 |
+
# Get Vae
|
| 138 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 139 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 140 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 141 |
+
).to(weight_dtype)
|
| 142 |
+
|
| 143 |
+
if vae_path is not None:
|
| 144 |
+
print(f"From checkpoint: {vae_path}")
|
| 145 |
+
if vae_path.endswith("safetensors"):
|
| 146 |
+
from safetensors.torch import load_file, safe_open
|
| 147 |
+
state_dict = load_file(vae_path)
|
| 148 |
+
else:
|
| 149 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 150 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 151 |
+
|
| 152 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 153 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 154 |
+
|
| 155 |
+
# Get Tokenizer
|
| 156 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 157 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Get Text encoder
|
| 161 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 162 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 163 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 164 |
+
low_cpu_mem_usage=True,
|
| 165 |
+
torch_dtype=weight_dtype,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Get Scheduler
|
| 169 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 170 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 171 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 172 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 173 |
+
}[sampler_name]
|
| 174 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 175 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 176 |
+
scheduler = Chosen_Scheduler(
|
| 177 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Get Pipeline
|
| 181 |
+
pipeline = WanPipeline(
|
| 182 |
+
transformer=transformer,
|
| 183 |
+
vae=vae,
|
| 184 |
+
tokenizer=tokenizer,
|
| 185 |
+
text_encoder=text_encoder,
|
| 186 |
+
scheduler=scheduler,
|
| 187 |
+
)
|
| 188 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 189 |
+
from functools import partial
|
| 190 |
+
transformer.enable_multi_gpus_inference()
|
| 191 |
+
if fsdp_dit:
|
| 192 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 193 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 194 |
+
print("Add FSDP DIT")
|
| 195 |
+
if fsdp_text_encoder:
|
| 196 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 197 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 198 |
+
print("Add FSDP TEXT ENCODER")
|
| 199 |
+
|
| 200 |
+
if compile_dit:
|
| 201 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 202 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 203 |
+
print("Add Compile")
|
| 204 |
+
|
| 205 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 206 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 207 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 208 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 209 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 210 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 211 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 212 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 213 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 214 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 215 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 216 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 217 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 218 |
+
pipeline.to(device=device)
|
| 219 |
+
else:
|
| 220 |
+
pipeline.to(device=device)
|
| 221 |
+
|
| 222 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 223 |
+
if coefficients is not None:
|
| 224 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 225 |
+
pipeline.transformer.enable_teacache(
|
| 226 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
if cfg_skip_ratio is not None:
|
| 230 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 231 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 232 |
+
|
| 233 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 234 |
+
|
| 235 |
+
if lora_path is not None:
|
| 236 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
| 237 |
+
|
| 238 |
+
with torch.no_grad():
|
| 239 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 240 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 241 |
+
|
| 242 |
+
if enable_riflex:
|
| 243 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 244 |
+
|
| 245 |
+
sample = pipeline(
|
| 246 |
+
prompt,
|
| 247 |
+
num_frames = video_length,
|
| 248 |
+
negative_prompt = negative_prompt,
|
| 249 |
+
height = sample_size[0],
|
| 250 |
+
width = sample_size[1],
|
| 251 |
+
generator = generator,
|
| 252 |
+
guidance_scale = guidance_scale,
|
| 253 |
+
num_inference_steps = num_inference_steps,
|
| 254 |
+
shift = shift,
|
| 255 |
+
).videos
|
| 256 |
+
|
| 257 |
+
if lora_path is not None:
|
| 258 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device, dtype=weight_dtype)
|
| 259 |
+
|
| 260 |
+
def save_results():
|
| 261 |
+
if not os.path.exists(save_path):
|
| 262 |
+
os.makedirs(save_path, exist_ok=True)
|
| 263 |
+
|
| 264 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 265 |
+
prefix = str(index).zfill(8)
|
| 266 |
+
if video_length == 1:
|
| 267 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 268 |
+
|
| 269 |
+
image = sample[0, :, 0]
|
| 270 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 271 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 272 |
+
image = Image.fromarray(image)
|
| 273 |
+
image.save(video_path)
|
| 274 |
+
else:
|
| 275 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 276 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 277 |
+
|
| 278 |
+
if ulysses_degree * ring_degree > 1:
|
| 279 |
+
import torch.distributed as dist
|
| 280 |
+
if dist.get_rank() == 0:
|
| 281 |
+
save_results()
|
| 282 |
+
else:
|
| 283 |
+
save_results()
|
VideoX-Fun/examples/wan2.1/predict_t2v_val1.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
WanTransformer3DModel, H3AE)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import WanPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
|
| 31 |
+
parser.add_argument("--lora_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_videoalign/output_Oct5/checkpoint-1500.safetensors', help="prompt file for inference")
|
| 32 |
+
parser.add_argument("--save_folder", type=str, default='samples1', help="prompt file for inference")
|
| 33 |
+
|
| 34 |
+
parser.add_argument("--sample_size", type=list, default=[512, 288], help="prompt file for inference")
|
| 35 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 36 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 37 |
+
|
| 38 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 39 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 41 |
+
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 44 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 45 |
+
#
|
| 46 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 47 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 48 |
+
#
|
| 49 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 50 |
+
#
|
| 51 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 52 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 53 |
+
#
|
| 54 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 55 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 56 |
+
|
| 57 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 58 |
+
# Multi GPUs config
|
| 59 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 60 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 61 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 62 |
+
ulysses_degree = 1
|
| 63 |
+
ring_degree = 1
|
| 64 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 65 |
+
fsdp_dit = False
|
| 66 |
+
fsdp_text_encoder = True
|
| 67 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 68 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 69 |
+
compile_dit = False
|
| 70 |
+
|
| 71 |
+
# TeaCache config
|
| 72 |
+
enable_teacache = True
|
| 73 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 74 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 75 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 76 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 77 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 78 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 79 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 80 |
+
teacache_threshold = 0.10
|
| 81 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 82 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 83 |
+
num_skip_start_steps = 5
|
| 84 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 85 |
+
teacache_offload = False
|
| 86 |
+
|
| 87 |
+
# Skip some cfg steps in inference
|
| 88 |
+
# Recommended to be set between 0.00 and 0.25
|
| 89 |
+
cfg_skip_ratio = 0
|
| 90 |
+
|
| 91 |
+
# Riflex config
|
| 92 |
+
enable_riflex = False
|
| 93 |
+
# Index of intrinsic frequency
|
| 94 |
+
riflex_k = 6
|
| 95 |
+
|
| 96 |
+
# Config and model path
|
| 97 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 98 |
+
# model path
|
| 99 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 100 |
+
|
| 101 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 102 |
+
sampler_name = "Flow_Unipc"
|
| 103 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 104 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 105 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 106 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 107 |
+
shift = 3
|
| 108 |
+
|
| 109 |
+
# Load pretrained model if need
|
| 110 |
+
transformer_path = None
|
| 111 |
+
vae_path = None
|
| 112 |
+
use_h3ae = args.use_h3ae
|
| 113 |
+
lora_path = None
|
| 114 |
+
|
| 115 |
+
# Other params
|
| 116 |
+
sample_size = args.sample_size
|
| 117 |
+
video_length = 49
|
| 118 |
+
fps = 16
|
| 119 |
+
|
| 120 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 121 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 122 |
+
prompt_list_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt'
|
| 123 |
+
num_generated_videos = 30
|
| 124 |
+
weight_dtype = torch.bfloat16
|
| 125 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 126 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 127 |
+
# negative_prompt = ""
|
| 128 |
+
|
| 129 |
+
guidance_scale = 6.0
|
| 130 |
+
seed = args.seed
|
| 131 |
+
num_inference_steps = args.num_inference_steps
|
| 132 |
+
lora_weight = args.lora_weight
|
| 133 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 134 |
+
|
| 135 |
+
if use_h3ae:
|
| 136 |
+
# pdb.set_trace()
|
| 137 |
+
save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 138 |
+
|
| 139 |
+
if seed != 42:
|
| 140 |
+
save_path= f"{save_path}-seed{seed}"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if lora_path:
|
| 144 |
+
import pdb
|
| 145 |
+
# pdb.set_trace()
|
| 146 |
+
sub_path = lora_path.split('/')[-2]
|
| 147 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 148 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 149 |
+
else:
|
| 150 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}/output_pretrain'
|
| 151 |
+
|
| 152 |
+
if args.debug:
|
| 153 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 154 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 155 |
+
config = OmegaConf.load(config_path)
|
| 156 |
+
|
| 157 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 158 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 159 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 160 |
+
low_cpu_mem_usage=True,
|
| 161 |
+
torch_dtype=weight_dtype,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
if transformer_path is not None:
|
| 165 |
+
print(f"From checkpoint: {transformer_path}")
|
| 166 |
+
if transformer_path.endswith("safetensors"):
|
| 167 |
+
from safetensors.torch import load_file, safe_open
|
| 168 |
+
state_dict = load_file(transformer_path)
|
| 169 |
+
else:
|
| 170 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 171 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 172 |
+
|
| 173 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 174 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 175 |
+
|
| 176 |
+
# Get Vae
|
| 177 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 178 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 179 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 180 |
+
).to(weight_dtype)
|
| 181 |
+
h3ae = H3AE.from_pretrained("/nfs/hub/h3ae/h3ae_wan_ch64_41616_channel").to(weight_dtype).to(device)
|
| 182 |
+
|
| 183 |
+
if vae_path is not None:
|
| 184 |
+
print(f"From checkpoint: {vae_path}")
|
| 185 |
+
if vae_path.endswith("safetensors"):
|
| 186 |
+
from safetensors.torch import load_file, safe_open
|
| 187 |
+
state_dict = load_file(vae_path)
|
| 188 |
+
else:
|
| 189 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 190 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 191 |
+
|
| 192 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 193 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 194 |
+
|
| 195 |
+
# Get Tokenizer
|
| 196 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 197 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Get Text encoder
|
| 201 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 202 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 203 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 204 |
+
low_cpu_mem_usage=True,
|
| 205 |
+
torch_dtype=weight_dtype,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
prompt_list = []
|
| 209 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 210 |
+
for line in file:
|
| 211 |
+
# 去除行末的换行符
|
| 212 |
+
prompt_list.append(line.strip())
|
| 213 |
+
|
| 214 |
+
for prompt in prompt_list[:num_generated_videos]:
|
| 215 |
+
|
| 216 |
+
# Get Scheduler
|
| 217 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 218 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 219 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 220 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 221 |
+
}[sampler_name]
|
| 222 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 223 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 224 |
+
scheduler = Chosen_Scheduler(
|
| 225 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Get Pipeline
|
| 229 |
+
pipeline = WanPipeline(
|
| 230 |
+
transformer=transformer,
|
| 231 |
+
vae=vae,
|
| 232 |
+
tokenizer=tokenizer,
|
| 233 |
+
text_encoder=text_encoder,
|
| 234 |
+
scheduler=scheduler,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 238 |
+
from functools import partial
|
| 239 |
+
transformer.enable_multi_gpus_inference()
|
| 240 |
+
if fsdp_dit:
|
| 241 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 242 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 243 |
+
print("Add FSDP DIT")
|
| 244 |
+
if fsdp_text_encoder:
|
| 245 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 246 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 247 |
+
print("Add FSDP TEXT ENCODER")
|
| 248 |
+
|
| 249 |
+
if compile_dit:
|
| 250 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 251 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 252 |
+
print("Add Compile")
|
| 253 |
+
|
| 254 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 255 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 256 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 257 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 258 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 259 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 260 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 261 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 262 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 263 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 264 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 265 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 266 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 267 |
+
pipeline.to(device=device)
|
| 268 |
+
else:
|
| 269 |
+
pipeline.to(device=device)
|
| 270 |
+
|
| 271 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 272 |
+
if coefficients is not None:
|
| 273 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 274 |
+
pipeline.transformer.enable_teacache(
|
| 275 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if cfg_skip_ratio is not None:
|
| 279 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 280 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 281 |
+
|
| 282 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if lora_path is not None:
|
| 287 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 288 |
+
|
| 289 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 290 |
+
with torch.no_grad():
|
| 291 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 292 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 293 |
+
|
| 294 |
+
if enable_riflex:
|
| 295 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 296 |
+
|
| 297 |
+
if not use_h3ae:
|
| 298 |
+
sample = pipeline(
|
| 299 |
+
prompt,
|
| 300 |
+
num_frames = video_length,
|
| 301 |
+
negative_prompt = negative_prompt,
|
| 302 |
+
height = sample_size[0],
|
| 303 |
+
width = sample_size[1],
|
| 304 |
+
generator = generator,
|
| 305 |
+
guidance_scale = guidance_scale,
|
| 306 |
+
num_inference_steps = num_inference_steps,
|
| 307 |
+
shift = shift,
|
| 308 |
+
).videos
|
| 309 |
+
import pdb
|
| 310 |
+
# pdb.set_trace()
|
| 311 |
+
else:
|
| 312 |
+
latents = pipeline(
|
| 313 |
+
prompt,
|
| 314 |
+
num_frames = video_length,
|
| 315 |
+
negative_prompt = negative_prompt,
|
| 316 |
+
height = sample_size[0],
|
| 317 |
+
width = sample_size[1],
|
| 318 |
+
generator = generator,
|
| 319 |
+
guidance_scale = guidance_scale,
|
| 320 |
+
num_inference_steps = num_inference_steps,
|
| 321 |
+
shift = shift,
|
| 322 |
+
output_type = 'latent',
|
| 323 |
+
return_dict = True
|
| 324 |
+
).videos
|
| 325 |
+
|
| 326 |
+
latents = torch.nn.functional.pixel_unshuffle(latents.transpose(1, 2), 2).transpose(1, 2)
|
| 327 |
+
# sample = sample.clamp(-1,1)
|
| 328 |
+
# pdb.set_trace()
|
| 329 |
+
sample = h3ae.decode(latents)[0]
|
| 330 |
+
sample = (sample / 2 + 0.5).clamp(0, 1).cpu().float()#.numpy()
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
if lora_path is not None:
|
| 334 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 335 |
+
|
| 336 |
+
def save_results():
|
| 337 |
+
if not os.path.exists(save_path):
|
| 338 |
+
os.makedirs(save_path, exist_ok=True)
|
| 339 |
+
|
| 340 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 341 |
+
prefix = str(index).zfill(8)
|
| 342 |
+
if video_length == 1:
|
| 343 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 344 |
+
|
| 345 |
+
image = sample[0, :, 0]
|
| 346 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 347 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 348 |
+
image = Image.fromarray(image)
|
| 349 |
+
image.save(video_path)
|
| 350 |
+
else:
|
| 351 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 352 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 353 |
+
|
| 354 |
+
if ulysses_degree * ring_degree > 1:
|
| 355 |
+
import torch.distributed as dist
|
| 356 |
+
if dist.get_rank() == 0:
|
| 357 |
+
save_results()
|
| 358 |
+
else:
|
| 359 |
+
save_results()
|
| 360 |
+
|
| 361 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_val2.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
|
| 32 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 35 |
+
|
| 36 |
+
parser.add_argument("--save_folder", type=str, default='samples4', help="prompt file for inference")
|
| 37 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--sample_height", type=list, default=512, help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--sample_width", type=list, default=288, help="prompt file for inference")
|
| 41 |
+
|
| 42 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 43 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 44 |
+
|
| 45 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 46 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 47 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 48 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 52 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 53 |
+
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 56 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 57 |
+
#
|
| 58 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 59 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 60 |
+
#
|
| 61 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 62 |
+
#
|
| 63 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 64 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 65 |
+
#
|
| 66 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 67 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 68 |
+
|
| 69 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 70 |
+
# Multi GPUs config
|
| 71 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 72 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 73 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 74 |
+
ulysses_degree = 1
|
| 75 |
+
ring_degree = 1
|
| 76 |
+
|
| 77 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 78 |
+
fsdp_dit = False
|
| 79 |
+
fsdp_text_encoder = True
|
| 80 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 81 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 82 |
+
compile_dit = False
|
| 83 |
+
|
| 84 |
+
# TeaCache config
|
| 85 |
+
enable_teacache = True
|
| 86 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 87 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 88 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 89 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 90 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 91 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 92 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 93 |
+
teacache_threshold = 0.10
|
| 94 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 95 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 96 |
+
num_skip_start_steps = 5
|
| 97 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 98 |
+
teacache_offload = False
|
| 99 |
+
|
| 100 |
+
# Skip some cfg steps in inference
|
| 101 |
+
# Recommended to be set between 0.00 and 0.25
|
| 102 |
+
cfg_skip_ratio = 0
|
| 103 |
+
|
| 104 |
+
# Riflex config
|
| 105 |
+
enable_riflex = False
|
| 106 |
+
# Index of intrinsic frequency
|
| 107 |
+
riflex_k = 6
|
| 108 |
+
|
| 109 |
+
# Config and model path
|
| 110 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 111 |
+
# model path
|
| 112 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 113 |
+
|
| 114 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 115 |
+
sampler_name = args.sampler_name
|
| 116 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 117 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 118 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 119 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 120 |
+
shift = 3 # 8
|
| 121 |
+
|
| 122 |
+
# Load pretrained model if need
|
| 123 |
+
transformer_path = args.transformer_path
|
| 124 |
+
vae_path = None
|
| 125 |
+
|
| 126 |
+
lora_path = args.lora_path
|
| 127 |
+
# pdb.set_trace()
|
| 128 |
+
# Other params
|
| 129 |
+
sample_size = [args.sample_height, args.sample_width]
|
| 130 |
+
video_length = 49
|
| 131 |
+
fps = 16
|
| 132 |
+
|
| 133 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 134 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 135 |
+
prompt_list_path = args.prompt_list_path
|
| 136 |
+
num_generated_videos = args.num_generated_videos
|
| 137 |
+
weight_dtype = torch.bfloat16
|
| 138 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 139 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 140 |
+
|
| 141 |
+
guidance_scale = 6.0
|
| 142 |
+
|
| 143 |
+
seed = args.seed
|
| 144 |
+
num_inference_steps = args.num_inference_steps
|
| 145 |
+
lora_weight = 1.0
|
| 146 |
+
|
| 147 |
+
if not transformer_path:
|
| 148 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}-lw{lora_weight}"
|
| 149 |
+
else:
|
| 150 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}"
|
| 151 |
+
|
| 152 |
+
# if use_h3ae:
|
| 153 |
+
# # pdb.set_trace()
|
| 154 |
+
# save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 155 |
+
# import pdb
|
| 156 |
+
# pdb.set_trace()
|
| 157 |
+
if seed != 42:
|
| 158 |
+
save_path= f"{save_path}-seed{seed}"
|
| 159 |
+
|
| 160 |
+
# if seed == -1:
|
| 161 |
+
# save_path= f"{save_path}-randomseed"
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if lora_path:
|
| 165 |
+
import pdb
|
| 166 |
+
# pdb.set_trace()
|
| 167 |
+
sub_path = lora_path.split('/')[-2]
|
| 168 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 169 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 170 |
+
elif transformer_path:
|
| 171 |
+
sub_path = transformer_path.split('/')[-4]
|
| 172 |
+
itr = transformer_path.split('/')[-3].split('-')[-1]
|
| 173 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 174 |
+
# pdb.set_trace()
|
| 175 |
+
else:
|
| 176 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-seed{seed}/output_pretrain'
|
| 177 |
+
|
| 178 |
+
if args.debug:
|
| 179 |
+
lora_path = None
|
| 180 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 181 |
+
|
| 182 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 183 |
+
config = OmegaConf.load(config_path)
|
| 184 |
+
|
| 185 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 186 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 187 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 188 |
+
low_cpu_mem_usage=True,
|
| 189 |
+
torch_dtype=weight_dtype,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if transformer_path is not None:
|
| 193 |
+
print(f"From checkpoint: {transformer_path}")
|
| 194 |
+
if transformer_path.endswith("safetensors"):
|
| 195 |
+
from safetensors.torch import load_file, safe_open
|
| 196 |
+
state_dict = load_file(transformer_path)
|
| 197 |
+
else:
|
| 198 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 199 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 200 |
+
# pdb.set_trace()
|
| 201 |
+
|
| 202 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 203 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 204 |
+
# pdb.set_trace()
|
| 205 |
+
|
| 206 |
+
# Get Vae
|
| 207 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 208 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 209 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 210 |
+
).to(weight_dtype)
|
| 211 |
+
|
| 212 |
+
if vae_path is not None:
|
| 213 |
+
print(f"From checkpoint: {vae_path}")
|
| 214 |
+
if vae_path.endswith("safetensors"):
|
| 215 |
+
from safetensors.torch import load_file, safe_open
|
| 216 |
+
state_dict = load_file(vae_path)
|
| 217 |
+
else:
|
| 218 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 219 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 220 |
+
|
| 221 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 222 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 223 |
+
|
| 224 |
+
# Get Tokenizer
|
| 225 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 226 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Get Text encoder
|
| 230 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 231 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 232 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 233 |
+
low_cpu_mem_usage=True,
|
| 234 |
+
torch_dtype=weight_dtype,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
# Get Scheduler
|
| 238 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 239 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 240 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 241 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 242 |
+
}[sampler_name]
|
| 243 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 244 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 245 |
+
scheduler = Chosen_Scheduler(
|
| 246 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# Get Pipeline
|
| 250 |
+
pipeline = WanPipeline(
|
| 251 |
+
transformer=transformer,
|
| 252 |
+
vae=vae,
|
| 253 |
+
tokenizer=tokenizer,
|
| 254 |
+
text_encoder=text_encoder,
|
| 255 |
+
scheduler=scheduler,
|
| 256 |
+
)
|
| 257 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 258 |
+
from functools import partial
|
| 259 |
+
transformer.enable_multi_gpus_inference()
|
| 260 |
+
if fsdp_dit:
|
| 261 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 262 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 263 |
+
print("Add FSDP DIT")
|
| 264 |
+
if fsdp_text_encoder:
|
| 265 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 266 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 267 |
+
print("Add FSDP TEXT ENCODER")
|
| 268 |
+
|
| 269 |
+
if compile_dit:
|
| 270 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 271 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 272 |
+
print("Add Compile")
|
| 273 |
+
|
| 274 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 275 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 276 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 277 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 278 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 279 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 280 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 281 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 282 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 283 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 284 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 285 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 286 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 287 |
+
pipeline.to(device=device)
|
| 288 |
+
else:
|
| 289 |
+
pipeline.to(device=device)
|
| 290 |
+
|
| 291 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 292 |
+
if coefficients is not None:
|
| 293 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 294 |
+
pipeline.transformer.enable_teacache(
|
| 295 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if cfg_skip_ratio is not None:
|
| 299 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 300 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 304 |
+
if seed == -1:
|
| 305 |
+
generator = None
|
| 306 |
+
|
| 307 |
+
prompt_list = []
|
| 308 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 309 |
+
for line in file:
|
| 310 |
+
# 去除行末的换行符
|
| 311 |
+
prompt_list.append(line.strip())
|
| 312 |
+
|
| 313 |
+
if lora_path is not None:
|
| 314 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 315 |
+
|
| 316 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 317 |
+
if num_generated_videos == -1:
|
| 318 |
+
num_generated_videos = len(prompt_list)
|
| 319 |
+
for prompt in prompt_list[:num_generated_videos]:
|
| 320 |
+
with torch.no_grad():
|
| 321 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 322 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 323 |
+
|
| 324 |
+
if enable_riflex:
|
| 325 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 326 |
+
|
| 327 |
+
sample = pipeline(
|
| 328 |
+
prompt,
|
| 329 |
+
num_frames = video_length,
|
| 330 |
+
negative_prompt = negative_prompt,
|
| 331 |
+
height = sample_size[0],
|
| 332 |
+
width = sample_size[1],
|
| 333 |
+
generator = generator,
|
| 334 |
+
guidance_scale = guidance_scale,
|
| 335 |
+
num_inference_steps = num_inference_steps,
|
| 336 |
+
shift = shift,
|
| 337 |
+
).videos
|
| 338 |
+
|
| 339 |
+
# if lora_path is not None:
|
| 340 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 341 |
+
|
| 342 |
+
def save_results():
|
| 343 |
+
if not os.path.exists(save_path):
|
| 344 |
+
os.makedirs(save_path, exist_ok=True)
|
| 345 |
+
|
| 346 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 347 |
+
prefix = str(index).zfill(8)
|
| 348 |
+
if video_length == 1:
|
| 349 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 350 |
+
|
| 351 |
+
image = sample[0, :, 0]
|
| 352 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 353 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 354 |
+
image = Image.fromarray(image)
|
| 355 |
+
image.save(video_path)
|
| 356 |
+
else:
|
| 357 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 358 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 359 |
+
|
| 360 |
+
if ulysses_degree * ring_degree > 1:
|
| 361 |
+
import torch.distributed as dist
|
| 362 |
+
if dist.get_rank() == 0:
|
| 363 |
+
save_results()
|
| 364 |
+
else:
|
| 365 |
+
save_results()
|
| 366 |
+
|
| 367 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_val3.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
|
| 32 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 35 |
+
|
| 36 |
+
parser.add_argument("--save_folder", type=str, default='samples4', help="prompt file for inference")
|
| 37 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--sample_height", type=int, default=512, help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--sample_width", type=int, default=288, help="prompt file for inference")
|
| 41 |
+
|
| 42 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 43 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 44 |
+
# parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 45 |
+
|
| 46 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 47 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 48 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 49 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 53 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 54 |
+
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 57 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 58 |
+
#
|
| 59 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 60 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 61 |
+
#
|
| 62 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 63 |
+
#
|
| 64 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 65 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 66 |
+
#
|
| 67 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 68 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 69 |
+
|
| 70 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 71 |
+
# Multi GPUs config
|
| 72 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 73 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 74 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 75 |
+
ulysses_degree = 1
|
| 76 |
+
ring_degree = 1
|
| 77 |
+
|
| 78 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 79 |
+
fsdp_dit = False
|
| 80 |
+
fsdp_text_encoder = True
|
| 81 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 82 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 83 |
+
compile_dit = False
|
| 84 |
+
|
| 85 |
+
# TeaCache config
|
| 86 |
+
enable_teacache = True
|
| 87 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 88 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 89 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 90 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 91 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 92 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 93 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 94 |
+
teacache_threshold = 0.10
|
| 95 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 96 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 97 |
+
num_skip_start_steps = 5
|
| 98 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 99 |
+
teacache_offload = False
|
| 100 |
+
|
| 101 |
+
# Skip some cfg steps in inference
|
| 102 |
+
# Recommended to be set between 0.00 and 0.25
|
| 103 |
+
cfg_skip_ratio = 0
|
| 104 |
+
|
| 105 |
+
# Riflex config
|
| 106 |
+
enable_riflex = False
|
| 107 |
+
# Index of intrinsic frequency
|
| 108 |
+
riflex_k = 6
|
| 109 |
+
|
| 110 |
+
# Config and model path
|
| 111 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 112 |
+
# model path
|
| 113 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 114 |
+
|
| 115 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 116 |
+
sampler_name = args.sampler_name
|
| 117 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 118 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 119 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 120 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 121 |
+
shift = args.shift
|
| 122 |
+
|
| 123 |
+
# Load pretrained model if need
|
| 124 |
+
transformer_path = args.transformer_path
|
| 125 |
+
vae_path = None
|
| 126 |
+
|
| 127 |
+
lora_path = args.lora_path
|
| 128 |
+
# pdb.set_trace()
|
| 129 |
+
# Other params
|
| 130 |
+
sample_size = [args.sample_height, args.sample_width]
|
| 131 |
+
video_length = 49
|
| 132 |
+
fps = 16
|
| 133 |
+
|
| 134 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 135 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 136 |
+
prompt_list_path = args.prompt_list_path
|
| 137 |
+
num_generated_videos = args.num_generated_videos
|
| 138 |
+
weight_dtype = torch.bfloat16
|
| 139 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 140 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 141 |
+
guidance_scale = 6.0
|
| 142 |
+
seed = args.seed
|
| 143 |
+
num_inference_steps = args.num_inference_steps
|
| 144 |
+
lora_weight = 1.0
|
| 145 |
+
|
| 146 |
+
if not transformer_path:
|
| 147 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}-lw{lora_weight}"
|
| 148 |
+
else:
|
| 149 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}"
|
| 150 |
+
|
| 151 |
+
# if use_h3ae:
|
| 152 |
+
# # pdb.set_trace()
|
| 153 |
+
# save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 154 |
+
# import pdb
|
| 155 |
+
# pdb.set_trace()
|
| 156 |
+
if seed != 42:
|
| 157 |
+
save_path= f"{save_path}-seed{seed}"
|
| 158 |
+
|
| 159 |
+
# if seed == -1:
|
| 160 |
+
# save_path= f"{save_path}-randomseed"
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if lora_path:
|
| 164 |
+
import pdb
|
| 165 |
+
# pdb.set_trace()
|
| 166 |
+
sub_path = lora_path.split('/')[-2]
|
| 167 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 168 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 169 |
+
elif transformer_path:
|
| 170 |
+
sub_path = transformer_path.split('/')[-4]
|
| 171 |
+
itr = transformer_path.split('/')[-3].split('-')[-1]
|
| 172 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 173 |
+
# pdb.set_trace()
|
| 174 |
+
else:
|
| 175 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-seed{seed}/output_pretrain'
|
| 176 |
+
|
| 177 |
+
if args.debug:
|
| 178 |
+
lora_path = None
|
| 179 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 180 |
+
|
| 181 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 182 |
+
config = OmegaConf.load(config_path)
|
| 183 |
+
|
| 184 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 185 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 186 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 187 |
+
low_cpu_mem_usage=True,
|
| 188 |
+
torch_dtype=weight_dtype,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if transformer_path is not None:
|
| 192 |
+
print(f"From checkpoint: {transformer_path}")
|
| 193 |
+
if transformer_path.endswith("safetensors"):
|
| 194 |
+
from safetensors.torch import load_file, safe_open
|
| 195 |
+
state_dict = load_file(transformer_path)
|
| 196 |
+
else:
|
| 197 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 198 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 199 |
+
# pdb.set_trace()
|
| 200 |
+
|
| 201 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 202 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 203 |
+
# pdb.set_trace()
|
| 204 |
+
|
| 205 |
+
# Get Vae
|
| 206 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 207 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 208 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 209 |
+
).to(weight_dtype)
|
| 210 |
+
|
| 211 |
+
if vae_path is not None:
|
| 212 |
+
print(f"From checkpoint: {vae_path}")
|
| 213 |
+
if vae_path.endswith("safetensors"):
|
| 214 |
+
from safetensors.torch import load_file, safe_open
|
| 215 |
+
state_dict = load_file(vae_path)
|
| 216 |
+
else:
|
| 217 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 218 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 219 |
+
|
| 220 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 221 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 222 |
+
|
| 223 |
+
# Get Tokenizer
|
| 224 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 225 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Get Text encoder
|
| 229 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 230 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 231 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 232 |
+
low_cpu_mem_usage=True,
|
| 233 |
+
torch_dtype=weight_dtype,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Get Scheduler
|
| 237 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 238 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 239 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 240 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 241 |
+
}[sampler_name]
|
| 242 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 243 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 244 |
+
scheduler = Chosen_Scheduler(
|
| 245 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# Get Pipeline
|
| 249 |
+
pipeline = WanPipeline(
|
| 250 |
+
transformer=transformer,
|
| 251 |
+
vae=vae,
|
| 252 |
+
tokenizer=tokenizer,
|
| 253 |
+
text_encoder=text_encoder,
|
| 254 |
+
scheduler=scheduler,
|
| 255 |
+
)
|
| 256 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 257 |
+
from functools import partial
|
| 258 |
+
transformer.enable_multi_gpus_inference()
|
| 259 |
+
if fsdp_dit:
|
| 260 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 261 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 262 |
+
print("Add FSDP DIT")
|
| 263 |
+
if fsdp_text_encoder:
|
| 264 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 265 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 266 |
+
print("Add FSDP TEXT ENCODER")
|
| 267 |
+
|
| 268 |
+
if compile_dit:
|
| 269 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 270 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 271 |
+
print("Add Compile")
|
| 272 |
+
|
| 273 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 274 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 275 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 276 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 277 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 278 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 279 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 280 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 281 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 282 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 283 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 284 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 285 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 286 |
+
pipeline.to(device=device)
|
| 287 |
+
else:
|
| 288 |
+
pipeline.to(device=device)
|
| 289 |
+
|
| 290 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 291 |
+
if coefficients is not None:
|
| 292 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 293 |
+
pipeline.transformer.enable_teacache(
|
| 294 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
if cfg_skip_ratio is not None:
|
| 298 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 299 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 303 |
+
if seed == -1:
|
| 304 |
+
generator = None
|
| 305 |
+
|
| 306 |
+
prompt_list = []
|
| 307 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 308 |
+
for line in file:
|
| 309 |
+
# 去除行末的换行符
|
| 310 |
+
prompt_list.append(line.strip())
|
| 311 |
+
|
| 312 |
+
if lora_path is not None:
|
| 313 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 314 |
+
|
| 315 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 316 |
+
if num_generated_videos == -1:
|
| 317 |
+
num_generated_videos = len(prompt_list)
|
| 318 |
+
|
| 319 |
+
# for prompt in prompt_list[:num_generated_videos]:
|
| 320 |
+
for i in range(len(prompt_list[:num_generated_videos])):
|
| 321 |
+
prompt = prompt_list[:num_generated_videos][i]
|
| 322 |
+
prefix = str(i+1).zfill(8)
|
| 323 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 324 |
+
if os.path.exists(video_path):
|
| 325 |
+
continue
|
| 326 |
+
|
| 327 |
+
with torch.no_grad():
|
| 328 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 329 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 330 |
+
|
| 331 |
+
if enable_riflex:
|
| 332 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 333 |
+
|
| 334 |
+
sample = pipeline(
|
| 335 |
+
prompt,
|
| 336 |
+
num_frames = video_length,
|
| 337 |
+
negative_prompt = negative_prompt,
|
| 338 |
+
height = sample_size[0],
|
| 339 |
+
width = sample_size[1],
|
| 340 |
+
generator = generator,
|
| 341 |
+
guidance_scale = guidance_scale,
|
| 342 |
+
num_inference_steps = num_inference_steps,
|
| 343 |
+
shift = shift,
|
| 344 |
+
).videos
|
| 345 |
+
|
| 346 |
+
# if lora_path is not None:
|
| 347 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 348 |
+
|
| 349 |
+
def save_results():
|
| 350 |
+
if not os.path.exists(save_path):
|
| 351 |
+
os.makedirs(save_path, exist_ok=True)
|
| 352 |
+
|
| 353 |
+
# index = len([path for path in os.listdir(save_path)]) + 1
|
| 354 |
+
# prefix = str(index).zfill(8)
|
| 355 |
+
if video_length == 1:
|
| 356 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 357 |
+
|
| 358 |
+
image = sample[0, :, 0]
|
| 359 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 360 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 361 |
+
image = Image.fromarray(image)
|
| 362 |
+
image.save(video_path)
|
| 363 |
+
else:
|
| 364 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 365 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 366 |
+
|
| 367 |
+
if ulysses_degree * ring_degree > 1:
|
| 368 |
+
import torch.distributed as dist
|
| 369 |
+
if dist.get_rank() == 0:
|
| 370 |
+
save_results()
|
| 371 |
+
else:
|
| 372 |
+
save_results()
|
| 373 |
+
|
| 374 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_val4.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
|
| 32 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 35 |
+
|
| 36 |
+
parser.add_argument("--save_folder", type=str, default='samples4', help="prompt file for inference")
|
| 37 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--sample_height", type=list, default=512, help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--sample_width", type=list, default=288, help="prompt file for inference")
|
| 41 |
+
|
| 42 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 43 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 44 |
+
# parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 45 |
+
parser.add_argument("--ulysses_degree", type=int, default=1, help="prompt file for inference")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 49 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 50 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 51 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 55 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 56 |
+
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 59 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 60 |
+
#
|
| 61 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 62 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 63 |
+
#
|
| 64 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 65 |
+
#
|
| 66 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 67 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 68 |
+
#
|
| 69 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 70 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 71 |
+
|
| 72 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 73 |
+
# Multi GPUs config
|
| 74 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 75 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 76 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 77 |
+
ulysses_degree = args.ulysses_degree
|
| 78 |
+
ring_degree = 1
|
| 79 |
+
|
| 80 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 81 |
+
fsdp_dit = False
|
| 82 |
+
fsdp_text_encoder = True
|
| 83 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 84 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 85 |
+
compile_dit = False
|
| 86 |
+
|
| 87 |
+
# TeaCache config
|
| 88 |
+
enable_teacache = args.enable_teacache
|
| 89 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 90 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 91 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 92 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 93 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 94 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 95 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 96 |
+
teacache_threshold = 0.10
|
| 97 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 98 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 99 |
+
num_skip_start_steps = 5
|
| 100 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 101 |
+
teacache_offload = False
|
| 102 |
+
|
| 103 |
+
# Skip some cfg steps in inference
|
| 104 |
+
# Recommended to be set between 0.00 and 0.25
|
| 105 |
+
cfg_skip_ratio = 0
|
| 106 |
+
|
| 107 |
+
# Riflex config
|
| 108 |
+
enable_riflex = False
|
| 109 |
+
# Index of intrinsic frequency
|
| 110 |
+
riflex_k = 6
|
| 111 |
+
|
| 112 |
+
# Config and model path
|
| 113 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 114 |
+
# model path
|
| 115 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 116 |
+
|
| 117 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 118 |
+
sampler_name = args.sampler_name
|
| 119 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 120 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 121 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 122 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 123 |
+
shift = args.shift
|
| 124 |
+
|
| 125 |
+
# Load pretrained model if need
|
| 126 |
+
transformer_path = args.transformer_path
|
| 127 |
+
vae_path = None
|
| 128 |
+
|
| 129 |
+
lora_path = args.lora_path
|
| 130 |
+
# pdb.set_trace()
|
| 131 |
+
# Other params
|
| 132 |
+
sample_size = [args.sample_height, args.sample_width]
|
| 133 |
+
video_length = 49
|
| 134 |
+
fps = 16
|
| 135 |
+
|
| 136 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 137 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 138 |
+
prompt_list_path = args.prompt_list_path
|
| 139 |
+
num_generated_videos = args.num_generated_videos
|
| 140 |
+
weight_dtype = torch.bfloat16
|
| 141 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 142 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 143 |
+
guidance_scale = 6.0
|
| 144 |
+
seed = args.seed
|
| 145 |
+
num_inference_steps = args.num_inference_steps
|
| 146 |
+
lora_weight = 1.0
|
| 147 |
+
|
| 148 |
+
if not transformer_path:
|
| 149 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}-lw{lora_weight}"
|
| 150 |
+
else:
|
| 151 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}"
|
| 152 |
+
|
| 153 |
+
# if use_h3ae:
|
| 154 |
+
# # pdb.set_trace()
|
| 155 |
+
# save_path= f"{args.save_folder}/h3ae/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-lw{lora_weight}"
|
| 156 |
+
# import pdb
|
| 157 |
+
# pdb.set_trace()
|
| 158 |
+
if seed != 42:
|
| 159 |
+
save_path= f"{save_path}-seed{seed}"
|
| 160 |
+
|
| 161 |
+
# if seed == -1:
|
| 162 |
+
# save_path= f"{save_path}-randomseed"
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if lora_path:
|
| 166 |
+
import pdb
|
| 167 |
+
# pdb.set_trace()
|
| 168 |
+
sub_path = lora_path.split('/')[-2]
|
| 169 |
+
itr = lora_path.split('/')[-1].split('-')[-1].split('.')[0]
|
| 170 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 171 |
+
elif transformer_path:
|
| 172 |
+
sub_path = transformer_path.split('/')[-4]
|
| 173 |
+
itr = transformer_path.split('/')[-3].split('-')[-1]
|
| 174 |
+
save_path = f'{save_path}/{sub_path}/steps_{itr}'
|
| 175 |
+
# pdb.set_trace()
|
| 176 |
+
else:
|
| 177 |
+
save_path = f'{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}-{num_inference_steps}-seed{seed}/output_pretrain'
|
| 178 |
+
|
| 179 |
+
if args.debug:
|
| 180 |
+
lora_path = None
|
| 181 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-{sample_size[0]}*{sample_size[1]}/output_debug1"
|
| 182 |
+
|
| 183 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 184 |
+
config = OmegaConf.load(config_path)
|
| 185 |
+
|
| 186 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 187 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 188 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 189 |
+
low_cpu_mem_usage=True,
|
| 190 |
+
torch_dtype=weight_dtype,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
if transformer_path is not None:
|
| 194 |
+
print(f"From checkpoint: {transformer_path}")
|
| 195 |
+
if transformer_path.endswith("safetensors"):
|
| 196 |
+
from safetensors.torch import load_file, safe_open
|
| 197 |
+
state_dict = load_file(transformer_path)
|
| 198 |
+
else:
|
| 199 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 200 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 201 |
+
# pdb.set_trace()
|
| 202 |
+
|
| 203 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 204 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 205 |
+
# pdb.set_trace()
|
| 206 |
+
|
| 207 |
+
# Get Vae
|
| 208 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 209 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 210 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 211 |
+
).to(weight_dtype)
|
| 212 |
+
|
| 213 |
+
if vae_path is not None:
|
| 214 |
+
print(f"From checkpoint: {vae_path}")
|
| 215 |
+
if vae_path.endswith("safetensors"):
|
| 216 |
+
from safetensors.torch import load_file, safe_open
|
| 217 |
+
state_dict = load_file(vae_path)
|
| 218 |
+
else:
|
| 219 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 220 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 221 |
+
|
| 222 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 223 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 224 |
+
|
| 225 |
+
if args.use_h3ae:
|
| 226 |
+
h3ae = H3AE.from_pretrained("/nfs/hub/h3ae/h3ae_wan_ch64_41616_channel").to(weight_dtype).to(device)
|
| 227 |
+
|
| 228 |
+
# Get Tokenizer
|
| 229 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 230 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# Get Text encoder
|
| 234 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 235 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 236 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 237 |
+
low_cpu_mem_usage=True,
|
| 238 |
+
torch_dtype=weight_dtype,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
# Get Scheduler
|
| 242 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 243 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 244 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 245 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 246 |
+
}[sampler_name]
|
| 247 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 248 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 249 |
+
scheduler = Chosen_Scheduler(
|
| 250 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Get Pipeline
|
| 254 |
+
pipeline = WanPipeline(
|
| 255 |
+
transformer=transformer,
|
| 256 |
+
vae=vae,
|
| 257 |
+
tokenizer=tokenizer,
|
| 258 |
+
text_encoder=text_encoder,
|
| 259 |
+
scheduler=scheduler,
|
| 260 |
+
)
|
| 261 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 262 |
+
from functools import partial
|
| 263 |
+
transformer.enable_multi_gpus_inference()
|
| 264 |
+
if fsdp_dit:
|
| 265 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 266 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 267 |
+
print("Add FSDP DIT")
|
| 268 |
+
if fsdp_text_encoder:
|
| 269 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 270 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 271 |
+
print("Add FSDP TEXT ENCODER")
|
| 272 |
+
|
| 273 |
+
if compile_dit:
|
| 274 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 275 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 276 |
+
print("Add Compile")
|
| 277 |
+
|
| 278 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 279 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 280 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 281 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 282 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 283 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 284 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 285 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 286 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 287 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 288 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 289 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 290 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 291 |
+
pipeline.to(device=device)
|
| 292 |
+
else:
|
| 293 |
+
pipeline.to(device=device)
|
| 294 |
+
|
| 295 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 296 |
+
if coefficients is not None:
|
| 297 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 298 |
+
pipeline.transformer.enable_teacache(
|
| 299 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
if cfg_skip_ratio is not None:
|
| 303 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 304 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 308 |
+
if seed == -1:
|
| 309 |
+
generator = None
|
| 310 |
+
|
| 311 |
+
prompt_list = []
|
| 312 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 313 |
+
for line in file:
|
| 314 |
+
# 去除行末的换行符
|
| 315 |
+
prompt_list.append(line.strip())
|
| 316 |
+
|
| 317 |
+
if lora_path is not None:
|
| 318 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 319 |
+
|
| 320 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 321 |
+
if num_generated_videos == -1:
|
| 322 |
+
num_generated_videos = len(prompt_list)
|
| 323 |
+
|
| 324 |
+
# for prompt in prompt_list[:num_generated_videos]:
|
| 325 |
+
for i in range(len(prompt_list[:num_generated_videos])):
|
| 326 |
+
prompt = prompt_list[:num_generated_videos][i]
|
| 327 |
+
prefix = str(i+1).zfill(8)
|
| 328 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 329 |
+
if os.path.exists(video_path):
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
with torch.no_grad():
|
| 333 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 334 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 335 |
+
|
| 336 |
+
if enable_riflex:
|
| 337 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 338 |
+
|
| 339 |
+
if args.use_h3ae:
|
| 340 |
+
|
| 341 |
+
from diffusers.video_processor import VideoProcessor
|
| 342 |
+
video_processor = VideoProcessor(vae_scale_factor=vae.spatial_compression_ratio)
|
| 343 |
+
|
| 344 |
+
latents = pipeline(
|
| 345 |
+
prompt,
|
| 346 |
+
num_frames = video_length,
|
| 347 |
+
negative_prompt = negative_prompt,
|
| 348 |
+
height = sample_size[0],
|
| 349 |
+
width = sample_size[1],
|
| 350 |
+
generator = generator,
|
| 351 |
+
guidance_scale = guidance_scale,
|
| 352 |
+
num_inference_steps = num_inference_steps,
|
| 353 |
+
shift = shift,
|
| 354 |
+
output_type = 'latent',
|
| 355 |
+
return_dict = True
|
| 356 |
+
).videos
|
| 357 |
+
|
| 358 |
+
latents = torch.nn.functional.pixel_unshuffle(latents.transpose(1, 2), 2).transpose(1, 2)
|
| 359 |
+
# sample = sample.clamp(-1,1)
|
| 360 |
+
# pdb.set_trace()
|
| 361 |
+
sample = h3ae.decode(latents)[0]
|
| 362 |
+
|
| 363 |
+
sample = (sample / 2 + 0.5).clamp(0, 1).cpu().float()#.numpy()
|
| 364 |
+
# sample = video_processor.postprocess_video(video=sample, output_type='numpy')
|
| 365 |
+
else:
|
| 366 |
+
sample = pipeline(
|
| 367 |
+
prompt,
|
| 368 |
+
num_frames = video_length,
|
| 369 |
+
negative_prompt = negative_prompt,
|
| 370 |
+
height = sample_size[0],
|
| 371 |
+
width = sample_size[1],
|
| 372 |
+
generator = generator,
|
| 373 |
+
guidance_scale = guidance_scale,
|
| 374 |
+
num_inference_steps = num_inference_steps,
|
| 375 |
+
shift = shift,
|
| 376 |
+
).videos
|
| 377 |
+
|
| 378 |
+
# if lora_path is not None:
|
| 379 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 380 |
+
|
| 381 |
+
def save_results():
|
| 382 |
+
if not os.path.exists(save_path):
|
| 383 |
+
os.makedirs(save_path, exist_ok=True)
|
| 384 |
+
|
| 385 |
+
# index = len([path for path in os.listdir(save_path)]) + 1
|
| 386 |
+
# prefix = str(index).zfill(8)
|
| 387 |
+
if video_length == 1:
|
| 388 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 389 |
+
|
| 390 |
+
image = sample[0, :, 0]
|
| 391 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 392 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 393 |
+
image = Image.fromarray(image)
|
| 394 |
+
image.save(video_path)
|
| 395 |
+
else:
|
| 396 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 397 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 398 |
+
|
| 399 |
+
if ulysses_degree * ring_degree > 1:
|
| 400 |
+
import torch.distributed as dist
|
| 401 |
+
if dist.get_rank() == 0:
|
| 402 |
+
save_results()
|
| 403 |
+
else:
|
| 404 |
+
save_results()
|
| 405 |
+
|
| 406 |
+
|
VideoX-Fun/examples/wan2.1/predict_t2v_val_sd.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pdb
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 18 |
+
WanTransformer3DModel, H3AE)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
|
| 32 |
+
parser.add_argument("--lora_path", type=str, default=None, help="prompt file for inference")
|
| 33 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="prompt file for inference")
|
| 34 |
+
parser.add_argument("--prompt_list_path", type=str, default='/nfs/ywang29/Reward_finetuning/VideoX-Fun/MovieGenVideoBench_val.txt', help="prompt file for inference")
|
| 35 |
+
|
| 36 |
+
parser.add_argument("--save_folder", type=str, default='samples_sd', help="prompt file for inference")
|
| 37 |
+
parser.add_argument("--sampler_name", type=str, default='Flow', help="Flow, Flow_Unipc, Flow_DPM++")
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--sample_height", type=list, default=512, help="prompt file for inference")
|
| 40 |
+
parser.add_argument("--sample_width", type=list, default=288, help="prompt file for inference")
|
| 41 |
+
|
| 42 |
+
parser.add_argument("--seed", type=int, default=42, help="prompt file for inference")
|
| 43 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="prompt file for inference")
|
| 44 |
+
# parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 45 |
+
|
| 46 |
+
parser.add_argument("--use_h3ae", type=bool, default=False, help="prompt file for inference")
|
| 47 |
+
parser.add_argument("--debug", type=bool, default=False, help="prompt file for inference")
|
| 48 |
+
parser.add_argument("--num_inference_steps", type=int, default=30, help="prompt file for inference")
|
| 49 |
+
parser.add_argument("--num_generated_videos", type=int, default=100, help="prompt file for inference")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
parser.add_argument("--enable_teacache", type=bool, default=True, help="prompt file for inference")
|
| 53 |
+
parser.add_argument("--shift", type=int, default=3, help="prompt file for inference")
|
| 54 |
+
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 57 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 58 |
+
#
|
| 59 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 60 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 61 |
+
#
|
| 62 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 63 |
+
#
|
| 64 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 65 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 66 |
+
#
|
| 67 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 68 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 69 |
+
|
| 70 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 71 |
+
# Multi GPUs config
|
| 72 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 73 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 74 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 75 |
+
ulysses_degree = 1
|
| 76 |
+
ring_degree = 1
|
| 77 |
+
|
| 78 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 79 |
+
fsdp_dit = False
|
| 80 |
+
fsdp_text_encoder = True
|
| 81 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 82 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 83 |
+
compile_dit = False
|
| 84 |
+
|
| 85 |
+
# TeaCache config
|
| 86 |
+
enable_teacache = False
|
| 87 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 88 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 89 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 90 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 91 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 92 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 93 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 94 |
+
teacache_threshold = 0.10
|
| 95 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 96 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 97 |
+
num_skip_start_steps = 5
|
| 98 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 99 |
+
teacache_offload = False
|
| 100 |
+
|
| 101 |
+
# Skip some cfg steps in inference
|
| 102 |
+
# Recommended to be set between 0.00 and 0.25
|
| 103 |
+
cfg_skip_ratio = 0
|
| 104 |
+
|
| 105 |
+
# Riflex config
|
| 106 |
+
enable_riflex = False
|
| 107 |
+
# Index of intrinsic frequency
|
| 108 |
+
riflex_k = 6
|
| 109 |
+
|
| 110 |
+
# Config and model path
|
| 111 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 112 |
+
# model path
|
| 113 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-T2V-1.3B"
|
| 114 |
+
|
| 115 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 116 |
+
sampler_name = args.sampler_name
|
| 117 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 118 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 119 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 120 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 121 |
+
shift = 5
|
| 122 |
+
|
| 123 |
+
# Load pretrained model if need
|
| 124 |
+
# transformer_path = '/nfs/ywu6/Efficient-DiT/outputs/09-18-wan-distill-4-step-14b-288p/checkpoints/generator/diffusion_pytorch_model.safetensors'
|
| 125 |
+
# transformer_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_sd/checkpoint-1000/transformer/diffusion_pytorch_model.safetensors'
|
| 126 |
+
transformer_path = args.transformer_path
|
| 127 |
+
vae_path = None
|
| 128 |
+
|
| 129 |
+
lora_path = None
|
| 130 |
+
# pdb.set_trace()
|
| 131 |
+
# Other params
|
| 132 |
+
sample_size = [args.sample_height, args.sample_width]
|
| 133 |
+
video_length = 49
|
| 134 |
+
fps = 16
|
| 135 |
+
|
| 136 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 137 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 138 |
+
prompt_list_path = args.prompt_list_path
|
| 139 |
+
num_generated_videos = args.num_generated_videos
|
| 140 |
+
weight_dtype = torch.bfloat16
|
| 141 |
+
# prompt = "The car is positioned in the center of the road, moving forward. The surrounding scenery, including fields, hills, and the sky, serves as a backdrop on either side and in the distance."
|
| 142 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 143 |
+
guidance_scale = 1.0
|
| 144 |
+
seed = args.seed
|
| 145 |
+
num_inference_steps = 4
|
| 146 |
+
lora_weight = 1.0
|
| 147 |
+
|
| 148 |
+
if args.transformer_path is not None:
|
| 149 |
+
sub_name = args.transformer_path.split('/')[-3]
|
| 150 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}/{sub_name}"
|
| 151 |
+
else:
|
| 152 |
+
transformer_path = '/nfs/ywu6/Efficient-DiT/outputs/09-18-wan-distill-4-step-14b-288p/checkpoints/generator/diffusion_pytorch_model.safetensors'
|
| 153 |
+
save_path = f"{args.save_folder}/wan-videos-t2v-512*288-{num_inference_steps}/pretrain_sd"
|
| 154 |
+
|
| 155 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 156 |
+
config = OmegaConf.load(config_path)
|
| 157 |
+
|
| 158 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 159 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 160 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 161 |
+
low_cpu_mem_usage=True,
|
| 162 |
+
torch_dtype=weight_dtype,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
if transformer_path is not None:
|
| 166 |
+
print(f"From checkpoint: {transformer_path}")
|
| 167 |
+
if transformer_path.endswith("safetensors"):
|
| 168 |
+
from safetensors.torch import load_file, safe_open
|
| 169 |
+
state_dict = load_file(transformer_path)
|
| 170 |
+
else:
|
| 171 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 172 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 173 |
+
# pdb.set_trace()
|
| 174 |
+
OLD_PREFIX_TRANSFORMER = 'transformer_blocks.'
|
| 175 |
+
NEW_PREFIX_BLOCKS = 'blocks.'
|
| 176 |
+
|
| 177 |
+
new_state_dict={}
|
| 178 |
+
|
| 179 |
+
for old_key, value in state_dict.items():
|
| 180 |
+
new_key = old_key
|
| 181 |
+
|
| 182 |
+
# 1. 处理主要的命名不一致:'transformer_blocks' -> 'blocks'
|
| 183 |
+
if new_key.startswith(OLD_PREFIX_TRANSFORMER):
|
| 184 |
+
new_key = new_key.replace(OLD_PREFIX_TRANSFORMER, NEW_PREFIX_BLOCKS)
|
| 185 |
+
|
| 186 |
+
# 2. (可选) 处理模型包装层的前缀,例如 'model.blocks...' -> 'blocks...'
|
| 187 |
+
# 如果您的目标模型直接是 Transformer,可能不需要这一步。
|
| 188 |
+
# if new_key.startswith('model.'):
|
| 189 |
+
# new_key = new_key[len('model.'):]
|
| 190 |
+
|
| 191 |
+
new_state_dict[new_key] = value
|
| 192 |
+
|
| 193 |
+
m, u = transformer.load_state_dict(new_state_dict, strict=False)
|
| 194 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 195 |
+
# pdb.set_trace()
|
| 196 |
+
|
| 197 |
+
# Get Vae
|
| 198 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 199 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 200 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 201 |
+
).to(weight_dtype)
|
| 202 |
+
|
| 203 |
+
if vae_path is not None:
|
| 204 |
+
print(f"From checkpoint: {vae_path}")
|
| 205 |
+
if vae_path.endswith("safetensors"):
|
| 206 |
+
from safetensors.torch import load_file, safe_open
|
| 207 |
+
state_dict = load_file(vae_path)
|
| 208 |
+
else:
|
| 209 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 210 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 211 |
+
|
| 212 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 213 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 214 |
+
|
| 215 |
+
# Get Tokenizer
|
| 216 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 217 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# Get Text encoder
|
| 221 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 222 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 223 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 224 |
+
low_cpu_mem_usage=True,
|
| 225 |
+
torch_dtype=weight_dtype,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Get Scheduler
|
| 229 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 230 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 231 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 232 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 233 |
+
}[sampler_name]
|
| 234 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 235 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 236 |
+
scheduler = Chosen_Scheduler(
|
| 237 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
# Get Pipeline
|
| 241 |
+
pipeline = WanPipeline(
|
| 242 |
+
transformer=transformer,
|
| 243 |
+
vae=vae,
|
| 244 |
+
tokenizer=tokenizer,
|
| 245 |
+
text_encoder=text_encoder,
|
| 246 |
+
scheduler=scheduler,
|
| 247 |
+
)
|
| 248 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 249 |
+
from functools import partial
|
| 250 |
+
transformer.enable_multi_gpus_inference()
|
| 251 |
+
if fsdp_dit:
|
| 252 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 253 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 254 |
+
print("Add FSDP DIT")
|
| 255 |
+
if fsdp_text_encoder:
|
| 256 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 257 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 258 |
+
print("Add FSDP TEXT ENCODER")
|
| 259 |
+
|
| 260 |
+
if compile_dit:
|
| 261 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 262 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 263 |
+
print("Add Compile")
|
| 264 |
+
|
| 265 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 266 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 267 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 268 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 269 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 270 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 271 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 272 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 273 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 274 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 275 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 276 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 277 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 278 |
+
pipeline.to(device=device)
|
| 279 |
+
else:
|
| 280 |
+
pipeline.to(device=device)
|
| 281 |
+
|
| 282 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 283 |
+
if coefficients is not None:
|
| 284 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 285 |
+
pipeline.transformer.enable_teacache(
|
| 286 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if cfg_skip_ratio is not None:
|
| 290 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 291 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if seed == -1:
|
| 295 |
+
generator = None
|
| 296 |
+
else:
|
| 297 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
prompt_list = []
|
| 301 |
+
with open(prompt_list_path, 'r', encoding='utf-8') as file:
|
| 302 |
+
for line in file:
|
| 303 |
+
# 去除行末的换行符
|
| 304 |
+
prompt_list.append(line.strip())
|
| 305 |
+
|
| 306 |
+
if lora_path is not None:
|
| 307 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 308 |
+
|
| 309 |
+
#def generate(video_length, negative_prompt, sample_size, generator, guidance_scale, num_inference_steps, shift, save_path, ulysses_degree, ring_degree):
|
| 310 |
+
if num_generated_videos == -1:
|
| 311 |
+
num_generated_videos = len(prompt_list)
|
| 312 |
+
|
| 313 |
+
# for prompt in prompt_list[:num_generated_videos]:
|
| 314 |
+
for i in range(len(prompt_list[:num_generated_videos])):
|
| 315 |
+
prompt = prompt_list[:num_generated_videos][i]
|
| 316 |
+
prefix = str(i+1).zfill(8)
|
| 317 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 318 |
+
if os.path.exists(video_path):
|
| 319 |
+
continue
|
| 320 |
+
|
| 321 |
+
with torch.no_grad():
|
| 322 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 323 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 324 |
+
|
| 325 |
+
if enable_riflex:
|
| 326 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 327 |
+
|
| 328 |
+
sample = pipeline(
|
| 329 |
+
prompt,
|
| 330 |
+
num_frames = video_length,
|
| 331 |
+
negative_prompt = negative_prompt,
|
| 332 |
+
height = sample_size[0],
|
| 333 |
+
width = sample_size[1],
|
| 334 |
+
generator = generator,
|
| 335 |
+
guidance_scale = guidance_scale,
|
| 336 |
+
num_inference_steps = num_inference_steps,
|
| 337 |
+
shift = shift,
|
| 338 |
+
).videos
|
| 339 |
+
|
| 340 |
+
# if lora_path is not None:
|
| 341 |
+
# pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 342 |
+
|
| 343 |
+
def save_results():
|
| 344 |
+
if not os.path.exists(save_path):
|
| 345 |
+
os.makedirs(save_path, exist_ok=True)
|
| 346 |
+
|
| 347 |
+
# index = len([path for path in os.listdir(save_path)]) + 1
|
| 348 |
+
# prefix = str(index).zfill(8)
|
| 349 |
+
if video_length == 1:
|
| 350 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 351 |
+
|
| 352 |
+
image = sample[0, :, 0]
|
| 353 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 354 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 355 |
+
image = Image.fromarray(image)
|
| 356 |
+
image.save(video_path)
|
| 357 |
+
else:
|
| 358 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 359 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 360 |
+
|
| 361 |
+
if ulysses_degree * ring_degree > 1:
|
| 362 |
+
import torch.distributed as dist
|
| 363 |
+
if dist.get_rank() == 0:
|
| 364 |
+
save_results()
|
| 365 |
+
else:
|
| 366 |
+
save_results()
|
| 367 |
+
|
| 368 |
+
|
VideoX-Fun/examples/wan2.1_fun/app.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.api.api import (infer_forward_api,
|
| 13 |
+
update_diffusion_transformer_api)
|
| 14 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 15 |
+
from videox_fun.ui.wan_fun_ui import ui, ui_client, ui_host
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
# Choose the ui mode
|
| 19 |
+
# "normal" refers to the standard UI, which allows users to click to switch models, change model types, and more.
|
| 20 |
+
# "host" represents the hosting mode, where the model is loaded directly at startup and can be accessed via
|
| 21 |
+
# the API to return generation results.
|
| 22 |
+
# "client" represents the client mode, offering a simple UI that sends requests to a remote API for generation.
|
| 23 |
+
ui_mode = "normal"
|
| 24 |
+
|
| 25 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 26 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
#
|
| 28 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 31 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 32 |
+
#
|
| 33 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 34 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 35 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 36 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 37 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 38 |
+
compile_dit = False
|
| 39 |
+
|
| 40 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 41 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 42 |
+
weight_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# Server ip
|
| 45 |
+
server_name = "0.0.0.0"
|
| 46 |
+
server_port = 7860
|
| 47 |
+
|
| 48 |
+
# Config path
|
| 49 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 50 |
+
# Params below is used when ui_mode = "host"
|
| 51 |
+
# Model path of the pretrained model
|
| 52 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-InP"
|
| 53 |
+
# "Inpaint" or "Control"
|
| 54 |
+
model_type = "Inpaint"
|
| 55 |
+
|
| 56 |
+
if ui_mode == "host":
|
| 57 |
+
demo, controller = ui_host(GPU_memory_mode, flow_scheduler_dict, model_name, model_type, config_path, compile_dit, weight_dtype)
|
| 58 |
+
elif ui_mode == "client":
|
| 59 |
+
demo, controller = ui_client(flow_scheduler_dict, model_name)
|
| 60 |
+
else:
|
| 61 |
+
demo, controller = ui(GPU_memory_mode, flow_scheduler_dict, config_path, compile_dit, weight_dtype)
|
| 62 |
+
|
| 63 |
+
def gr_launch():
|
| 64 |
+
# launch gradio
|
| 65 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 66 |
+
server_name=server_name,
|
| 67 |
+
server_port=server_port,
|
| 68 |
+
prevent_thread_lock=True
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# launch api
|
| 72 |
+
infer_forward_api(None, app, controller)
|
| 73 |
+
update_diffusion_transformer_api(None, app, controller)
|
| 74 |
+
|
| 75 |
+
gr_launch()
|
| 76 |
+
|
| 77 |
+
# not close the python
|
| 78 |
+
while True:
|
| 79 |
+
time.sleep(5)
|
VideoX-Fun/examples/wan2.1_fun/launch_api.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import ray
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.api.api_multi_nodes import (MultiNodesEngine,
|
| 16 |
+
multi_nodes_infer_forward_api)
|
| 17 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 18 |
+
from videox_fun.ui.wan_fun_ui import Wan_Fun_Controller
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description='xDiT HTTP Service')
|
| 22 |
+
parser.add_argument('--world_size', type=int, default=8, help='Number of parallel workers')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--gpu_memory_mode', type=str, default="model_full_load", help='''
|
| 25 |
+
GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8].
|
| 26 |
+
model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
|
| 28 |
+
model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 29 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 30 |
+
|
| 31 |
+
model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 32 |
+
|
| 33 |
+
model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 34 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
'''
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument('--ulysses_degree', type=int, default=4, help='Degree of Ulysses configuration')
|
| 38 |
+
parser.add_argument('--ring_degree', type=int, default=2, help='Degree of Ring configuration')
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
'--compile_dit', action='store_true', help='''
|
| 41 |
+
Enable compile dit.
|
| 42 |
+
Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 43 |
+
The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 44 |
+
'''
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument('--fsdp_dit', action='store_true', help="Use DIT FSDP to save more GPU memory in multi gpus.")
|
| 47 |
+
parser.add_argument('--fsdp_text_encoder', action='store_true', help="Use Text Encoder FSDP to save more GPU memory in multi gpus.")
|
| 48 |
+
parser.add_argument('--weight_dtype', type=str, default='bf16', help='Weight data type')
|
| 49 |
+
parser.add_argument('--server_name', type=str, default="0.0.0.0", help='Server IP address')
|
| 50 |
+
parser.add_argument('--server_port', type=int, default=7860, help='Server Port')
|
| 51 |
+
parser.add_argument('--config_path', type=str, default="config/wan2.1/wan_civitai.yaml", help='Path to config file')
|
| 52 |
+
parser.add_argument('--model_name', type=str, default="models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-InP", help='Model path')
|
| 53 |
+
parser.add_argument('--model_type', type=str, default="Inpaint", help='Model type (Inpaint/Control)')
|
| 54 |
+
parser.add_argument('--savedir_sample', type=str, default=None, help='The save directory for samples')
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
weight_dtype = torch.float32
|
| 58 |
+
if args.weight_dtype == "bf16":
|
| 59 |
+
weight_dtype = torch.bfloat16
|
| 60 |
+
elif args.weight_dtype == "fp16":
|
| 61 |
+
weight_dtype = torch.float16
|
| 62 |
+
|
| 63 |
+
engine = MultiNodesEngine(
|
| 64 |
+
world_size=args.world_size, Controller=Wan_Fun_Controller,
|
| 65 |
+
GPU_memory_mode=args.gpu_memory_mode, scheduler_dict=flow_scheduler_dict, model_name=args.model_name, model_type=args.model_type, config_path=args.config_path,
|
| 66 |
+
ulysses_degree=args.ulysses_degree, ring_degree=args.ring_degree,
|
| 67 |
+
fsdp_dit=args.fsdp_dit, fsdp_text_encoder=args.fsdp_text_encoder, compile_dit=args.compile_dit,
|
| 68 |
+
weight_dtype=weight_dtype, savedir_sample=args.savedir_sample,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def gr_launch():
|
| 72 |
+
# launch gradio
|
| 73 |
+
with gr.Blocks() as demo:
|
| 74 |
+
gr.Markdown("")
|
| 75 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 76 |
+
server_name=args.server_name,
|
| 77 |
+
server_port=args.server_port,
|
| 78 |
+
prevent_thread_lock=True
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# launch api
|
| 82 |
+
multi_nodes_infer_forward_api(None, app, engine)
|
| 83 |
+
|
| 84 |
+
gr_launch()
|
| 85 |
+
|
| 86 |
+
# not close the python
|
| 87 |
+
while True:
|
| 88 |
+
time.sleep(5)
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|
VideoX-Fun/examples/wan2.1_fun/post_infer.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
import base64
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_diffusion_transformer(diffusion_transformer_path, url='http://127.0.0.1:7860'):
|
| 11 |
+
datas = json.dumps({
|
| 12 |
+
"diffusion_transformer_path": diffusion_transformer_path
|
| 13 |
+
})
|
| 14 |
+
r = requests.post(f'{url}/videox_fun/update_diffusion_transformer', data=datas, timeout=1500)
|
| 15 |
+
data = r.content.decode('utf-8')
|
| 16 |
+
return data
|
| 17 |
+
|
| 18 |
+
def post_update_edition(edition, url='http://0.0.0.0:7860'):
|
| 19 |
+
datas = json.dumps({
|
| 20 |
+
"edition": edition
|
| 21 |
+
})
|
| 22 |
+
r = requests.post(f'{url}/videox_fun/update_edition', data=datas, timeout=1500)
|
| 23 |
+
data = r.content.decode('utf-8')
|
| 24 |
+
return data
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def post_infer(
|
| 28 |
+
generation_method,
|
| 29 |
+
length_slider,
|
| 30 |
+
url='http://127.0.0.1:7860',
|
| 31 |
+
POST_TOKEN="",
|
| 32 |
+
timeout=5000,
|
| 33 |
+
base_model_path="none",
|
| 34 |
+
lora_model_path="none",
|
| 35 |
+
lora_alpha_slider=0.55,
|
| 36 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 37 |
+
negative_prompt_textbox="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion.",
|
| 38 |
+
sampler_dropdown="Flow",
|
| 39 |
+
sample_step_slider=50,
|
| 40 |
+
width_slider=672,
|
| 41 |
+
height_slider=384,
|
| 42 |
+
cfg_scale_slider=6,
|
| 43 |
+
seed_textbox=43
|
| 44 |
+
):
|
| 45 |
+
# Prepare the data payload
|
| 46 |
+
datas = json.dumps({
|
| 47 |
+
"base_model_path": base_model_path,
|
| 48 |
+
"lora_model_path": lora_model_path,
|
| 49 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 50 |
+
"prompt_textbox": prompt_textbox,
|
| 51 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 52 |
+
"sampler_dropdown": sampler_dropdown,
|
| 53 |
+
"sample_step_slider": sample_step_slider,
|
| 54 |
+
"width_slider": width_slider,
|
| 55 |
+
"height_slider": height_slider,
|
| 56 |
+
"generation_method": generation_method,
|
| 57 |
+
"length_slider": length_slider,
|
| 58 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 59 |
+
"seed_textbox": seed_textbox,
|
| 60 |
+
})
|
| 61 |
+
|
| 62 |
+
# Initialize session and set headers
|
| 63 |
+
session = requests.session()
|
| 64 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 65 |
+
|
| 66 |
+
# Send POST request
|
| 67 |
+
if url[-1] == "/":
|
| 68 |
+
url = url[:-1]
|
| 69 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 70 |
+
|
| 71 |
+
data = post_r.content.decode('utf-8')
|
| 72 |
+
return data
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
# initiate time
|
| 76 |
+
time_start = time.time()
|
| 77 |
+
|
| 78 |
+
# The Url you want to post
|
| 79 |
+
POST_URL = 'http://0.0.0.0:7860'
|
| 80 |
+
# Used in EAS. If you don't need Authorization, please set it to empty string.
|
| 81 |
+
TOKEN = ''
|
| 82 |
+
|
| 83 |
+
# -------------------------- #
|
| 84 |
+
# Step 1: update edition
|
| 85 |
+
# -------------------------- #
|
| 86 |
+
# diffusion_transformer_path = "models/Diffusion_Transformer/Wan2.1-Fun-1.3B-InP"
|
| 87 |
+
# outputs = post_diffusion_transformer(diffusion_transformer_path)
|
| 88 |
+
# print('Output update edition: ', outputs)
|
| 89 |
+
|
| 90 |
+
# -------------------------- #
|
| 91 |
+
# Step 2: infer
|
| 92 |
+
# -------------------------- #
|
| 93 |
+
# "Video Generation" and "Image Generation"
|
| 94 |
+
generation_method = "Video Generation"
|
| 95 |
+
# Video length
|
| 96 |
+
length_slider = 49
|
| 97 |
+
# Used in Lora models
|
| 98 |
+
lora_model_path = "none"
|
| 99 |
+
lora_alpha_slider = 0.55
|
| 100 |
+
# Prompts
|
| 101 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 102 |
+
negative_prompt_textbox = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 103 |
+
# Sampler name
|
| 104 |
+
sampler_dropdown = "Flow"
|
| 105 |
+
# Sampler steps
|
| 106 |
+
sample_step_slider = 50
|
| 107 |
+
# height and width
|
| 108 |
+
width_slider = 832
|
| 109 |
+
height_slider = 480
|
| 110 |
+
# cfg scale
|
| 111 |
+
cfg_scale_slider = 6
|
| 112 |
+
seed_textbox = 43
|
| 113 |
+
|
| 114 |
+
outputs = post_infer(
|
| 115 |
+
generation_method,
|
| 116 |
+
length_slider,
|
| 117 |
+
lora_model_path=lora_model_path,
|
| 118 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 119 |
+
prompt_textbox=prompt_textbox,
|
| 120 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 121 |
+
sampler_dropdown=sampler_dropdown,
|
| 122 |
+
sample_step_slider=sample_step_slider,
|
| 123 |
+
width_slider=width_slider,
|
| 124 |
+
height_slider=height_slider,
|
| 125 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 126 |
+
seed_textbox=seed_textbox,
|
| 127 |
+
url=POST_URL,
|
| 128 |
+
POST_TOKEN=TOKEN
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Get decoded data
|
| 132 |
+
outputs = json.loads(outputs)
|
| 133 |
+
base64_encoding = outputs["base64_encoding"]
|
| 134 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 135 |
+
|
| 136 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 137 |
+
if is_image or length_slider == 1:
|
| 138 |
+
file_path = "1.png"
|
| 139 |
+
else:
|
| 140 |
+
file_path = "1.mp4"
|
| 141 |
+
with open(file_path, "wb") as file:
|
| 142 |
+
file.write(decoded_data)
|
| 143 |
+
|
| 144 |
+
# End of record time
|
| 145 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 146 |
+
time_end = time.time()
|
| 147 |
+
time_sum = (time_end - time_start)
|
| 148 |
+
print('# --------------------------------------------------------- #')
|
| 149 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 150 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1_fun/post_infer_queue.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def post_infer(
|
| 9 |
+
generation_method,
|
| 10 |
+
length_slider,
|
| 11 |
+
url='http://127.0.0.1:7860',
|
| 12 |
+
POST_TOKEN="",
|
| 13 |
+
timeout=5,
|
| 14 |
+
base_model_path="none",
|
| 15 |
+
lora_model_path="none",
|
| 16 |
+
lora_alpha_slider=0.55,
|
| 17 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 18 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 19 |
+
sampler_dropdown="Flow",
|
| 20 |
+
sample_step_slider=50,
|
| 21 |
+
width_slider=672,
|
| 22 |
+
height_slider=384,
|
| 23 |
+
cfg_scale_slider=6,
|
| 24 |
+
seed_textbox=43,
|
| 25 |
+
enable_teacache = None,
|
| 26 |
+
teacache_threshold = None,
|
| 27 |
+
num_skip_start_steps = None,
|
| 28 |
+
teacache_offload = None,
|
| 29 |
+
cfg_skip_ratio = None,
|
| 30 |
+
enable_riflex = None,
|
| 31 |
+
riflex_k = None,
|
| 32 |
+
):
|
| 33 |
+
# Prepare the data payload
|
| 34 |
+
datas = json.dumps({
|
| 35 |
+
"base_model_path": base_model_path,
|
| 36 |
+
"lora_model_path": lora_model_path,
|
| 37 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 38 |
+
"prompt_textbox": prompt_textbox,
|
| 39 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 40 |
+
"sampler_dropdown": sampler_dropdown,
|
| 41 |
+
"sample_step_slider": sample_step_slider,
|
| 42 |
+
"width_slider": width_slider,
|
| 43 |
+
"height_slider": height_slider,
|
| 44 |
+
"generation_method": generation_method,
|
| 45 |
+
"length_slider": length_slider,
|
| 46 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 47 |
+
"seed_textbox": seed_textbox,
|
| 48 |
+
|
| 49 |
+
"enable_teacache": enable_teacache,
|
| 50 |
+
"teacache_threshold": teacache_threshold,
|
| 51 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 52 |
+
"teacache_offload": teacache_offload,
|
| 53 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 54 |
+
"enable_riflex": enable_riflex,
|
| 55 |
+
"riflex_k": riflex_k,
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
# Initialize session and set headers
|
| 59 |
+
session = requests.session()
|
| 60 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 61 |
+
|
| 62 |
+
# Send POST request
|
| 63 |
+
if url[-1] == "/":
|
| 64 |
+
url = url[:-1]
|
| 65 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 66 |
+
|
| 67 |
+
# Extract request ID from POST response headers
|
| 68 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 69 |
+
|
| 70 |
+
# Prepare query parameters for GET request
|
| 71 |
+
query = {
|
| 72 |
+
'_index_': '0',
|
| 73 |
+
'_length_': '1',
|
| 74 |
+
'_timeout_': str(timeout),
|
| 75 |
+
'_raw_': 'false',
|
| 76 |
+
'_auto_delete_': 'true',
|
| 77 |
+
}
|
| 78 |
+
if request_id:
|
| 79 |
+
query['requestId'] = request_id
|
| 80 |
+
|
| 81 |
+
query_str = urllib.parse.urlencode(query)
|
| 82 |
+
|
| 83 |
+
# Polling GET request until status code is not 204
|
| 84 |
+
status_code = 204
|
| 85 |
+
while status_code == 204:
|
| 86 |
+
if query_str:
|
| 87 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 88 |
+
else:
|
| 89 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 90 |
+
status_code = get_r.status_code
|
| 91 |
+
# Decode and return the response content
|
| 92 |
+
data = get_r.content.decode('utf-8')
|
| 93 |
+
return data
|
| 94 |
+
|
| 95 |
+
if __name__ == '__main__':
|
| 96 |
+
# initiate time
|
| 97 |
+
time_start = time.time()
|
| 98 |
+
|
| 99 |
+
# EAS队列配置
|
| 100 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 101 |
+
# Use in EAS Queue
|
| 102 |
+
TOKEN = 'xxxxxxxx'
|
| 103 |
+
|
| 104 |
+
# Support TeaCache.
|
| 105 |
+
enable_teacache = True
|
| 106 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 107 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 108 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 109 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 110 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 111 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 112 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 113 |
+
teacache_threshold = 0.10
|
| 114 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 115 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 116 |
+
num_skip_start_steps = 5
|
| 117 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 118 |
+
teacache_offload = False
|
| 119 |
+
|
| 120 |
+
# Skip some cfg steps in inference
|
| 121 |
+
# Recommended to be set between 0.00 and 0.25
|
| 122 |
+
cfg_skip_ratio = 0
|
| 123 |
+
|
| 124 |
+
# Riflex config
|
| 125 |
+
enable_riflex = False
|
| 126 |
+
# Index of intrinsic frequency
|
| 127 |
+
riflex_k = 6
|
| 128 |
+
|
| 129 |
+
# "Video Generation" and "Image Generation"
|
| 130 |
+
generation_method = "Video Generation"
|
| 131 |
+
# Video length
|
| 132 |
+
length_slider = 81
|
| 133 |
+
# Used in Lora models
|
| 134 |
+
lora_model_path = "none"
|
| 135 |
+
lora_alpha_slider = 0.55
|
| 136 |
+
# Prompts
|
| 137 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 138 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 139 |
+
# Sampler name
|
| 140 |
+
sampler_dropdown = "Flow"
|
| 141 |
+
# Sampler steps
|
| 142 |
+
sample_step_slider = 50
|
| 143 |
+
# height and width
|
| 144 |
+
width_slider = 832
|
| 145 |
+
height_slider = 480
|
| 146 |
+
# cfg scale
|
| 147 |
+
cfg_scale_slider = 6
|
| 148 |
+
seed_textbox = 43
|
| 149 |
+
|
| 150 |
+
outputs = post_infer(
|
| 151 |
+
generation_method,
|
| 152 |
+
length_slider,
|
| 153 |
+
lora_model_path=lora_model_path,
|
| 154 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 155 |
+
prompt_textbox=prompt_textbox,
|
| 156 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 157 |
+
sampler_dropdown=sampler_dropdown,
|
| 158 |
+
sample_step_slider=sample_step_slider,
|
| 159 |
+
width_slider=width_slider,
|
| 160 |
+
height_slider=height_slider,
|
| 161 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 162 |
+
seed_textbox=seed_textbox,
|
| 163 |
+
enable_teacache = enable_teacache,
|
| 164 |
+
teacache_threshold = teacache_threshold,
|
| 165 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 166 |
+
teacache_offload = teacache_offload,
|
| 167 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 168 |
+
enable_riflex = enable_riflex,
|
| 169 |
+
riflex_k = riflex_k,
|
| 170 |
+
url=EAS_URL,
|
| 171 |
+
POST_TOKEN=TOKEN
|
| 172 |
+
)
|
| 173 |
+
# Get decoded data
|
| 174 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 175 |
+
base64_encoding = outputs["base64_encoding"]
|
| 176 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 177 |
+
|
| 178 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 179 |
+
if is_image or length_slider == 1:
|
| 180 |
+
file_path = "1.png"
|
| 181 |
+
else:
|
| 182 |
+
file_path = "1.mp4"
|
| 183 |
+
with open(file_path, "wb") as file:
|
| 184 |
+
file.write(decoded_data)
|
| 185 |
+
|
| 186 |
+
# End of record time
|
| 187 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 188 |
+
time_end = time.time()
|
| 189 |
+
time_sum = (time_end - time_start)
|
| 190 |
+
print('# --------------------------------------------------------- #')
|
| 191 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 192 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1_fun/post_infer_queue_i2v.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_infer(
|
| 11 |
+
generation_method,
|
| 12 |
+
length_slider,
|
| 13 |
+
url='http://127.0.0.1:7860',
|
| 14 |
+
POST_TOKEN="",
|
| 15 |
+
timeout=5,
|
| 16 |
+
base_model_path="none",
|
| 17 |
+
lora_model_path="none",
|
| 18 |
+
lora_alpha_slider=0.55,
|
| 19 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 20 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 21 |
+
sampler_dropdown="Flow",
|
| 22 |
+
sample_step_slider=50,
|
| 23 |
+
width_slider=672,
|
| 24 |
+
height_slider=384,
|
| 25 |
+
cfg_scale_slider=6,
|
| 26 |
+
seed_textbox=43,
|
| 27 |
+
enable_teacache = None,
|
| 28 |
+
teacache_threshold = None,
|
| 29 |
+
num_skip_start_steps = None,
|
| 30 |
+
teacache_offload = None,
|
| 31 |
+
cfg_skip_ratio = None,
|
| 32 |
+
enable_riflex = None,
|
| 33 |
+
riflex_k = None,
|
| 34 |
+
start_image = None
|
| 35 |
+
):
|
| 36 |
+
if start_image:
|
| 37 |
+
try:
|
| 38 |
+
if not start_image.startswith("http"):
|
| 39 |
+
image = Image.open(start_image).convert("RGB")
|
| 40 |
+
# 将图片转换为 Base64 编码
|
| 41 |
+
buffered = BytesIO()
|
| 42 |
+
image.save(buffered, format="JPEG")
|
| 43 |
+
start_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error processing start_image: {e}")
|
| 46 |
+
raise
|
| 47 |
+
|
| 48 |
+
# Prepare the data payload
|
| 49 |
+
datas = json.dumps({
|
| 50 |
+
"base_model_path": base_model_path,
|
| 51 |
+
"lora_model_path": lora_model_path,
|
| 52 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 53 |
+
"prompt_textbox": prompt_textbox,
|
| 54 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 55 |
+
"sampler_dropdown": sampler_dropdown,
|
| 56 |
+
"sample_step_slider": sample_step_slider,
|
| 57 |
+
"width_slider": width_slider,
|
| 58 |
+
"height_slider": height_slider,
|
| 59 |
+
"generation_method": generation_method,
|
| 60 |
+
"length_slider": length_slider,
|
| 61 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 62 |
+
"seed_textbox": seed_textbox,
|
| 63 |
+
|
| 64 |
+
"enable_teacache": enable_teacache,
|
| 65 |
+
"teacache_threshold": teacache_threshold,
|
| 66 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 67 |
+
"teacache_offload": teacache_offload,
|
| 68 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 69 |
+
"enable_riflex": enable_riflex,
|
| 70 |
+
"riflex_k": riflex_k,
|
| 71 |
+
"start_image": start_image
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# Initialize session and set headers
|
| 75 |
+
session = requests.session()
|
| 76 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 77 |
+
|
| 78 |
+
# Send POST request
|
| 79 |
+
if url[-1] == "/":
|
| 80 |
+
url = url[:-1]
|
| 81 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 82 |
+
|
| 83 |
+
# Extract request ID from POST response headers
|
| 84 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 85 |
+
|
| 86 |
+
# Prepare query parameters for GET request
|
| 87 |
+
query = {
|
| 88 |
+
'_index_': '0',
|
| 89 |
+
'_length_': '1',
|
| 90 |
+
'_timeout_': str(timeout),
|
| 91 |
+
'_raw_': 'false',
|
| 92 |
+
'_auto_delete_': 'true',
|
| 93 |
+
}
|
| 94 |
+
if request_id:
|
| 95 |
+
query['requestId'] = request_id
|
| 96 |
+
|
| 97 |
+
query_str = urllib.parse.urlencode(query)
|
| 98 |
+
|
| 99 |
+
# Polling GET request until status code is not 204
|
| 100 |
+
status_code = 204
|
| 101 |
+
while status_code == 204:
|
| 102 |
+
if query_str:
|
| 103 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 104 |
+
else:
|
| 105 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 106 |
+
status_code = get_r.status_code
|
| 107 |
+
# Decode and return the response content
|
| 108 |
+
data = get_r.content.decode('utf-8')
|
| 109 |
+
return data
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == '__main__':
|
| 113 |
+
# initiate time
|
| 114 |
+
time_start = time.time()
|
| 115 |
+
|
| 116 |
+
# EAS队列配置
|
| 117 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 118 |
+
# Use in EAS Queue
|
| 119 |
+
TOKEN = 'xxxxxxxx'
|
| 120 |
+
|
| 121 |
+
# Support TeaCache.
|
| 122 |
+
enable_teacache = True
|
| 123 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 124 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 125 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 126 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 127 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 128 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 129 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 130 |
+
teacache_threshold = 0.10
|
| 131 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 132 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 133 |
+
num_skip_start_steps = 5
|
| 134 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 135 |
+
teacache_offload = False
|
| 136 |
+
|
| 137 |
+
# Skip some cfg steps in inference
|
| 138 |
+
# Recommended to be set between 0.00 and 0.25
|
| 139 |
+
cfg_skip_ratio = 0
|
| 140 |
+
|
| 141 |
+
# Riflex config
|
| 142 |
+
enable_riflex = False
|
| 143 |
+
# Index of intrinsic frequency
|
| 144 |
+
riflex_k = 6
|
| 145 |
+
|
| 146 |
+
# "Video Generation" and "Image Generation"
|
| 147 |
+
generation_method = "Video Generation"
|
| 148 |
+
# Video length
|
| 149 |
+
length_slider = 81
|
| 150 |
+
# Used in Lora models
|
| 151 |
+
lora_model_path = "none"
|
| 152 |
+
lora_alpha_slider = 0.55
|
| 153 |
+
# Prompts
|
| 154 |
+
prompt_textbox = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 155 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 156 |
+
# Sampler name
|
| 157 |
+
sampler_dropdown = "Flow"
|
| 158 |
+
# Sampler steps
|
| 159 |
+
sample_step_slider = 50
|
| 160 |
+
# height and width
|
| 161 |
+
width_slider = 832
|
| 162 |
+
height_slider = 480
|
| 163 |
+
# cfg scale
|
| 164 |
+
cfg_scale_slider = 6
|
| 165 |
+
seed_textbox = 43
|
| 166 |
+
|
| 167 |
+
# 起始图片路径
|
| 168 |
+
start_image_path = "asset/1.png" # 替换为实际的图片路径
|
| 169 |
+
|
| 170 |
+
outputs = post_infer(
|
| 171 |
+
generation_method,
|
| 172 |
+
length_slider,
|
| 173 |
+
lora_model_path=lora_model_path,
|
| 174 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 175 |
+
prompt_textbox=prompt_textbox,
|
| 176 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 177 |
+
sampler_dropdown=sampler_dropdown,
|
| 178 |
+
sample_step_slider=sample_step_slider,
|
| 179 |
+
width_slider=width_slider,
|
| 180 |
+
height_slider=height_slider,
|
| 181 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 182 |
+
seed_textbox=seed_textbox,
|
| 183 |
+
enable_teacache = enable_teacache,
|
| 184 |
+
teacache_threshold = teacache_threshold,
|
| 185 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 186 |
+
teacache_offload = teacache_offload,
|
| 187 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 188 |
+
enable_riflex = enable_riflex,
|
| 189 |
+
riflex_k = riflex_k,
|
| 190 |
+
url=EAS_URL,
|
| 191 |
+
POST_TOKEN=TOKEN,
|
| 192 |
+
start_image=start_image_path # 传递起始图片路径
|
| 193 |
+
)
|
| 194 |
+
# Get decoded data
|
| 195 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 196 |
+
base64_encoding = outputs["base64_encoding"]
|
| 197 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 198 |
+
|
| 199 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 200 |
+
if is_image or length_slider == 1:
|
| 201 |
+
file_path = "1.png"
|
| 202 |
+
else:
|
| 203 |
+
file_path = "1.mp4"
|
| 204 |
+
with open(file_path, "wb") as file:
|
| 205 |
+
file.write(decoded_data)
|
| 206 |
+
|
| 207 |
+
# End of record time
|
| 208 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 209 |
+
time_end = time.time()
|
| 210 |
+
time_sum = (time_end - time_start)
|
| 211 |
+
print('# --------------------------------------------------------- #')
|
| 212 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 213 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1_fun/post_infer_queue_v2v_control.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def post_infer(
|
| 12 |
+
generation_method,
|
| 13 |
+
length_slider,
|
| 14 |
+
url='http://127.0.0.1:7860',
|
| 15 |
+
POST_TOKEN="",
|
| 16 |
+
timeout=5,
|
| 17 |
+
base_model_path="none",
|
| 18 |
+
lora_model_path="none",
|
| 19 |
+
lora_alpha_slider=0.55,
|
| 20 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 21 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 22 |
+
sampler_dropdown="Flow",
|
| 23 |
+
sample_step_slider=50,
|
| 24 |
+
width_slider=672,
|
| 25 |
+
height_slider=384,
|
| 26 |
+
cfg_scale_slider=6,
|
| 27 |
+
seed_textbox=43,
|
| 28 |
+
enable_teacache = None,
|
| 29 |
+
teacache_threshold = None,
|
| 30 |
+
num_skip_start_steps = None,
|
| 31 |
+
teacache_offload = None,
|
| 32 |
+
cfg_skip_ratio = None,
|
| 33 |
+
enable_riflex = None,
|
| 34 |
+
riflex_k = None,
|
| 35 |
+
control_video = None,
|
| 36 |
+
ref_image = None
|
| 37 |
+
):
|
| 38 |
+
if control_video:
|
| 39 |
+
try:
|
| 40 |
+
if not control_video.startswith("http"):
|
| 41 |
+
with open(control_video, "rb") as file:
|
| 42 |
+
video_data = file.read()
|
| 43 |
+
|
| 44 |
+
control_video = base64.b64encode(video_data).decode('utf-8')
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Error processing control_video: {e}")
|
| 47 |
+
raise
|
| 48 |
+
|
| 49 |
+
if ref_image:
|
| 50 |
+
try:
|
| 51 |
+
if not ref_image.startswith("http"):
|
| 52 |
+
image = Image.open(ref_image).convert("RGB")
|
| 53 |
+
# 将图片转换为 Base64 编码
|
| 54 |
+
buffered = BytesIO()
|
| 55 |
+
image.save(buffered, format="JPEG")
|
| 56 |
+
ref_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error processing ref_image: {e}")
|
| 59 |
+
raise
|
| 60 |
+
|
| 61 |
+
# Prepare the data payload
|
| 62 |
+
datas = json.dumps({
|
| 63 |
+
"base_model_path": base_model_path,
|
| 64 |
+
"lora_model_path": lora_model_path,
|
| 65 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 66 |
+
"prompt_textbox": prompt_textbox,
|
| 67 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 68 |
+
"sampler_dropdown": sampler_dropdown,
|
| 69 |
+
"sample_step_slider": sample_step_slider,
|
| 70 |
+
"width_slider": width_slider,
|
| 71 |
+
"height_slider": height_slider,
|
| 72 |
+
"generation_method": generation_method,
|
| 73 |
+
"length_slider": length_slider,
|
| 74 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 75 |
+
"seed_textbox": seed_textbox,
|
| 76 |
+
|
| 77 |
+
"ref_image": ref_image,
|
| 78 |
+
"enable_teacache": enable_teacache,
|
| 79 |
+
"teacache_threshold": teacache_threshold,
|
| 80 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 81 |
+
"teacache_offload": teacache_offload,
|
| 82 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 83 |
+
"enable_riflex": enable_riflex,
|
| 84 |
+
"riflex_k": riflex_k,
|
| 85 |
+
"control_video": control_video
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
# Initialize session and set headers
|
| 89 |
+
session = requests.session()
|
| 90 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 91 |
+
|
| 92 |
+
# Send POST request
|
| 93 |
+
if url[-1] == "/":
|
| 94 |
+
url = url[:-1]
|
| 95 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 96 |
+
|
| 97 |
+
# Extract request ID from POST response headers
|
| 98 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 99 |
+
|
| 100 |
+
# Prepare query parameters for GET request
|
| 101 |
+
query = {
|
| 102 |
+
'_index_': '0',
|
| 103 |
+
'_length_': '1',
|
| 104 |
+
'_timeout_': str(timeout),
|
| 105 |
+
'_raw_': 'false',
|
| 106 |
+
'_auto_delete_': 'true',
|
| 107 |
+
}
|
| 108 |
+
if request_id:
|
| 109 |
+
query['requestId'] = request_id
|
| 110 |
+
|
| 111 |
+
query_str = urllib.parse.urlencode(query)
|
| 112 |
+
|
| 113 |
+
# Polling GET request until status code is not 204
|
| 114 |
+
status_code = 204
|
| 115 |
+
while status_code == 204:
|
| 116 |
+
if query_str:
|
| 117 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 118 |
+
else:
|
| 119 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 120 |
+
status_code = get_r.status_code
|
| 121 |
+
# Decode and return the response content
|
| 122 |
+
data = get_r.content.decode('utf-8')
|
| 123 |
+
return data
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == '__main__':
|
| 127 |
+
# initiate time
|
| 128 |
+
time_start = time.time()
|
| 129 |
+
|
| 130 |
+
# EAS队列配置
|
| 131 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 132 |
+
# Use in EAS Queue
|
| 133 |
+
TOKEN = 'xxxxxxxx'
|
| 134 |
+
|
| 135 |
+
# Support TeaCache.
|
| 136 |
+
enable_teacache = True
|
| 137 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 138 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 139 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 140 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 141 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 142 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 143 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 144 |
+
teacache_threshold = 0.10
|
| 145 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 146 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 147 |
+
num_skip_start_steps = 5
|
| 148 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 149 |
+
teacache_offload = False
|
| 150 |
+
|
| 151 |
+
# Skip some cfg steps in inference
|
| 152 |
+
# Recommended to be set between 0.00 and 0.25
|
| 153 |
+
cfg_skip_ratio = 0
|
| 154 |
+
|
| 155 |
+
# Riflex config
|
| 156 |
+
enable_riflex = False
|
| 157 |
+
# Index of intrinsic frequency
|
| 158 |
+
riflex_k = 6
|
| 159 |
+
|
| 160 |
+
# "Video Generation" and "Image Generation"
|
| 161 |
+
generation_method = "Video Generation"
|
| 162 |
+
# Video length
|
| 163 |
+
length_slider = 81
|
| 164 |
+
# Used in Lora models
|
| 165 |
+
lora_model_path = "none"
|
| 166 |
+
lora_alpha_slider = 0.55
|
| 167 |
+
# Prompts
|
| 168 |
+
prompt_textbox = "在这个阳光明媚的户外花园里,美女身穿一袭及膝的白色无袖连衣裙,裙摆在她轻盈的舞姿中轻柔地摆动,宛如一只翩翩起舞的蝴蝶。阳光透过树叶间洒下斑驳的光影,映衬出她柔和的脸庞和清澈的眼眸,显得格外优雅。仿佛每一个动作都在诉说着青春与活力,她在草地上旋转,裙摆随之飞扬,仿佛整个花园都因她的舞动而欢愉。周围五彩缤纷的花朵在微风中摇曳,玫瑰、菊花、百合,各自释放出阵阵香气,营造出一种轻松而愉快的氛围。"
|
| 169 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 170 |
+
# Sampler name
|
| 171 |
+
sampler_dropdown = "Flow"
|
| 172 |
+
# Sampler steps
|
| 173 |
+
sample_step_slider = 50
|
| 174 |
+
# height and width
|
| 175 |
+
width_slider = 480
|
| 176 |
+
height_slider = 832
|
| 177 |
+
# cfg scale
|
| 178 |
+
cfg_scale_slider = 6
|
| 179 |
+
seed_textbox = 43
|
| 180 |
+
|
| 181 |
+
# 控制视频路径(可以是本地路径或 URL)
|
| 182 |
+
control_video_path = "asset/000000.mp4" # 替换为实际的视频路径
|
| 183 |
+
# 参考图片路径
|
| 184 |
+
ref_image_path = None # 替换为实际的图片路径
|
| 185 |
+
|
| 186 |
+
outputs = post_infer(
|
| 187 |
+
generation_method,
|
| 188 |
+
length_slider,
|
| 189 |
+
lora_model_path=lora_model_path,
|
| 190 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 191 |
+
prompt_textbox=prompt_textbox,
|
| 192 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 193 |
+
sampler_dropdown=sampler_dropdown,
|
| 194 |
+
sample_step_slider=sample_step_slider,
|
| 195 |
+
width_slider=width_slider,
|
| 196 |
+
height_slider=height_slider,
|
| 197 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 198 |
+
seed_textbox=seed_textbox,
|
| 199 |
+
enable_teacache = enable_teacache,
|
| 200 |
+
teacache_threshold = teacache_threshold,
|
| 201 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 202 |
+
teacache_offload = teacache_offload,
|
| 203 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 204 |
+
enable_riflex = enable_riflex,
|
| 205 |
+
riflex_k = riflex_k,
|
| 206 |
+
url=EAS_URL,
|
| 207 |
+
POST_TOKEN=TOKEN,
|
| 208 |
+
control_video=control_video_path, # 传递控制视频路径
|
| 209 |
+
ref_image=ref_image_path # 传递参考图片路径
|
| 210 |
+
)
|
| 211 |
+
# Get decoded data
|
| 212 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 213 |
+
base64_encoding = outputs["base64_encoding"]
|
| 214 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 215 |
+
|
| 216 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 217 |
+
if is_image or length_slider == 1:
|
| 218 |
+
file_path = "1.png"
|
| 219 |
+
else:
|
| 220 |
+
file_path = "1.mp4"
|
| 221 |
+
with open(file_path, "wb") as file:
|
| 222 |
+
file.write(decoded_data)
|
| 223 |
+
|
| 224 |
+
# End of record time
|
| 225 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 226 |
+
time_end = time.time()
|
| 227 |
+
time_sum = (time_end - time_start)
|
| 228 |
+
print('# --------------------------------------------------------- #')
|
| 229 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 230 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.1_fun/predict_i2v.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, CLIPModel, WanT5EncoderModel,
|
| 18 |
+
WanTransformer3DModel)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanFunInpaintPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 30 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 31 |
+
#
|
| 32 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 33 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 34 |
+
#
|
| 35 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 36 |
+
#
|
| 37 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 38 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 41 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 42 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 43 |
+
# Multi GPUs config
|
| 44 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 45 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 46 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 47 |
+
ulysses_degree = 1
|
| 48 |
+
ring_degree = 1
|
| 49 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 50 |
+
fsdp_dit = False
|
| 51 |
+
fsdp_text_encoder = True
|
| 52 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 53 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 54 |
+
compile_dit = False
|
| 55 |
+
|
| 56 |
+
# Support TeaCache.
|
| 57 |
+
enable_teacache = True
|
| 58 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 59 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 60 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 61 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 62 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 63 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 64 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 65 |
+
teacache_threshold = 0.10
|
| 66 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 67 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 68 |
+
num_skip_start_steps = 5
|
| 69 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 70 |
+
teacache_offload = False
|
| 71 |
+
|
| 72 |
+
# Skip some cfg steps in inference
|
| 73 |
+
# Recommended to be set between 0.00 and 0.25
|
| 74 |
+
cfg_skip_ratio = 0
|
| 75 |
+
|
| 76 |
+
# Riflex config
|
| 77 |
+
enable_riflex = False
|
| 78 |
+
# Index of intrinsic frequency
|
| 79 |
+
riflex_k = 6
|
| 80 |
+
|
| 81 |
+
# Config and model path
|
| 82 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 83 |
+
# model path
|
| 84 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-InP"
|
| 85 |
+
|
| 86 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 87 |
+
sampler_name = "Flow"
|
| 88 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 89 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 90 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 91 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 92 |
+
shift = 3
|
| 93 |
+
|
| 94 |
+
# Load pretrained model if need
|
| 95 |
+
transformer_path = None
|
| 96 |
+
vae_path = None
|
| 97 |
+
lora_path = None
|
| 98 |
+
|
| 99 |
+
# Other params
|
| 100 |
+
sample_size = [480, 832]
|
| 101 |
+
video_length = 81
|
| 102 |
+
fps = 16
|
| 103 |
+
|
| 104 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 105 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 106 |
+
weight_dtype = torch.bfloat16
|
| 107 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 108 |
+
validation_image_start = "asset/1.png"
|
| 109 |
+
validation_image_end = None
|
| 110 |
+
|
| 111 |
+
# prompts
|
| 112 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 113 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 114 |
+
guidance_scale = 6.0
|
| 115 |
+
seed = 43
|
| 116 |
+
num_inference_steps = 50
|
| 117 |
+
lora_weight = 0.55
|
| 118 |
+
save_path = "samples/wan-videos-fun-i2v"
|
| 119 |
+
|
| 120 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 121 |
+
config = OmegaConf.load(config_path)
|
| 122 |
+
|
| 123 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 124 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 125 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 126 |
+
low_cpu_mem_usage=True,
|
| 127 |
+
torch_dtype=weight_dtype,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if transformer_path is not None:
|
| 131 |
+
print(f"From checkpoint: {transformer_path}")
|
| 132 |
+
if transformer_path.endswith("safetensors"):
|
| 133 |
+
from safetensors.torch import load_file, safe_open
|
| 134 |
+
state_dict = load_file(transformer_path)
|
| 135 |
+
else:
|
| 136 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 137 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 138 |
+
|
| 139 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 140 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 141 |
+
|
| 142 |
+
# Get Vae
|
| 143 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 144 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 145 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 146 |
+
).to(weight_dtype)
|
| 147 |
+
|
| 148 |
+
if vae_path is not None:
|
| 149 |
+
print(f"From checkpoint: {vae_path}")
|
| 150 |
+
if vae_path.endswith("safetensors"):
|
| 151 |
+
from safetensors.torch import load_file, safe_open
|
| 152 |
+
state_dict = load_file(vae_path)
|
| 153 |
+
else:
|
| 154 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 155 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 156 |
+
|
| 157 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 158 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 159 |
+
|
| 160 |
+
# Get Tokenizer
|
| 161 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 162 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# Get Text encoder
|
| 166 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 167 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 168 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 169 |
+
low_cpu_mem_usage=True,
|
| 170 |
+
torch_dtype=weight_dtype,
|
| 171 |
+
)
|
| 172 |
+
text_encoder = text_encoder.eval()
|
| 173 |
+
|
| 174 |
+
# Get Clip Image Encoder
|
| 175 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 176 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 177 |
+
).to(weight_dtype)
|
| 178 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 179 |
+
|
| 180 |
+
# Get Scheduler
|
| 181 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 182 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 183 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 184 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 185 |
+
}[sampler_name]
|
| 186 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 187 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 188 |
+
scheduler = Chosen_Scheduler(
|
| 189 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# Get Pipeline
|
| 193 |
+
pipeline = WanFunInpaintPipeline(
|
| 194 |
+
transformer=transformer,
|
| 195 |
+
vae=vae,
|
| 196 |
+
tokenizer=tokenizer,
|
| 197 |
+
text_encoder=text_encoder,
|
| 198 |
+
scheduler=scheduler,
|
| 199 |
+
clip_image_encoder=clip_image_encoder
|
| 200 |
+
)
|
| 201 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 202 |
+
from functools import partial
|
| 203 |
+
transformer.enable_multi_gpus_inference()
|
| 204 |
+
if fsdp_dit:
|
| 205 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 206 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 207 |
+
print("Add FSDP DIT")
|
| 208 |
+
if fsdp_text_encoder:
|
| 209 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 210 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 211 |
+
print("Add FSDP TEXT ENCODER")
|
| 212 |
+
|
| 213 |
+
if compile_dit:
|
| 214 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 215 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 216 |
+
print("Add Compile")
|
| 217 |
+
|
| 218 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 219 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 220 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 221 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 222 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 223 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 224 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 225 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 226 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 227 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 228 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 229 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 230 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 231 |
+
pipeline.to(device=device)
|
| 232 |
+
else:
|
| 233 |
+
pipeline.to(device=device)
|
| 234 |
+
|
| 235 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 236 |
+
if coefficients is not None:
|
| 237 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 238 |
+
pipeline.transformer.enable_teacache(
|
| 239 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
if cfg_skip_ratio is not None:
|
| 243 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 244 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 245 |
+
|
| 246 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 247 |
+
|
| 248 |
+
if lora_path is not None:
|
| 249 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 250 |
+
|
| 251 |
+
with torch.no_grad():
|
| 252 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 253 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 254 |
+
|
| 255 |
+
if enable_riflex:
|
| 256 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 257 |
+
|
| 258 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, validation_image_end, video_length=video_length, sample_size=sample_size)
|
| 259 |
+
|
| 260 |
+
sample = pipeline(
|
| 261 |
+
prompt,
|
| 262 |
+
num_frames = video_length,
|
| 263 |
+
negative_prompt = negative_prompt,
|
| 264 |
+
height = sample_size[0],
|
| 265 |
+
width = sample_size[1],
|
| 266 |
+
generator = generator,
|
| 267 |
+
guidance_scale = guidance_scale,
|
| 268 |
+
num_inference_steps = num_inference_steps,
|
| 269 |
+
|
| 270 |
+
video = input_video,
|
| 271 |
+
mask_video = input_video_mask,
|
| 272 |
+
clip_image = clip_image,
|
| 273 |
+
shift = shift,
|
| 274 |
+
).videos
|
| 275 |
+
|
| 276 |
+
if lora_path is not None:
|
| 277 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 278 |
+
|
| 279 |
+
def save_results():
|
| 280 |
+
if not os.path.exists(save_path):
|
| 281 |
+
os.makedirs(save_path, exist_ok=True)
|
| 282 |
+
|
| 283 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 284 |
+
prefix = str(index).zfill(8)
|
| 285 |
+
if video_length == 1:
|
| 286 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 287 |
+
|
| 288 |
+
image = sample[0, :, 0]
|
| 289 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 290 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 291 |
+
image = Image.fromarray(image)
|
| 292 |
+
image.save(video_path)
|
| 293 |
+
else:
|
| 294 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 295 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 296 |
+
|
| 297 |
+
if ulysses_degree * ring_degree > 1:
|
| 298 |
+
import torch.distributed as dist
|
| 299 |
+
if dist.get_rank() == 0:
|
| 300 |
+
save_results()
|
| 301 |
+
else:
|
| 302 |
+
save_results()
|
VideoX-Fun/examples/wan2.1_fun/predict_t2v.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, CLIPModel, WanT5EncoderModel,
|
| 18 |
+
WanTransformer3DModel)
|
| 19 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 20 |
+
from videox_fun.pipeline import WanFunInpaintPipeline, WanFunPipeline
|
| 21 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 22 |
+
convert_weight_dtype_wrapper)
|
| 23 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 24 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 25 |
+
save_videos_grid)
|
| 26 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 27 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 28 |
+
|
| 29 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 30 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 31 |
+
#
|
| 32 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 33 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 34 |
+
#
|
| 35 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 36 |
+
#
|
| 37 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 38 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 41 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 42 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 43 |
+
# Multi GPUs config
|
| 44 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 45 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 46 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 47 |
+
ulysses_degree = 1
|
| 48 |
+
ring_degree = 1
|
| 49 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 50 |
+
fsdp_dit = False
|
| 51 |
+
fsdp_text_encoder = True
|
| 52 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 53 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 54 |
+
compile_dit = False
|
| 55 |
+
|
| 56 |
+
# Support TeaCache.
|
| 57 |
+
enable_teacache = True
|
| 58 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 59 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 60 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 61 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 62 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 63 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 64 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 65 |
+
teacache_threshold = 0.10
|
| 66 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 67 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 68 |
+
num_skip_start_steps = 5
|
| 69 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 70 |
+
teacache_offload = False
|
| 71 |
+
|
| 72 |
+
# Skip some cfg steps in inference
|
| 73 |
+
# Recommended to be set between 0.00 and 0.25
|
| 74 |
+
cfg_skip_ratio = 0
|
| 75 |
+
|
| 76 |
+
# Riflex config
|
| 77 |
+
enable_riflex = False
|
| 78 |
+
# Index of intrinsic frequency
|
| 79 |
+
riflex_k = 6
|
| 80 |
+
|
| 81 |
+
# Config and model path
|
| 82 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 83 |
+
# model path
|
| 84 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-InP"
|
| 85 |
+
|
| 86 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 87 |
+
sampler_name = "Flow"
|
| 88 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 89 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 90 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 91 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 92 |
+
shift = 3
|
| 93 |
+
|
| 94 |
+
# Load pretrained model if need
|
| 95 |
+
transformer_path = None
|
| 96 |
+
vae_path = None
|
| 97 |
+
lora_path = None
|
| 98 |
+
|
| 99 |
+
# Other params
|
| 100 |
+
sample_size = [480, 832]
|
| 101 |
+
video_length = 81
|
| 102 |
+
fps = 16
|
| 103 |
+
|
| 104 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 105 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 106 |
+
weight_dtype = torch.bfloat16
|
| 107 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 108 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 109 |
+
guidance_scale = 6.0
|
| 110 |
+
seed = 43
|
| 111 |
+
num_inference_steps = 50
|
| 112 |
+
lora_weight = 0.55
|
| 113 |
+
save_path = "samples/wan-videos-fun-t2v"
|
| 114 |
+
|
| 115 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 116 |
+
config = OmegaConf.load(config_path)
|
| 117 |
+
|
| 118 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 119 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 120 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 121 |
+
low_cpu_mem_usage=True,
|
| 122 |
+
torch_dtype=weight_dtype,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if transformer_path is not None:
|
| 126 |
+
print(f"From checkpoint: {transformer_path}")
|
| 127 |
+
if transformer_path.endswith("safetensors"):
|
| 128 |
+
from safetensors.torch import load_file, safe_open
|
| 129 |
+
state_dict = load_file(transformer_path)
|
| 130 |
+
else:
|
| 131 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 132 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 133 |
+
|
| 134 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 135 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 136 |
+
|
| 137 |
+
# Get Vae
|
| 138 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 139 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 140 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 141 |
+
).to(weight_dtype)
|
| 142 |
+
|
| 143 |
+
if vae_path is not None:
|
| 144 |
+
print(f"From checkpoint: {vae_path}")
|
| 145 |
+
if vae_path.endswith("safetensors"):
|
| 146 |
+
from safetensors.torch import load_file, safe_open
|
| 147 |
+
state_dict = load_file(vae_path)
|
| 148 |
+
else:
|
| 149 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 150 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 151 |
+
|
| 152 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 153 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 154 |
+
|
| 155 |
+
# Get Tokenizer
|
| 156 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 157 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Get Text encoder
|
| 161 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 162 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 163 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 164 |
+
low_cpu_mem_usage=True,
|
| 165 |
+
torch_dtype=weight_dtype,
|
| 166 |
+
)
|
| 167 |
+
text_encoder = text_encoder.eval()
|
| 168 |
+
|
| 169 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 170 |
+
# Get Clip Image Encoder
|
| 171 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 172 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 173 |
+
).to(weight_dtype)
|
| 174 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 175 |
+
else:
|
| 176 |
+
clip_image_encoder = None
|
| 177 |
+
clip_image_processor = None
|
| 178 |
+
|
| 179 |
+
# Get Scheduler
|
| 180 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 181 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 182 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 183 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 184 |
+
}[sampler_name]
|
| 185 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 186 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 187 |
+
scheduler = Chosen_Scheduler(
|
| 188 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 192 |
+
pipeline = WanFunInpaintPipeline(
|
| 193 |
+
vae=vae,
|
| 194 |
+
tokenizer=tokenizer,
|
| 195 |
+
text_encoder=text_encoder,
|
| 196 |
+
transformer=transformer,
|
| 197 |
+
scheduler=scheduler,
|
| 198 |
+
clip_image_encoder=clip_image_encoder,
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
pipeline = WanFunPipeline(
|
| 202 |
+
vae=vae,
|
| 203 |
+
tokenizer=tokenizer,
|
| 204 |
+
text_encoder=text_encoder,
|
| 205 |
+
transformer=transformer,
|
| 206 |
+
scheduler=scheduler,
|
| 207 |
+
)
|
| 208 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 209 |
+
from functools import partial
|
| 210 |
+
transformer.enable_multi_gpus_inference()
|
| 211 |
+
if fsdp_dit:
|
| 212 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 213 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 214 |
+
print("Add FSDP DIT")
|
| 215 |
+
if fsdp_text_encoder:
|
| 216 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 217 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 218 |
+
print("Add FSDP TEXT ENCODER")
|
| 219 |
+
|
| 220 |
+
if compile_dit:
|
| 221 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 222 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 223 |
+
print("Add Compile")
|
| 224 |
+
|
| 225 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 226 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 227 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 228 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 229 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 230 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 231 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 232 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 233 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 234 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 235 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 236 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 237 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 238 |
+
pipeline.to(device=device)
|
| 239 |
+
else:
|
| 240 |
+
pipeline.to(device=device)
|
| 241 |
+
|
| 242 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 243 |
+
if coefficients is not None:
|
| 244 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 245 |
+
pipeline.transformer.enable_teacache(
|
| 246 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if cfg_skip_ratio is not None:
|
| 250 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 251 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 252 |
+
|
| 253 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 254 |
+
|
| 255 |
+
if lora_path is not None:
|
| 256 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 257 |
+
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 260 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 261 |
+
|
| 262 |
+
if enable_riflex:
|
| 263 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 264 |
+
|
| 265 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 266 |
+
input_video, input_video_mask, _ = get_image_to_video_latent(None, None, video_length=video_length, sample_size=sample_size)
|
| 267 |
+
|
| 268 |
+
sample = pipeline(
|
| 269 |
+
prompt,
|
| 270 |
+
num_frames = video_length,
|
| 271 |
+
negative_prompt = negative_prompt,
|
| 272 |
+
height = sample_size[0],
|
| 273 |
+
width = sample_size[1],
|
| 274 |
+
generator = generator,
|
| 275 |
+
guidance_scale = guidance_scale,
|
| 276 |
+
num_inference_steps = num_inference_steps,
|
| 277 |
+
|
| 278 |
+
video = input_video,
|
| 279 |
+
mask_video = input_video_mask,
|
| 280 |
+
shift = shift,
|
| 281 |
+
).videos
|
| 282 |
+
else:
|
| 283 |
+
sample = pipeline(
|
| 284 |
+
prompt,
|
| 285 |
+
num_frames = video_length,
|
| 286 |
+
negative_prompt = negative_prompt,
|
| 287 |
+
height = sample_size[0],
|
| 288 |
+
width = sample_size[1],
|
| 289 |
+
generator = generator,
|
| 290 |
+
guidance_scale = guidance_scale,
|
| 291 |
+
num_inference_steps = num_inference_steps,
|
| 292 |
+
shift = shift,
|
| 293 |
+
).videos
|
| 294 |
+
|
| 295 |
+
if lora_path is not None:
|
| 296 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 297 |
+
|
| 298 |
+
def save_results():
|
| 299 |
+
if not os.path.exists(save_path):
|
| 300 |
+
os.makedirs(save_path, exist_ok=True)
|
| 301 |
+
|
| 302 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 303 |
+
prefix = str(index).zfill(8)
|
| 304 |
+
if video_length == 1:
|
| 305 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 306 |
+
|
| 307 |
+
image = sample[0, :, 0]
|
| 308 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 309 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 310 |
+
image = Image.fromarray(image)
|
| 311 |
+
image.save(video_path)
|
| 312 |
+
else:
|
| 313 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 314 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 315 |
+
|
| 316 |
+
if ulysses_degree * ring_degree > 1:
|
| 317 |
+
import torch.distributed as dist
|
| 318 |
+
if dist.get_rank() == 0:
|
| 319 |
+
save_results()
|
| 320 |
+
else:
|
| 321 |
+
save_results()
|
VideoX-Fun/examples/wan2.1_fun/predict_v2v_control.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, AutoTokenizer, CLIPModel,
|
| 18 |
+
WanT5EncoderModel, WanTransformer3DModel)
|
| 19 |
+
from videox_fun.data.dataset_image_video import process_pose_file
|
| 20 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 21 |
+
from videox_fun.pipeline import WanFunControlPipeline, WanPipeline
|
| 22 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 23 |
+
convert_weight_dtype_wrapper,
|
| 24 |
+
replace_parameters_by_name)
|
| 25 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 26 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_latent,
|
| 27 |
+
get_video_to_video_latent,
|
| 28 |
+
save_videos_grid)
|
| 29 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 30 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 31 |
+
|
| 32 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 33 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 34 |
+
#
|
| 35 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 36 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 41 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 42 |
+
#
|
| 43 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 44 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 45 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 46 |
+
# Multi GPUs config
|
| 47 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 48 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 49 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 50 |
+
ulysses_degree = 1
|
| 51 |
+
ring_degree = 1
|
| 52 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 53 |
+
fsdp_dit = False
|
| 54 |
+
fsdp_text_encoder = True
|
| 55 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 56 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 57 |
+
compile_dit = False
|
| 58 |
+
|
| 59 |
+
# Support TeaCache.
|
| 60 |
+
enable_teacache = True
|
| 61 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 62 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 63 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 64 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 65 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 66 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 67 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 68 |
+
teacache_threshold = 0.10
|
| 69 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 70 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 71 |
+
num_skip_start_steps = 5
|
| 72 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 73 |
+
teacache_offload = False
|
| 74 |
+
|
| 75 |
+
# Skip some cfg steps in inference
|
| 76 |
+
# Recommended to be set between 0.00 and 0.25
|
| 77 |
+
cfg_skip_ratio = 0
|
| 78 |
+
|
| 79 |
+
# Riflex config
|
| 80 |
+
enable_riflex = False
|
| 81 |
+
# Index of intrinsic frequency
|
| 82 |
+
riflex_k = 6
|
| 83 |
+
|
| 84 |
+
# Config and model path
|
| 85 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 86 |
+
# model path
|
| 87 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-Control"
|
| 88 |
+
|
| 89 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 90 |
+
sampler_name = "Flow"
|
| 91 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 92 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 93 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 94 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 95 |
+
shift = 3
|
| 96 |
+
|
| 97 |
+
# Load pretrained model if need
|
| 98 |
+
transformer_path = None
|
| 99 |
+
vae_path = None
|
| 100 |
+
lora_path = None
|
| 101 |
+
|
| 102 |
+
# Other params
|
| 103 |
+
sample_size = [832, 480]
|
| 104 |
+
video_length = 49
|
| 105 |
+
fps = 16
|
| 106 |
+
|
| 107 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 108 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 109 |
+
weight_dtype = torch.bfloat16
|
| 110 |
+
control_video = "asset/pose.mp4"
|
| 111 |
+
control_camera_txt = None
|
| 112 |
+
start_image = None
|
| 113 |
+
ref_image = None
|
| 114 |
+
|
| 115 |
+
# 使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性
|
| 116 |
+
# 在neg prompt中添加"安静,固定"等词语可以增加动态性。
|
| 117 |
+
prompt = "在这个阳光明媚的户外花园里,美女身穿一袭及膝的白色无袖连衣裙,裙摆在她轻盈的舞姿中轻柔地摆动,宛如一只翩翩起舞的蝴蝶。阳光透过树叶间洒下斑驳的光影,映衬出她柔和的脸庞和清澈的眼眸,显得格外优雅。仿佛每一个动作都在诉说着青春与活力,她在草地上旋转,裙摆随之飞扬,仿佛整个花园都因她的舞动而欢愉。周围五彩缤纷的花朵在微风中摇曳,玫瑰、菊花、百合,各自释放出阵阵香气,营造出一种轻松而愉快的氛围。"
|
| 118 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 119 |
+
|
| 120 |
+
# Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability
|
| 121 |
+
# Adding words such as "quiet, solid" to the neg prompt can increase dynamism.
|
| 122 |
+
# prompt = "A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical."
|
| 123 |
+
# negative_prompt = "Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code."
|
| 124 |
+
guidance_scale = 6.0
|
| 125 |
+
seed = 43
|
| 126 |
+
num_inference_steps = 50
|
| 127 |
+
lora_weight = 0.55
|
| 128 |
+
save_path = "samples/wan-videos-fun-control"
|
| 129 |
+
|
| 130 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 131 |
+
config = OmegaConf.load(config_path)
|
| 132 |
+
|
| 133 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 134 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 135 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 136 |
+
low_cpu_mem_usage=True,
|
| 137 |
+
torch_dtype=weight_dtype,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if transformer_path is not None:
|
| 141 |
+
print(f"From checkpoint: {transformer_path}")
|
| 142 |
+
if transformer_path.endswith("safetensors"):
|
| 143 |
+
from safetensors.torch import load_file, safe_open
|
| 144 |
+
state_dict = load_file(transformer_path)
|
| 145 |
+
else:
|
| 146 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 147 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 148 |
+
|
| 149 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 150 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 151 |
+
|
| 152 |
+
# Get Vae
|
| 153 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 154 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 155 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 156 |
+
).to(weight_dtype)
|
| 157 |
+
|
| 158 |
+
if vae_path is not None:
|
| 159 |
+
print(f"From checkpoint: {vae_path}")
|
| 160 |
+
if vae_path.endswith("safetensors"):
|
| 161 |
+
from safetensors.torch import load_file, safe_open
|
| 162 |
+
state_dict = load_file(vae_path)
|
| 163 |
+
else:
|
| 164 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 165 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 166 |
+
|
| 167 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 168 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 169 |
+
|
| 170 |
+
# Get Tokenizer
|
| 171 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 172 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Get Text encoder
|
| 176 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 177 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 178 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 179 |
+
low_cpu_mem_usage=True,
|
| 180 |
+
torch_dtype=weight_dtype,
|
| 181 |
+
)
|
| 182 |
+
text_encoder = text_encoder.eval()
|
| 183 |
+
|
| 184 |
+
# Get Clip Image Encoder
|
| 185 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 186 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 187 |
+
).to(weight_dtype)
|
| 188 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 189 |
+
|
| 190 |
+
# Get Scheduler
|
| 191 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 192 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 193 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 194 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 195 |
+
}[sampler_name]
|
| 196 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 197 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 198 |
+
scheduler = Chosen_Scheduler(
|
| 199 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Get Pipeline
|
| 203 |
+
pipeline = WanFunControlPipeline(
|
| 204 |
+
transformer=transformer,
|
| 205 |
+
vae=vae,
|
| 206 |
+
tokenizer=tokenizer,
|
| 207 |
+
text_encoder=text_encoder,
|
| 208 |
+
scheduler=scheduler,
|
| 209 |
+
clip_image_encoder=clip_image_encoder
|
| 210 |
+
)
|
| 211 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 212 |
+
from functools import partial
|
| 213 |
+
transformer.enable_multi_gpus_inference()
|
| 214 |
+
if fsdp_dit:
|
| 215 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 216 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 217 |
+
print("Add FSDP DIT")
|
| 218 |
+
if fsdp_text_encoder:
|
| 219 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 220 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 221 |
+
print("Add FSDP TEXT ENCODER")
|
| 222 |
+
|
| 223 |
+
if compile_dit:
|
| 224 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 225 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 226 |
+
print("Add Compile")
|
| 227 |
+
|
| 228 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 229 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 230 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 231 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 232 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 233 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 234 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 235 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 236 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 237 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 238 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 239 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 240 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 241 |
+
pipeline.to(device=device)
|
| 242 |
+
else:
|
| 243 |
+
pipeline.to(device=device)
|
| 244 |
+
|
| 245 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 246 |
+
if coefficients is not None:
|
| 247 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 248 |
+
pipeline.transformer.enable_teacache(
|
| 249 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if cfg_skip_ratio is not None:
|
| 253 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 254 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 255 |
+
|
| 256 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 257 |
+
|
| 258 |
+
if lora_path is not None:
|
| 259 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 260 |
+
|
| 261 |
+
with torch.no_grad():
|
| 262 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 263 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 264 |
+
|
| 265 |
+
if enable_riflex:
|
| 266 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 267 |
+
|
| 268 |
+
if ref_image is not None:
|
| 269 |
+
clip_image = Image.open(ref_image).convert("RGB")
|
| 270 |
+
elif start_image is not None:
|
| 271 |
+
clip_image = Image.open(start_image).convert("RGB")
|
| 272 |
+
else:
|
| 273 |
+
clip_image = None
|
| 274 |
+
|
| 275 |
+
if ref_image is not None:
|
| 276 |
+
ref_image = get_image_latent(ref_image, sample_size=sample_size)
|
| 277 |
+
|
| 278 |
+
if start_image is not None:
|
| 279 |
+
start_image = get_image_latent(start_image, sample_size=sample_size)
|
| 280 |
+
|
| 281 |
+
if control_camera_txt is not None:
|
| 282 |
+
input_video, input_video_mask = None, None
|
| 283 |
+
control_camera_video = process_pose_file(control_camera_txt, sample_size[1], sample_size[0])
|
| 284 |
+
control_camera_video = control_camera_video[:video_length].permute([3, 0, 1, 2]).unsqueeze(0)
|
| 285 |
+
else:
|
| 286 |
+
input_video, input_video_mask, _, _ = get_video_to_video_latent(control_video, video_length=video_length, sample_size=sample_size, fps=fps, ref_image=None)
|
| 287 |
+
control_camera_video = None
|
| 288 |
+
|
| 289 |
+
sample = pipeline(
|
| 290 |
+
prompt,
|
| 291 |
+
num_frames = video_length,
|
| 292 |
+
negative_prompt = negative_prompt,
|
| 293 |
+
height = sample_size[0],
|
| 294 |
+
width = sample_size[1],
|
| 295 |
+
generator = generator,
|
| 296 |
+
guidance_scale = guidance_scale,
|
| 297 |
+
num_inference_steps = num_inference_steps,
|
| 298 |
+
|
| 299 |
+
control_video = input_video,
|
| 300 |
+
control_camera_video = control_camera_video,
|
| 301 |
+
ref_image = ref_image,
|
| 302 |
+
start_image = start_image,
|
| 303 |
+
clip_image = clip_image,
|
| 304 |
+
shift = shift,
|
| 305 |
+
).videos
|
| 306 |
+
|
| 307 |
+
if lora_path is not None:
|
| 308 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 309 |
+
|
| 310 |
+
def save_results():
|
| 311 |
+
if not os.path.exists(save_path):
|
| 312 |
+
os.makedirs(save_path, exist_ok=True)
|
| 313 |
+
|
| 314 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 315 |
+
prefix = str(index).zfill(8)
|
| 316 |
+
if video_length == 1:
|
| 317 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 318 |
+
|
| 319 |
+
image = sample[0, :, 0]
|
| 320 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 321 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 322 |
+
image = Image.fromarray(image)
|
| 323 |
+
image.save(video_path)
|
| 324 |
+
else:
|
| 325 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 326 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 327 |
+
|
| 328 |
+
if ulysses_degree * ring_degree > 1:
|
| 329 |
+
import torch.distributed as dist
|
| 330 |
+
if dist.get_rank() == 0:
|
| 331 |
+
save_results()
|
| 332 |
+
else:
|
| 333 |
+
save_results()
|
VideoX-Fun/examples/wan2.1_fun/predict_v2v_control_camera.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, AutoTokenizer, CLIPModel,
|
| 18 |
+
WanT5EncoderModel, WanTransformer3DModel)
|
| 19 |
+
from videox_fun.data.dataset_image_video import process_pose_file
|
| 20 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 21 |
+
from videox_fun.pipeline import WanFunControlPipeline, WanPipeline
|
| 22 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 23 |
+
convert_weight_dtype_wrapper,
|
| 24 |
+
replace_parameters_by_name)
|
| 25 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 26 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent, get_image_latent,
|
| 27 |
+
get_video_to_video_latent,
|
| 28 |
+
save_videos_grid)
|
| 29 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 30 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 31 |
+
|
| 32 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 33 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 34 |
+
#
|
| 35 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 36 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 41 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 42 |
+
#
|
| 43 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 44 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 45 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 46 |
+
# Multi GPUs config
|
| 47 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 48 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 49 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 50 |
+
ulysses_degree = 1
|
| 51 |
+
ring_degree = 1
|
| 52 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 53 |
+
fsdp_dit = False
|
| 54 |
+
fsdp_text_encoder = True
|
| 55 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 56 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 57 |
+
compile_dit = False
|
| 58 |
+
|
| 59 |
+
# Support TeaCache.
|
| 60 |
+
enable_teacache = True
|
| 61 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 62 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 63 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 64 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 65 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 66 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 67 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 68 |
+
teacache_threshold = 0.10
|
| 69 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 70 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 71 |
+
num_skip_start_steps = 5
|
| 72 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 73 |
+
teacache_offload = False
|
| 74 |
+
|
| 75 |
+
# Skip some cfg steps in inference
|
| 76 |
+
# Recommended to be set between 0.00 and 0.25
|
| 77 |
+
cfg_skip_ratio = 0
|
| 78 |
+
|
| 79 |
+
# Riflex config
|
| 80 |
+
enable_riflex = False
|
| 81 |
+
# Index of intrinsic frequency
|
| 82 |
+
riflex_k = 6
|
| 83 |
+
|
| 84 |
+
# Config and model path
|
| 85 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 86 |
+
# model path
|
| 87 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-Control-Camera"
|
| 88 |
+
|
| 89 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 90 |
+
sampler_name = "Flow"
|
| 91 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 92 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 93 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 94 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 95 |
+
shift = 3
|
| 96 |
+
|
| 97 |
+
# Load pretrained model if need
|
| 98 |
+
transformer_path = None
|
| 99 |
+
vae_path = None
|
| 100 |
+
lora_path = None
|
| 101 |
+
|
| 102 |
+
# Other params
|
| 103 |
+
sample_size = [480, 832]
|
| 104 |
+
video_length = 81
|
| 105 |
+
fps = 16
|
| 106 |
+
|
| 107 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 108 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 109 |
+
weight_dtype = torch.bfloat16
|
| 110 |
+
control_video = None
|
| 111 |
+
control_camera_txt = "asset/Pan_Left.txt"
|
| 112 |
+
start_image = "asset/7.png"
|
| 113 |
+
ref_image = None
|
| 114 |
+
|
| 115 |
+
# 使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性
|
| 116 |
+
# 在neg prompt中添加"安静,固定"等词语可以增加动态性。
|
| 117 |
+
prompt = "一个小女孩正在户外玩耍。她穿着一件蓝色的短袖上衣和粉色的短裤,头发扎成一个可爱的辫子。她的脚上没有穿鞋,显得非常自然和随意。她正用一把红色的小铲子在泥土里挖土,似乎在进行某种有趣的活动,可能是种花或是挖掘宝藏。地上有一根长长的水管,可能是用来浇水的。背景是一片草地和一些绿色植物,阳光明媚,整个场景充满了童趣和生机。小女孩专注的表情和认真的动作让人感受到她的快乐和好奇心。"
|
| 118 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 119 |
+
|
| 120 |
+
# Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability
|
| 121 |
+
# Adding words such as "quiet, solid" to the neg prompt can increase dynamism.
|
| 122 |
+
# prompt = "A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical."
|
| 123 |
+
# negative_prompt = "Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code."
|
| 124 |
+
guidance_scale = 6.0
|
| 125 |
+
seed = 43
|
| 126 |
+
num_inference_steps = 50
|
| 127 |
+
lora_weight = 0.55
|
| 128 |
+
save_path = "samples/wan-videos-fun-control"
|
| 129 |
+
|
| 130 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 131 |
+
config = OmegaConf.load(config_path)
|
| 132 |
+
|
| 133 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 134 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 135 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 136 |
+
low_cpu_mem_usage=True,
|
| 137 |
+
torch_dtype=weight_dtype,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if transformer_path is not None:
|
| 141 |
+
print(f"From checkpoint: {transformer_path}")
|
| 142 |
+
if transformer_path.endswith("safetensors"):
|
| 143 |
+
from safetensors.torch import load_file, safe_open
|
| 144 |
+
state_dict = load_file(transformer_path)
|
| 145 |
+
else:
|
| 146 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 147 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 148 |
+
|
| 149 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 150 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 151 |
+
|
| 152 |
+
# Get Vae
|
| 153 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 154 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 155 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 156 |
+
).to(weight_dtype)
|
| 157 |
+
|
| 158 |
+
if vae_path is not None:
|
| 159 |
+
print(f"From checkpoint: {vae_path}")
|
| 160 |
+
if vae_path.endswith("safetensors"):
|
| 161 |
+
from safetensors.torch import load_file, safe_open
|
| 162 |
+
state_dict = load_file(vae_path)
|
| 163 |
+
else:
|
| 164 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 165 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 166 |
+
|
| 167 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 168 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 169 |
+
|
| 170 |
+
# Get Tokenizer
|
| 171 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 172 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Get Text encoder
|
| 176 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 177 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 178 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 179 |
+
low_cpu_mem_usage=True,
|
| 180 |
+
torch_dtype=weight_dtype,
|
| 181 |
+
)
|
| 182 |
+
text_encoder = text_encoder.eval()
|
| 183 |
+
|
| 184 |
+
# Get Clip Image Encoder
|
| 185 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 186 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 187 |
+
).to(weight_dtype)
|
| 188 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 189 |
+
|
| 190 |
+
# Get Scheduler
|
| 191 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 192 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 193 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 194 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 195 |
+
}[sampler_name]
|
| 196 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 197 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 198 |
+
scheduler = Chosen_Scheduler(
|
| 199 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Get Pipeline
|
| 203 |
+
pipeline = WanFunControlPipeline(
|
| 204 |
+
transformer=transformer,
|
| 205 |
+
vae=vae,
|
| 206 |
+
tokenizer=tokenizer,
|
| 207 |
+
text_encoder=text_encoder,
|
| 208 |
+
scheduler=scheduler,
|
| 209 |
+
clip_image_encoder=clip_image_encoder
|
| 210 |
+
)
|
| 211 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 212 |
+
from functools import partial
|
| 213 |
+
transformer.enable_multi_gpus_inference()
|
| 214 |
+
if fsdp_dit:
|
| 215 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 216 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 217 |
+
print("Add FSDP DIT")
|
| 218 |
+
if fsdp_text_encoder:
|
| 219 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 220 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 221 |
+
print("Add FSDP TEXT ENCODER")
|
| 222 |
+
|
| 223 |
+
if compile_dit:
|
| 224 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 225 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 226 |
+
print("Add Compile")
|
| 227 |
+
|
| 228 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 229 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 230 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 231 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 232 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 233 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 234 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 235 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 236 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 237 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 238 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 239 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 240 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 241 |
+
pipeline.to(device=device)
|
| 242 |
+
else:
|
| 243 |
+
pipeline.to(device=device)
|
| 244 |
+
|
| 245 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 246 |
+
if coefficients is not None:
|
| 247 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 248 |
+
pipeline.transformer.enable_teacache(
|
| 249 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if cfg_skip_ratio is not None:
|
| 253 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 254 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 255 |
+
|
| 256 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 257 |
+
|
| 258 |
+
if lora_path is not None:
|
| 259 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 260 |
+
|
| 261 |
+
with torch.no_grad():
|
| 262 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 263 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 264 |
+
|
| 265 |
+
if enable_riflex:
|
| 266 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 267 |
+
|
| 268 |
+
if ref_image is not None:
|
| 269 |
+
clip_image = Image.open(ref_image).convert("RGB")
|
| 270 |
+
elif start_image is not None:
|
| 271 |
+
clip_image = Image.open(start_image).convert("RGB")
|
| 272 |
+
else:
|
| 273 |
+
clip_image = None
|
| 274 |
+
|
| 275 |
+
if ref_image is not None:
|
| 276 |
+
ref_image = get_image_latent(ref_image, sample_size=sample_size)
|
| 277 |
+
|
| 278 |
+
if start_image is not None:
|
| 279 |
+
start_image = get_image_latent(start_image, sample_size=sample_size)
|
| 280 |
+
|
| 281 |
+
if control_camera_txt is not None:
|
| 282 |
+
input_video, input_video_mask = None, None
|
| 283 |
+
control_camera_video = process_pose_file(control_camera_txt, sample_size[1], sample_size[0])
|
| 284 |
+
control_camera_video = control_camera_video[:video_length].permute([3, 0, 1, 2]).unsqueeze(0)
|
| 285 |
+
else:
|
| 286 |
+
input_video, input_video_mask, _, _ = get_video_to_video_latent(control_video, video_length=video_length, sample_size=sample_size, fps=fps, ref_image=None)
|
| 287 |
+
control_camera_video = None
|
| 288 |
+
|
| 289 |
+
sample = pipeline(
|
| 290 |
+
prompt,
|
| 291 |
+
num_frames = video_length,
|
| 292 |
+
negative_prompt = negative_prompt,
|
| 293 |
+
height = sample_size[0],
|
| 294 |
+
width = sample_size[1],
|
| 295 |
+
generator = generator,
|
| 296 |
+
guidance_scale = guidance_scale,
|
| 297 |
+
num_inference_steps = num_inference_steps,
|
| 298 |
+
|
| 299 |
+
control_video = input_video,
|
| 300 |
+
control_camera_video = control_camera_video,
|
| 301 |
+
ref_image = ref_image,
|
| 302 |
+
start_image = start_image,
|
| 303 |
+
clip_image = clip_image,
|
| 304 |
+
shift = shift,
|
| 305 |
+
).videos
|
| 306 |
+
|
| 307 |
+
if lora_path is not None:
|
| 308 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 309 |
+
|
| 310 |
+
def save_results():
|
| 311 |
+
if not os.path.exists(save_path):
|
| 312 |
+
os.makedirs(save_path, exist_ok=True)
|
| 313 |
+
|
| 314 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 315 |
+
prefix = str(index).zfill(8)
|
| 316 |
+
if video_length == 1:
|
| 317 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 318 |
+
|
| 319 |
+
image = sample[0, :, 0]
|
| 320 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 321 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 322 |
+
image = Image.fromarray(image)
|
| 323 |
+
image.save(video_path)
|
| 324 |
+
else:
|
| 325 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 326 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 327 |
+
|
| 328 |
+
if ulysses_degree * ring_degree > 1:
|
| 329 |
+
import torch.distributed as dist
|
| 330 |
+
if dist.get_rank() == 0:
|
| 331 |
+
save_results()
|
| 332 |
+
else:
|
| 333 |
+
save_results()
|
VideoX-Fun/examples/wan2.1_fun/predict_v2v_control_ref.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
|
| 11 |
+
current_file_path = os.path.abspath(__file__)
|
| 12 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 13 |
+
for project_root in project_roots:
|
| 14 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 15 |
+
|
| 16 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 17 |
+
from videox_fun.models import (AutoencoderKLWan, AutoTokenizer, CLIPModel,
|
| 18 |
+
WanT5EncoderModel, WanTransformer3DModel)
|
| 19 |
+
from videox_fun.data.dataset_image_video import process_pose_file
|
| 20 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 21 |
+
from videox_fun.pipeline import WanFunControlPipeline, WanPipeline
|
| 22 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8,
|
| 23 |
+
convert_weight_dtype_wrapper,
|
| 24 |
+
replace_parameters_by_name)
|
| 25 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 26 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent, get_image_latent,
|
| 27 |
+
get_video_to_video_latent,
|
| 28 |
+
save_videos_grid)
|
| 29 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 30 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 31 |
+
|
| 32 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 33 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 34 |
+
#
|
| 35 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 36 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 37 |
+
#
|
| 38 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 39 |
+
#
|
| 40 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 41 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 42 |
+
#
|
| 43 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 44 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 45 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 46 |
+
# Multi GPUs config
|
| 47 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 48 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 49 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 50 |
+
ulysses_degree = 1
|
| 51 |
+
ring_degree = 1
|
| 52 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 53 |
+
fsdp_dit = False
|
| 54 |
+
fsdp_text_encoder = True
|
| 55 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 56 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 57 |
+
compile_dit = False
|
| 58 |
+
|
| 59 |
+
# Support TeaCache.
|
| 60 |
+
enable_teacache = True
|
| 61 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 62 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 63 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 64 |
+
# | Model Name | threshold | Model Name | threshold | Model Name | threshold |
|
| 65 |
+
# | Wan2.1-T2V-1.3B | 0.05~0.10 | Wan2.1-T2V-14B | 0.10~0.15 | Wan2.1-I2V-14B-720P | 0.20~0.30 |
|
| 66 |
+
# | Wan2.1-I2V-14B-480P | 0.20~0.25 | Wan2.1-Fun-*-1.3B-* | 0.05~0.10 | Wan2.1-Fun-*-14B-* | 0.20~0.30 |
|
| 67 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 68 |
+
teacache_threshold = 0.10
|
| 69 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 70 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 71 |
+
num_skip_start_steps = 5
|
| 72 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 73 |
+
teacache_offload = False
|
| 74 |
+
|
| 75 |
+
# Skip some cfg steps in inference for acceleration
|
| 76 |
+
# Recommended to be set between 0.00 and 0.25
|
| 77 |
+
cfg_skip_ratio = 0
|
| 78 |
+
|
| 79 |
+
# Riflex config
|
| 80 |
+
enable_riflex = False
|
| 81 |
+
# Index of intrinsic frequency
|
| 82 |
+
riflex_k = 6
|
| 83 |
+
|
| 84 |
+
# Config and model path
|
| 85 |
+
config_path = "config/wan2.1/wan_civitai.yaml"
|
| 86 |
+
# model path
|
| 87 |
+
model_name = "models/Diffusion_Transformer/Wan2.1-Fun-V1.1-1.3B-Control"
|
| 88 |
+
|
| 89 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 90 |
+
sampler_name = "Flow"
|
| 91 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 92 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 93 |
+
# If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
|
| 94 |
+
# If you want to generate a 720p video, it is recommended to set the shift value to 5.0.
|
| 95 |
+
shift = 3
|
| 96 |
+
|
| 97 |
+
# Load pretrained model if need
|
| 98 |
+
transformer_path = None
|
| 99 |
+
vae_path = None
|
| 100 |
+
lora_path = None
|
| 101 |
+
|
| 102 |
+
# Other params
|
| 103 |
+
sample_size = [832, 480]
|
| 104 |
+
video_length = 49
|
| 105 |
+
fps = 16
|
| 106 |
+
|
| 107 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 108 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 109 |
+
weight_dtype = torch.bfloat16
|
| 110 |
+
control_video = "asset/pose.mp4"
|
| 111 |
+
control_camera_txt = None
|
| 112 |
+
start_image = None
|
| 113 |
+
ref_image = "asset/6.png"
|
| 114 |
+
|
| 115 |
+
# 使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性
|
| 116 |
+
# 在neg prompt中添加"安静,固定"等词语可以增加动态性。
|
| 117 |
+
prompt = "一位年轻女性穿着一件粉色的连衣裙,裙子上有白色的装饰和粉色的纽扣。她的头发是紫色的,头上戴着一个红色的大蝴蝶结,显得非常可爱和精致。她还戴着一个红色的领结,整体造型充满了少女感和活力。她的表情温柔,双手轻轻交叉放在身前,姿态优雅。背景是简单的灰色,没有任何多余的装饰,使得人物更加突出。她的妆容清淡自然,突显了她的清新气质。整体画面给人一种甜美、梦幻的感觉,仿佛置身于童话世界中。"
|
| 118 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 119 |
+
|
| 120 |
+
# Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability
|
| 121 |
+
# Adding words such as "quiet, solid" to the neg prompt can increase dynamism.
|
| 122 |
+
# prompt = "A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical."
|
| 123 |
+
# negative_prompt = "Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code."
|
| 124 |
+
guidance_scale = 6.0
|
| 125 |
+
seed = 43
|
| 126 |
+
num_inference_steps = 50
|
| 127 |
+
lora_weight = 0.55
|
| 128 |
+
save_path = "samples/wan-videos-fun-control"
|
| 129 |
+
|
| 130 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 131 |
+
config = OmegaConf.load(config_path)
|
| 132 |
+
|
| 133 |
+
transformer = WanTransformer3DModel.from_pretrained(
|
| 134 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
|
| 135 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 136 |
+
low_cpu_mem_usage=True,
|
| 137 |
+
torch_dtype=weight_dtype,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if transformer_path is not None:
|
| 141 |
+
print(f"From checkpoint: {transformer_path}")
|
| 142 |
+
if transformer_path.endswith("safetensors"):
|
| 143 |
+
from safetensors.torch import load_file, safe_open
|
| 144 |
+
state_dict = load_file(transformer_path)
|
| 145 |
+
else:
|
| 146 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 147 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 148 |
+
|
| 149 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 150 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 151 |
+
|
| 152 |
+
# Get Vae
|
| 153 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 154 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 155 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 156 |
+
).to(weight_dtype)
|
| 157 |
+
|
| 158 |
+
if vae_path is not None:
|
| 159 |
+
print(f"From checkpoint: {vae_path}")
|
| 160 |
+
if vae_path.endswith("safetensors"):
|
| 161 |
+
from safetensors.torch import load_file, safe_open
|
| 162 |
+
state_dict = load_file(vae_path)
|
| 163 |
+
else:
|
| 164 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 165 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 166 |
+
|
| 167 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 168 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 169 |
+
|
| 170 |
+
# Get Tokenizer
|
| 171 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 172 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Get Text encoder
|
| 176 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 177 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 178 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 179 |
+
low_cpu_mem_usage=True,
|
| 180 |
+
torch_dtype=weight_dtype,
|
| 181 |
+
)
|
| 182 |
+
text_encoder = text_encoder.eval()
|
| 183 |
+
|
| 184 |
+
# Get Clip Image Encoder
|
| 185 |
+
clip_image_encoder = CLIPModel.from_pretrained(
|
| 186 |
+
os.path.join(model_name, config['image_encoder_kwargs'].get('image_encoder_subpath', 'image_encoder')),
|
| 187 |
+
).to(weight_dtype)
|
| 188 |
+
clip_image_encoder = clip_image_encoder.eval()
|
| 189 |
+
|
| 190 |
+
# Get Scheduler
|
| 191 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 192 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 193 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 194 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 195 |
+
}[sampler_name]
|
| 196 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 197 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 198 |
+
scheduler = Chosen_Scheduler(
|
| 199 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Get Pipeline
|
| 203 |
+
pipeline = WanFunControlPipeline(
|
| 204 |
+
transformer=transformer,
|
| 205 |
+
vae=vae,
|
| 206 |
+
tokenizer=tokenizer,
|
| 207 |
+
text_encoder=text_encoder,
|
| 208 |
+
scheduler=scheduler,
|
| 209 |
+
clip_image_encoder=clip_image_encoder
|
| 210 |
+
)
|
| 211 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 212 |
+
from functools import partial
|
| 213 |
+
transformer.enable_multi_gpus_inference()
|
| 214 |
+
if fsdp_dit:
|
| 215 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 216 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 217 |
+
print("Add FSDP DIT")
|
| 218 |
+
if fsdp_text_encoder:
|
| 219 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 220 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 221 |
+
print("Add FSDP TEXT ENCODER")
|
| 222 |
+
|
| 223 |
+
if compile_dit:
|
| 224 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 225 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 226 |
+
print("Add Compile")
|
| 227 |
+
|
| 228 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 229 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 230 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 231 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 232 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 233 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 234 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 235 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 236 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 237 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 238 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 239 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 240 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 241 |
+
pipeline.to(device=device)
|
| 242 |
+
else:
|
| 243 |
+
pipeline.to(device=device)
|
| 244 |
+
|
| 245 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 246 |
+
if coefficients is not None:
|
| 247 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 248 |
+
pipeline.transformer.enable_teacache(
|
| 249 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if cfg_skip_ratio is not None:
|
| 253 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 254 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 255 |
+
|
| 256 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 257 |
+
|
| 258 |
+
if lora_path is not None:
|
| 259 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 260 |
+
|
| 261 |
+
with torch.no_grad():
|
| 262 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 263 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 264 |
+
|
| 265 |
+
if enable_riflex:
|
| 266 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 267 |
+
|
| 268 |
+
if ref_image is not None:
|
| 269 |
+
clip_image = Image.open(ref_image).convert("RGB")
|
| 270 |
+
elif start_image is not None:
|
| 271 |
+
clip_image = Image.open(start_image).convert("RGB")
|
| 272 |
+
else:
|
| 273 |
+
clip_image = None
|
| 274 |
+
|
| 275 |
+
if ref_image is not None:
|
| 276 |
+
ref_image = get_image_latent(ref_image, sample_size=sample_size)
|
| 277 |
+
|
| 278 |
+
if start_image is not None:
|
| 279 |
+
start_image = get_image_latent(start_image, sample_size=sample_size)
|
| 280 |
+
|
| 281 |
+
if control_camera_txt is not None:
|
| 282 |
+
input_video, input_video_mask = None, None
|
| 283 |
+
control_camera_video = process_pose_file(control_camera_txt, sample_size[1], sample_size[0])
|
| 284 |
+
control_camera_video = control_camera_video[:video_length].permute([3, 0, 1, 2]).unsqueeze(0)
|
| 285 |
+
else:
|
| 286 |
+
input_video, input_video_mask, _, _ = get_video_to_video_latent(control_video, video_length=video_length, sample_size=sample_size, fps=fps, ref_image=None)
|
| 287 |
+
control_camera_video = None
|
| 288 |
+
|
| 289 |
+
sample = pipeline(
|
| 290 |
+
prompt,
|
| 291 |
+
num_frames = video_length,
|
| 292 |
+
negative_prompt = negative_prompt,
|
| 293 |
+
height = sample_size[0],
|
| 294 |
+
width = sample_size[1],
|
| 295 |
+
generator = generator,
|
| 296 |
+
guidance_scale = guidance_scale,
|
| 297 |
+
num_inference_steps = num_inference_steps,
|
| 298 |
+
|
| 299 |
+
control_video = input_video,
|
| 300 |
+
control_camera_video = control_camera_video,
|
| 301 |
+
ref_image = ref_image,
|
| 302 |
+
start_image = start_image,
|
| 303 |
+
clip_image = clip_image,
|
| 304 |
+
shift = shift,
|
| 305 |
+
).videos
|
| 306 |
+
|
| 307 |
+
if lora_path is not None:
|
| 308 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 309 |
+
|
| 310 |
+
def save_results():
|
| 311 |
+
if not os.path.exists(save_path):
|
| 312 |
+
os.makedirs(save_path, exist_ok=True)
|
| 313 |
+
|
| 314 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 315 |
+
prefix = str(index).zfill(8)
|
| 316 |
+
if video_length == 1:
|
| 317 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 318 |
+
|
| 319 |
+
image = sample[0, :, 0]
|
| 320 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 321 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 322 |
+
image = Image.fromarray(image)
|
| 323 |
+
image.save(video_path)
|
| 324 |
+
else:
|
| 325 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 326 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 327 |
+
|
| 328 |
+
if ulysses_degree * ring_degree > 1:
|
| 329 |
+
import torch.distributed as dist
|
| 330 |
+
if dist.get_rank() == 0:
|
| 331 |
+
save_results()
|
| 332 |
+
else:
|
| 333 |
+
save_results()
|
VideoX-Fun/examples/wan2.2/app.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.api.api import (infer_forward_api,
|
| 13 |
+
update_diffusion_transformer_api)
|
| 14 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 15 |
+
from videox_fun.ui.wan2_2_ui import ui, ui_client, ui_host
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
# Choose the ui mode
|
| 19 |
+
# "normal" refers to the standard UI, which allows users to click to switch models, change model types, and more.
|
| 20 |
+
# "host" represents the hosting mode, where the model is loaded directly at startup and can be accessed via
|
| 21 |
+
# the API to return generation results.
|
| 22 |
+
# "client" represents the client mode, offering a simple UI that sends requests to a remote API for generation.
|
| 23 |
+
ui_mode = "normal"
|
| 24 |
+
|
| 25 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 26 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
#
|
| 28 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 31 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 32 |
+
#
|
| 33 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 34 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 35 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 36 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 37 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 38 |
+
compile_dit = False
|
| 39 |
+
|
| 40 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 41 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 42 |
+
weight_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# Server ip
|
| 45 |
+
server_name = "0.0.0.0"
|
| 46 |
+
server_port = 7860
|
| 47 |
+
|
| 48 |
+
# Config path
|
| 49 |
+
config_path = "config/wan2.2/wan_civitai_i2v.yaml"
|
| 50 |
+
# Params below is used when ui_mode = "host"
|
| 51 |
+
# Model path of the pretrained model
|
| 52 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-I2V-A14B"
|
| 53 |
+
# "Inpaint" or "Control"
|
| 54 |
+
model_type = "Inpaint"
|
| 55 |
+
|
| 56 |
+
if ui_mode == "host":
|
| 57 |
+
demo, controller = ui_host(GPU_memory_mode, flow_scheduler_dict, model_name, model_type, config_path, compile_dit, weight_dtype)
|
| 58 |
+
elif ui_mode == "client":
|
| 59 |
+
demo, controller = ui_client(flow_scheduler_dict, model_name)
|
| 60 |
+
else:
|
| 61 |
+
demo, controller = ui(GPU_memory_mode, flow_scheduler_dict, config_path, compile_dit, weight_dtype)
|
| 62 |
+
|
| 63 |
+
def gr_launch():
|
| 64 |
+
# launch gradio
|
| 65 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 66 |
+
server_name=server_name,
|
| 67 |
+
server_port=server_port,
|
| 68 |
+
prevent_thread_lock=True
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# launch api
|
| 72 |
+
infer_forward_api(None, app, controller)
|
| 73 |
+
update_diffusion_transformer_api(None, app, controller)
|
| 74 |
+
|
| 75 |
+
gr_launch()
|
| 76 |
+
|
| 77 |
+
# not close the python
|
| 78 |
+
while True:
|
| 79 |
+
time.sleep(5)
|
VideoX-Fun/examples/wan2.2/launch_api.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import ray
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.api.api_multi_nodes import (MultiNodesEngine,
|
| 16 |
+
multi_nodes_infer_forward_api)
|
| 17 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 18 |
+
from videox_fun.ui.wan2_2_ui import Wan2_2_Controller
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description='xDiT HTTP Service')
|
| 22 |
+
parser.add_argument('--world_size', type=int, default=8, help='Number of parallel workers')
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
'--gpu_memory_mode', type=str, default="model_full_load", help='''
|
| 25 |
+
GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8].
|
| 26 |
+
model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
|
| 28 |
+
model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 29 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 30 |
+
|
| 31 |
+
model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 32 |
+
|
| 33 |
+
model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 34 |
+
and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 35 |
+
'''
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument('--ulysses_degree', type=int, default=4, help='Degree of Ulysses configuration')
|
| 38 |
+
parser.add_argument('--ring_degree', type=int, default=2, help='Degree of Ring configuration')
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
'--compile_dit', action='store_true', help='''
|
| 41 |
+
Enable compile dit.
|
| 42 |
+
Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 43 |
+
The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 44 |
+
'''
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument('--fsdp_dit', action='store_true', help="Use DIT FSDP to save more GPU memory in multi gpus.")
|
| 47 |
+
parser.add_argument('--fsdp_text_encoder', action='store_true', help="Use Text Encoder FSDP to save more GPU memory in multi gpus.")
|
| 48 |
+
parser.add_argument('--weight_dtype', type=str, default='bf16', help='Weight data type')
|
| 49 |
+
parser.add_argument('--server_name', type=str, default="0.0.0.0", help='Server IP address')
|
| 50 |
+
parser.add_argument('--server_port', type=int, default=7860, help='Server Port')
|
| 51 |
+
parser.add_argument('--config_path', type=str, default="config/wan2.2/wan_civitai_i2v.yaml", help='Path to config file')
|
| 52 |
+
parser.add_argument('--model_name', type=str, default="models/Diffusion_Transformer/Wan2.2-I2V-A14B", help='Model path')
|
| 53 |
+
parser.add_argument('--model_type', type=str, default="Inpaint", help='Model type (Inpaint/Control)')
|
| 54 |
+
parser.add_argument('--savedir_sample', type=str, default=None, help='The save directory for samples')
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
weight_dtype = torch.float32
|
| 58 |
+
if args.weight_dtype == "bf16":
|
| 59 |
+
weight_dtype = torch.bfloat16
|
| 60 |
+
elif args.weight_dtype == "fp16":
|
| 61 |
+
weight_dtype = torch.float16
|
| 62 |
+
|
| 63 |
+
engine = MultiNodesEngine(
|
| 64 |
+
world_size=args.world_size, Controller=Wan2_2_Controller,
|
| 65 |
+
GPU_memory_mode=args.gpu_memory_mode, scheduler_dict=flow_scheduler_dict, model_name=args.model_name, model_type=args.model_type, config_path=args.config_path,
|
| 66 |
+
ulysses_degree=args.ulysses_degree, ring_degree=args.ring_degree,
|
| 67 |
+
fsdp_dit=args.fsdp_dit, fsdp_text_encoder=args.fsdp_text_encoder, compile_dit=args.compile_dit,
|
| 68 |
+
weight_dtype=weight_dtype, savedir_sample=args.savedir_sample,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def gr_launch():
|
| 72 |
+
# launch gradio
|
| 73 |
+
with gr.Blocks() as demo:
|
| 74 |
+
gr.Markdown("")
|
| 75 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 76 |
+
server_name=args.server_name,
|
| 77 |
+
server_port=args.server_port,
|
| 78 |
+
prevent_thread_lock=True
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# launch api
|
| 82 |
+
multi_nodes_infer_forward_api(None, app, engine)
|
| 83 |
+
|
| 84 |
+
gr_launch()
|
| 85 |
+
|
| 86 |
+
# not close the python
|
| 87 |
+
while True:
|
| 88 |
+
time.sleep(5)
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|
VideoX-Fun/examples/wan2.2/post_infer.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def post_diffusion_transformer(diffusion_transformer_path, url='http://127.0.0.1:7860'):
|
| 12 |
+
datas = json.dumps({
|
| 13 |
+
"diffusion_transformer_path": diffusion_transformer_path
|
| 14 |
+
})
|
| 15 |
+
r = requests.post(f'{url}/videox_fun/update_diffusion_transformer', data=datas, timeout=1500)
|
| 16 |
+
data = r.content.decode('utf-8')
|
| 17 |
+
return data
|
| 18 |
+
|
| 19 |
+
def post_update_edition(edition, url='http://0.0.0.0:7860'):
|
| 20 |
+
datas = json.dumps({
|
| 21 |
+
"edition": edition
|
| 22 |
+
})
|
| 23 |
+
r = requests.post(f'{url}/videox_fun/update_edition', data=datas, timeout=1500)
|
| 24 |
+
data = r.content.decode('utf-8')
|
| 25 |
+
return data
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def post_infer(
|
| 29 |
+
generation_method,
|
| 30 |
+
length_slider,
|
| 31 |
+
url='http://127.0.0.1:7860',
|
| 32 |
+
POST_TOKEN="",
|
| 33 |
+
timeout=5000,
|
| 34 |
+
base_model_path="none",
|
| 35 |
+
lora_model_path="none",
|
| 36 |
+
lora_alpha_slider=0.55,
|
| 37 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 38 |
+
negative_prompt_textbox="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion.",
|
| 39 |
+
sampler_dropdown="Flow",
|
| 40 |
+
sample_step_slider=50,
|
| 41 |
+
width_slider=672,
|
| 42 |
+
height_slider=384,
|
| 43 |
+
cfg_scale_slider=6,
|
| 44 |
+
seed_textbox=43,
|
| 45 |
+
start_image = None
|
| 46 |
+
):
|
| 47 |
+
if start_image:
|
| 48 |
+
try:
|
| 49 |
+
if not start_image.startswith("http"):
|
| 50 |
+
image = Image.open(start_image).convert("RGB")
|
| 51 |
+
# 将图片转换为 Base64 编码
|
| 52 |
+
buffered = BytesIO()
|
| 53 |
+
image.save(buffered, format="JPEG")
|
| 54 |
+
start_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error processing start_image: {e}")
|
| 57 |
+
raise
|
| 58 |
+
|
| 59 |
+
# Prepare the data payload
|
| 60 |
+
datas = json.dumps({
|
| 61 |
+
"base_model_path": base_model_path,
|
| 62 |
+
"lora_model_path": lora_model_path,
|
| 63 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 64 |
+
"prompt_textbox": prompt_textbox,
|
| 65 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 66 |
+
"sampler_dropdown": sampler_dropdown,
|
| 67 |
+
"sample_step_slider": sample_step_slider,
|
| 68 |
+
"width_slider": width_slider,
|
| 69 |
+
"height_slider": height_slider,
|
| 70 |
+
"generation_method": generation_method,
|
| 71 |
+
"length_slider": length_slider,
|
| 72 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 73 |
+
"seed_textbox": seed_textbox,
|
| 74 |
+
|
| 75 |
+
"start_image": start_image
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
# Initialize session and set headers
|
| 79 |
+
session = requests.session()
|
| 80 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 81 |
+
|
| 82 |
+
# Send POST request
|
| 83 |
+
if url[-1] == "/":
|
| 84 |
+
url = url[:-1]
|
| 85 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 86 |
+
|
| 87 |
+
data = post_r.content.decode('utf-8')
|
| 88 |
+
return data
|
| 89 |
+
|
| 90 |
+
if __name__ == '__main__':
|
| 91 |
+
# initiate time
|
| 92 |
+
time_start = time.time()
|
| 93 |
+
|
| 94 |
+
# The Url you want to post
|
| 95 |
+
POST_URL = 'http://0.0.0.0:7860'
|
| 96 |
+
# Used in EAS. If you don't need Authorization, please set it to empty string.
|
| 97 |
+
TOKEN = ''
|
| 98 |
+
|
| 99 |
+
# -------------------------- #
|
| 100 |
+
# Step 1: update edition
|
| 101 |
+
# -------------------------- #
|
| 102 |
+
# diffusion_transformer_path = "models/Diffusion_Transformer/Wan2.2-I2V-A14B"
|
| 103 |
+
# outputs = post_diffusion_transformer(diffusion_transformer_path)
|
| 104 |
+
# print('Output update edition: ', outputs)
|
| 105 |
+
|
| 106 |
+
# -------------------------- #
|
| 107 |
+
# Step 2: infer
|
| 108 |
+
# -------------------------- #
|
| 109 |
+
# "Video Generation" and "Image Generation"
|
| 110 |
+
generation_method = "Video Generation"
|
| 111 |
+
# Video length
|
| 112 |
+
length_slider = 49
|
| 113 |
+
# Used in Lora models
|
| 114 |
+
lora_model_path = "none"
|
| 115 |
+
lora_alpha_slider = 0.55
|
| 116 |
+
# Prompts
|
| 117 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 118 |
+
negative_prompt_textbox = "The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 119 |
+
# Sampler name
|
| 120 |
+
sampler_dropdown = "Flow"
|
| 121 |
+
# Sampler steps
|
| 122 |
+
sample_step_slider = 50
|
| 123 |
+
# height and width
|
| 124 |
+
width_slider = 832
|
| 125 |
+
height_slider = 480
|
| 126 |
+
# cfg scale
|
| 127 |
+
cfg_scale_slider = 6
|
| 128 |
+
seed_textbox = 43
|
| 129 |
+
# 起始图片路径
|
| 130 |
+
start_image_path = "asset/3.png" # 替换为实际的图片路径
|
| 131 |
+
|
| 132 |
+
outputs = post_infer(
|
| 133 |
+
generation_method,
|
| 134 |
+
length_slider,
|
| 135 |
+
lora_model_path=lora_model_path,
|
| 136 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 137 |
+
prompt_textbox=prompt_textbox,
|
| 138 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 139 |
+
sampler_dropdown=sampler_dropdown,
|
| 140 |
+
sample_step_slider=sample_step_slider,
|
| 141 |
+
width_slider=width_slider,
|
| 142 |
+
height_slider=height_slider,
|
| 143 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 144 |
+
seed_textbox=seed_textbox,
|
| 145 |
+
url=POST_URL,
|
| 146 |
+
POST_TOKEN=TOKEN,
|
| 147 |
+
start_image=start_image_path
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Get decoded data
|
| 151 |
+
outputs = json.loads(outputs)
|
| 152 |
+
base64_encoding = outputs["base64_encoding"]
|
| 153 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 154 |
+
|
| 155 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 156 |
+
if is_image or length_slider == 1:
|
| 157 |
+
file_path = "1.png"
|
| 158 |
+
else:
|
| 159 |
+
file_path = "1.mp4"
|
| 160 |
+
with open(file_path, "wb") as file:
|
| 161 |
+
file.write(decoded_data)
|
| 162 |
+
|
| 163 |
+
# End of record time
|
| 164 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 165 |
+
time_end = time.time()
|
| 166 |
+
time_sum = (time_end - time_start)
|
| 167 |
+
print('# --------------------------------------------------------- #')
|
| 168 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 169 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.2/post_infer_queue.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def post_infer(
|
| 9 |
+
generation_method,
|
| 10 |
+
length_slider,
|
| 11 |
+
url='http://127.0.0.1:7860',
|
| 12 |
+
POST_TOKEN="",
|
| 13 |
+
timeout=5,
|
| 14 |
+
base_model_path="none",
|
| 15 |
+
lora_model_path="none",
|
| 16 |
+
lora_alpha_slider=0.55,
|
| 17 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 18 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 19 |
+
sampler_dropdown="Flow",
|
| 20 |
+
sample_step_slider=50,
|
| 21 |
+
width_slider=672,
|
| 22 |
+
height_slider=384,
|
| 23 |
+
cfg_scale_slider=6,
|
| 24 |
+
seed_textbox=43,
|
| 25 |
+
enable_teacache = None,
|
| 26 |
+
teacache_threshold = None,
|
| 27 |
+
num_skip_start_steps = None,
|
| 28 |
+
teacache_offload = None,
|
| 29 |
+
cfg_skip_ratio = None,
|
| 30 |
+
enable_riflex = None,
|
| 31 |
+
riflex_k = None,
|
| 32 |
+
):
|
| 33 |
+
# Prepare the data payload
|
| 34 |
+
datas = json.dumps({
|
| 35 |
+
"base_model_path": base_model_path,
|
| 36 |
+
"lora_model_path": lora_model_path,
|
| 37 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 38 |
+
"prompt_textbox": prompt_textbox,
|
| 39 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 40 |
+
"sampler_dropdown": sampler_dropdown,
|
| 41 |
+
"sample_step_slider": sample_step_slider,
|
| 42 |
+
"width_slider": width_slider,
|
| 43 |
+
"height_slider": height_slider,
|
| 44 |
+
"generation_method": generation_method,
|
| 45 |
+
"length_slider": length_slider,
|
| 46 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 47 |
+
"seed_textbox": seed_textbox,
|
| 48 |
+
|
| 49 |
+
"enable_teacache": enable_teacache,
|
| 50 |
+
"teacache_threshold": teacache_threshold,
|
| 51 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 52 |
+
"teacache_offload": teacache_offload,
|
| 53 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 54 |
+
"enable_riflex": enable_riflex,
|
| 55 |
+
"riflex_k": riflex_k,
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
# Initialize session and set headers
|
| 59 |
+
session = requests.session()
|
| 60 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 61 |
+
|
| 62 |
+
# Send POST request
|
| 63 |
+
if url[-1] == "/":
|
| 64 |
+
url = url[:-1]
|
| 65 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 66 |
+
|
| 67 |
+
# Extract request ID from POST response headers
|
| 68 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 69 |
+
|
| 70 |
+
# Prepare query parameters for GET request
|
| 71 |
+
query = {
|
| 72 |
+
'_index_': '0',
|
| 73 |
+
'_length_': '1',
|
| 74 |
+
'_timeout_': str(timeout),
|
| 75 |
+
'_raw_': 'false',
|
| 76 |
+
'_auto_delete_': 'true',
|
| 77 |
+
}
|
| 78 |
+
if request_id:
|
| 79 |
+
query['requestId'] = request_id
|
| 80 |
+
|
| 81 |
+
query_str = urllib.parse.urlencode(query)
|
| 82 |
+
|
| 83 |
+
# Polling GET request until status code is not 204
|
| 84 |
+
status_code = 204
|
| 85 |
+
while status_code == 204:
|
| 86 |
+
if query_str:
|
| 87 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 88 |
+
else:
|
| 89 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 90 |
+
status_code = get_r.status_code
|
| 91 |
+
# Decode and return the response content
|
| 92 |
+
data = get_r.content.decode('utf-8')
|
| 93 |
+
return data
|
| 94 |
+
|
| 95 |
+
if __name__ == '__main__':
|
| 96 |
+
# initiate time
|
| 97 |
+
time_start = time.time()
|
| 98 |
+
|
| 99 |
+
# EAS队列配置
|
| 100 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 101 |
+
# Use in EAS Queue
|
| 102 |
+
TOKEN = 'xxxxxxxx'
|
| 103 |
+
|
| 104 |
+
# Support TeaCache.
|
| 105 |
+
enable_teacache = True
|
| 106 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 107 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 108 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 109 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 110 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 111 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 112 |
+
teacache_threshold = 0.10
|
| 113 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 114 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 115 |
+
num_skip_start_steps = 5
|
| 116 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 117 |
+
teacache_offload = False
|
| 118 |
+
|
| 119 |
+
# Skip some cfg steps in inference
|
| 120 |
+
# Recommended to be set between 0.00 and 0.25
|
| 121 |
+
cfg_skip_ratio = 0
|
| 122 |
+
|
| 123 |
+
# Riflex config
|
| 124 |
+
enable_riflex = False
|
| 125 |
+
# Index of intrinsic frequency
|
| 126 |
+
riflex_k = 6
|
| 127 |
+
|
| 128 |
+
# "Video Generation" and "Image Generation"
|
| 129 |
+
generation_method = "Video Generation"
|
| 130 |
+
# Video length
|
| 131 |
+
length_slider = 81
|
| 132 |
+
# Used in Lora models
|
| 133 |
+
lora_model_path = "none"
|
| 134 |
+
lora_alpha_slider = 0.55
|
| 135 |
+
# Prompts
|
| 136 |
+
prompt_textbox = "A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic."
|
| 137 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 138 |
+
# Sampler name
|
| 139 |
+
sampler_dropdown = "Flow"
|
| 140 |
+
# Sampler steps
|
| 141 |
+
sample_step_slider = 50
|
| 142 |
+
# height and width
|
| 143 |
+
width_slider = 832
|
| 144 |
+
height_slider = 480
|
| 145 |
+
# cfg scale
|
| 146 |
+
cfg_scale_slider = 6
|
| 147 |
+
seed_textbox = 43
|
| 148 |
+
|
| 149 |
+
outputs = post_infer(
|
| 150 |
+
generation_method,
|
| 151 |
+
length_slider,
|
| 152 |
+
lora_model_path=lora_model_path,
|
| 153 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 154 |
+
prompt_textbox=prompt_textbox,
|
| 155 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 156 |
+
sampler_dropdown=sampler_dropdown,
|
| 157 |
+
sample_step_slider=sample_step_slider,
|
| 158 |
+
width_slider=width_slider,
|
| 159 |
+
height_slider=height_slider,
|
| 160 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 161 |
+
seed_textbox=seed_textbox,
|
| 162 |
+
enable_teacache = enable_teacache,
|
| 163 |
+
teacache_threshold = teacache_threshold,
|
| 164 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 165 |
+
teacache_offload = teacache_offload,
|
| 166 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 167 |
+
enable_riflex = enable_riflex,
|
| 168 |
+
riflex_k = riflex_k,
|
| 169 |
+
url=EAS_URL,
|
| 170 |
+
POST_TOKEN=TOKEN
|
| 171 |
+
)
|
| 172 |
+
# Get decoded data
|
| 173 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 174 |
+
base64_encoding = outputs["base64_encoding"]
|
| 175 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 176 |
+
|
| 177 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 178 |
+
if is_image or length_slider == 1:
|
| 179 |
+
file_path = "1.png"
|
| 180 |
+
else:
|
| 181 |
+
file_path = "1.mp4"
|
| 182 |
+
with open(file_path, "wb") as file:
|
| 183 |
+
file.write(decoded_data)
|
| 184 |
+
|
| 185 |
+
# End of record time
|
| 186 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 187 |
+
time_end = time.time()
|
| 188 |
+
time_sum = (time_end - time_start)
|
| 189 |
+
print('# --------------------------------------------------------- #')
|
| 190 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 191 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.2/post_infer_queue_i2v.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import requests
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def post_infer(
|
| 11 |
+
generation_method,
|
| 12 |
+
length_slider,
|
| 13 |
+
url='http://127.0.0.1:7860',
|
| 14 |
+
POST_TOKEN="",
|
| 15 |
+
timeout=5,
|
| 16 |
+
base_model_path="none",
|
| 17 |
+
lora_model_path="none",
|
| 18 |
+
lora_alpha_slider=0.55,
|
| 19 |
+
prompt_textbox="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",
|
| 20 |
+
negative_prompt_textbox="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
|
| 21 |
+
sampler_dropdown="Flow",
|
| 22 |
+
sample_step_slider=50,
|
| 23 |
+
width_slider=672,
|
| 24 |
+
height_slider=384,
|
| 25 |
+
cfg_scale_slider=6,
|
| 26 |
+
seed_textbox=43,
|
| 27 |
+
enable_teacache = None,
|
| 28 |
+
teacache_threshold = None,
|
| 29 |
+
num_skip_start_steps = None,
|
| 30 |
+
teacache_offload = None,
|
| 31 |
+
cfg_skip_ratio = None,
|
| 32 |
+
enable_riflex = None,
|
| 33 |
+
riflex_k = None,
|
| 34 |
+
start_image = None
|
| 35 |
+
):
|
| 36 |
+
if start_image:
|
| 37 |
+
try:
|
| 38 |
+
if not start_image.startswith("http"):
|
| 39 |
+
image = Image.open(start_image).convert("RGB")
|
| 40 |
+
# 将图片转换为 Base64 编码
|
| 41 |
+
buffered = BytesIO()
|
| 42 |
+
image.save(buffered, format="JPEG")
|
| 43 |
+
start_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error processing start_image: {e}")
|
| 46 |
+
raise
|
| 47 |
+
|
| 48 |
+
# Prepare the data payload
|
| 49 |
+
datas = json.dumps({
|
| 50 |
+
"base_model_path": base_model_path,
|
| 51 |
+
"lora_model_path": lora_model_path,
|
| 52 |
+
"lora_alpha_slider": lora_alpha_slider,
|
| 53 |
+
"prompt_textbox": prompt_textbox,
|
| 54 |
+
"negative_prompt_textbox": negative_prompt_textbox,
|
| 55 |
+
"sampler_dropdown": sampler_dropdown,
|
| 56 |
+
"sample_step_slider": sample_step_slider,
|
| 57 |
+
"width_slider": width_slider,
|
| 58 |
+
"height_slider": height_slider,
|
| 59 |
+
"generation_method": generation_method,
|
| 60 |
+
"length_slider": length_slider,
|
| 61 |
+
"cfg_scale_slider": cfg_scale_slider,
|
| 62 |
+
"seed_textbox": seed_textbox,
|
| 63 |
+
|
| 64 |
+
"enable_teacache": enable_teacache,
|
| 65 |
+
"teacache_threshold": teacache_threshold,
|
| 66 |
+
"num_skip_start_steps": num_skip_start_steps,
|
| 67 |
+
"teacache_offload": teacache_offload,
|
| 68 |
+
"cfg_skip_ratio": cfg_skip_ratio,
|
| 69 |
+
"enable_riflex": enable_riflex,
|
| 70 |
+
"riflex_k": riflex_k,
|
| 71 |
+
"start_image": start_image
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# Initialize session and set headers
|
| 75 |
+
session = requests.session()
|
| 76 |
+
session.headers.update({"Authorization": POST_TOKEN})
|
| 77 |
+
|
| 78 |
+
# Send POST request
|
| 79 |
+
if url[-1] == "/":
|
| 80 |
+
url = url[:-1]
|
| 81 |
+
post_r = session.post(f'{url}/videox_fun/infer_forward', data=datas, timeout=timeout)
|
| 82 |
+
|
| 83 |
+
# Extract request ID from POST response headers
|
| 84 |
+
request_id = post_r.headers.get("X-Eas-Queueservice-Request-Id")
|
| 85 |
+
|
| 86 |
+
# Prepare query parameters for GET request
|
| 87 |
+
query = {
|
| 88 |
+
'_index_': '0',
|
| 89 |
+
'_length_': '1',
|
| 90 |
+
'_timeout_': str(timeout),
|
| 91 |
+
'_raw_': 'false',
|
| 92 |
+
'_auto_delete_': 'true',
|
| 93 |
+
}
|
| 94 |
+
if request_id:
|
| 95 |
+
query['requestId'] = request_id
|
| 96 |
+
|
| 97 |
+
query_str = urllib.parse.urlencode(query)
|
| 98 |
+
|
| 99 |
+
# Polling GET request until status code is not 204
|
| 100 |
+
status_code = 204
|
| 101 |
+
while status_code == 204:
|
| 102 |
+
if query_str:
|
| 103 |
+
get_r = session.get(f'{url}/sink?{query_str}', timeout=timeout)
|
| 104 |
+
else:
|
| 105 |
+
get_r = session.get(f'{url}/sink', timeout=timeout)
|
| 106 |
+
status_code = get_r.status_code
|
| 107 |
+
# Decode and return the response content
|
| 108 |
+
data = get_r.content.decode('utf-8')
|
| 109 |
+
return data
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == '__main__':
|
| 113 |
+
# initiate time
|
| 114 |
+
time_start = time.time()
|
| 115 |
+
|
| 116 |
+
# EAS队列配置
|
| 117 |
+
EAS_URL = 'http://17xxxxxxxxx.pai-eas.aliyuncs.com/api/predict/xxxxxxxx'
|
| 118 |
+
# Use in EAS Queue
|
| 119 |
+
TOKEN = 'xxxxxxxx'
|
| 120 |
+
|
| 121 |
+
# Support TeaCache.
|
| 122 |
+
enable_teacache = True
|
| 123 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 124 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 125 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 126 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 127 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 128 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 129 |
+
teacache_threshold = 0.10
|
| 130 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 131 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 132 |
+
num_skip_start_steps = 5
|
| 133 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 134 |
+
teacache_offload = False
|
| 135 |
+
|
| 136 |
+
# Skip some cfg steps in inference
|
| 137 |
+
# Recommended to be set between 0.00 and 0.25
|
| 138 |
+
cfg_skip_ratio = 0
|
| 139 |
+
|
| 140 |
+
# Riflex config
|
| 141 |
+
enable_riflex = False
|
| 142 |
+
# Index of intrinsic frequency
|
| 143 |
+
riflex_k = 6
|
| 144 |
+
|
| 145 |
+
# "Video Generation" and "Image Generation"
|
| 146 |
+
generation_method = "Video Generation"
|
| 147 |
+
# Video length
|
| 148 |
+
length_slider = 81
|
| 149 |
+
# Used in Lora models
|
| 150 |
+
lora_model_path = "none"
|
| 151 |
+
lora_alpha_slider = 0.55
|
| 152 |
+
# Prompts
|
| 153 |
+
prompt_textbox = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 154 |
+
negative_prompt_textbox = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 155 |
+
# Sampler name
|
| 156 |
+
sampler_dropdown = "Flow"
|
| 157 |
+
# Sampler steps
|
| 158 |
+
sample_step_slider = 50
|
| 159 |
+
# height and width
|
| 160 |
+
width_slider = 832
|
| 161 |
+
height_slider = 480
|
| 162 |
+
# cfg scale
|
| 163 |
+
cfg_scale_slider = 6
|
| 164 |
+
seed_textbox = 43
|
| 165 |
+
|
| 166 |
+
# 起始图片路径
|
| 167 |
+
start_image_path = "asset/1.png" # 替换为实际的图片路径
|
| 168 |
+
|
| 169 |
+
outputs = post_infer(
|
| 170 |
+
generation_method,
|
| 171 |
+
length_slider,
|
| 172 |
+
lora_model_path=lora_model_path,
|
| 173 |
+
lora_alpha_slider=lora_alpha_slider,
|
| 174 |
+
prompt_textbox=prompt_textbox,
|
| 175 |
+
negative_prompt_textbox=negative_prompt_textbox,
|
| 176 |
+
sampler_dropdown=sampler_dropdown,
|
| 177 |
+
sample_step_slider=sample_step_slider,
|
| 178 |
+
width_slider=width_slider,
|
| 179 |
+
height_slider=height_slider,
|
| 180 |
+
cfg_scale_slider=cfg_scale_slider,
|
| 181 |
+
seed_textbox=seed_textbox,
|
| 182 |
+
enable_teacache = enable_teacache,
|
| 183 |
+
teacache_threshold = teacache_threshold,
|
| 184 |
+
num_skip_start_steps = num_skip_start_steps,
|
| 185 |
+
teacache_offload = teacache_offload,
|
| 186 |
+
cfg_skip_ratio = cfg_skip_ratio,
|
| 187 |
+
enable_riflex = enable_riflex,
|
| 188 |
+
riflex_k = riflex_k,
|
| 189 |
+
url=EAS_URL,
|
| 190 |
+
POST_TOKEN=TOKEN,
|
| 191 |
+
start_image=start_image_path # 传递起始图片路径
|
| 192 |
+
)
|
| 193 |
+
# Get decoded data
|
| 194 |
+
outputs = json.loads(base64.b64decode(json.loads(outputs)[0]['data']))
|
| 195 |
+
base64_encoding = outputs["base64_encoding"]
|
| 196 |
+
decoded_data = base64.b64decode(base64_encoding)
|
| 197 |
+
|
| 198 |
+
is_image = True if generation_method == "Image Generation" else False
|
| 199 |
+
if is_image or length_slider == 1:
|
| 200 |
+
file_path = "1.png"
|
| 201 |
+
else:
|
| 202 |
+
file_path = "1.mp4"
|
| 203 |
+
with open(file_path, "wb") as file:
|
| 204 |
+
file.write(decoded_data)
|
| 205 |
+
|
| 206 |
+
# End of record time
|
| 207 |
+
# The calculated time difference is the execution time of the program, expressed in seconds / s
|
| 208 |
+
time_end = time.time()
|
| 209 |
+
time_sum = (time_end - time_start)
|
| 210 |
+
print('# --------------------------------------------------------- #')
|
| 211 |
+
print(f'# Total expenditure: {time_sum}s')
|
| 212 |
+
print('# --------------------------------------------------------- #')
|
VideoX-Fun/examples/wan2.2/predict_i2v.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, AutoencoderKLWan3_8, AutoTokenizer, CLIPModel,
|
| 17 |
+
WanT5EncoderModel, Wan2_2Transformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import Wan2_2I2VPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = True
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 62 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 63 |
+
teacache_threshold = 0.10
|
| 64 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 65 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 66 |
+
num_skip_start_steps = 5
|
| 67 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 68 |
+
teacache_offload = False
|
| 69 |
+
|
| 70 |
+
# Skip some cfg steps in inference
|
| 71 |
+
# Recommended to be set between 0.00 and 0.25
|
| 72 |
+
cfg_skip_ratio = 0
|
| 73 |
+
|
| 74 |
+
# Riflex config
|
| 75 |
+
enable_riflex = False
|
| 76 |
+
# Index of intrinsic frequency
|
| 77 |
+
riflex_k = 6
|
| 78 |
+
|
| 79 |
+
# Config and model path
|
| 80 |
+
config_path = "config/wan2.2/wan_civitai_i2v.yaml"
|
| 81 |
+
# model path
|
| 82 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-I2V-A14B"
|
| 83 |
+
|
| 84 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 85 |
+
sampler_name = "Flow_Unipc"
|
| 86 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 87 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 88 |
+
shift = 5
|
| 89 |
+
|
| 90 |
+
# Load pretrained model if need
|
| 91 |
+
# The transformer_path is used for low noise model, the transformer_high_path is used for high noise model.
|
| 92 |
+
transformer_path = None
|
| 93 |
+
transformer_high_path = None
|
| 94 |
+
vae_path = None
|
| 95 |
+
# Load lora model if need
|
| 96 |
+
# The lora_path is used for low noise model, the lora_high_path is used for high noise model.
|
| 97 |
+
lora_path = None
|
| 98 |
+
lora_high_path = None
|
| 99 |
+
|
| 100 |
+
# Other params
|
| 101 |
+
sample_size = [480, 832]
|
| 102 |
+
video_length = 81
|
| 103 |
+
fps = 16
|
| 104 |
+
|
| 105 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 106 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 107 |
+
weight_dtype = torch.bfloat16
|
| 108 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 109 |
+
validation_image_start = "asset/1.png"
|
| 110 |
+
|
| 111 |
+
# prompts
|
| 112 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 113 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 114 |
+
guidance_scale = 6.0
|
| 115 |
+
seed = 43
|
| 116 |
+
num_inference_steps = 50
|
| 117 |
+
# The lora_weight is used for low noise model, the lora_high_weight is used for high noise model.
|
| 118 |
+
lora_weight = 0.55
|
| 119 |
+
lora_high_weight = 0.55
|
| 120 |
+
save_path = "samples/wan-videos-i2v"
|
| 121 |
+
|
| 122 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 123 |
+
config = OmegaConf.load(config_path)
|
| 124 |
+
boundary = config['transformer_additional_kwargs'].get('boundary', 0.900)
|
| 125 |
+
|
| 126 |
+
transformer = Wan2_2Transformer3DModel.from_pretrained(
|
| 127 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_low_noise_model_subpath', 'transformer')),
|
| 128 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 129 |
+
low_cpu_mem_usage=True,
|
| 130 |
+
torch_dtype=weight_dtype,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
transformer_2 = Wan2_2Transformer3DModel.from_pretrained(
|
| 134 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_high_noise_model_subpath', 'transformer')),
|
| 135 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 136 |
+
low_cpu_mem_usage=True,
|
| 137 |
+
torch_dtype=weight_dtype,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if transformer_path is not None:
|
| 141 |
+
print(f"From checkpoint: {transformer_path}")
|
| 142 |
+
if transformer_path.endswith("safetensors"):
|
| 143 |
+
from safetensors.torch import load_file, safe_open
|
| 144 |
+
state_dict = load_file(transformer_path)
|
| 145 |
+
else:
|
| 146 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 147 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 148 |
+
|
| 149 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 150 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 151 |
+
|
| 152 |
+
if transformer_high_path is not None:
|
| 153 |
+
print(f"From checkpoint: {transformer_high_path}")
|
| 154 |
+
if transformer_high_path.endswith("safetensors"):
|
| 155 |
+
from safetensors.torch import load_file, safe_open
|
| 156 |
+
state_dict = load_file(transformer_high_path)
|
| 157 |
+
else:
|
| 158 |
+
state_dict = torch.load(transformer_high_path, map_location="cpu")
|
| 159 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 160 |
+
|
| 161 |
+
m, u = transformer_2.load_state_dict(state_dict, strict=False)
|
| 162 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 163 |
+
|
| 164 |
+
# Get Vae
|
| 165 |
+
Chosen_AutoencoderKL = {
|
| 166 |
+
"AutoencoderKLWan": AutoencoderKLWan,
|
| 167 |
+
"AutoencoderKLWan3_8": AutoencoderKLWan3_8
|
| 168 |
+
}[config['vae_kwargs'].get('vae_type', 'AutoencoderKLWan')]
|
| 169 |
+
vae = Chosen_AutoencoderKL.from_pretrained(
|
| 170 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 171 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 172 |
+
).to(weight_dtype)
|
| 173 |
+
|
| 174 |
+
if vae_path is not None:
|
| 175 |
+
print(f"From checkpoint: {vae_path}")
|
| 176 |
+
if vae_path.endswith("safetensors"):
|
| 177 |
+
from safetensors.torch import load_file, safe_open
|
| 178 |
+
state_dict = load_file(vae_path)
|
| 179 |
+
else:
|
| 180 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 181 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 182 |
+
|
| 183 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 184 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 185 |
+
|
| 186 |
+
# Get Tokenizer
|
| 187 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 188 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Get Text encoder
|
| 192 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 193 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 194 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 195 |
+
low_cpu_mem_usage=True,
|
| 196 |
+
torch_dtype=weight_dtype,
|
| 197 |
+
)
|
| 198 |
+
text_encoder = text_encoder.eval()
|
| 199 |
+
|
| 200 |
+
# Get Scheduler
|
| 201 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 202 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 203 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 204 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 205 |
+
}[sampler_name]
|
| 206 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 207 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 208 |
+
scheduler = Chosen_Scheduler(
|
| 209 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# Get Pipeline
|
| 213 |
+
pipeline = Wan2_2I2VPipeline(
|
| 214 |
+
transformer=transformer,
|
| 215 |
+
transformer_2=transformer_2,
|
| 216 |
+
vae=vae,
|
| 217 |
+
tokenizer=tokenizer,
|
| 218 |
+
text_encoder=text_encoder,
|
| 219 |
+
scheduler=scheduler,
|
| 220 |
+
)
|
| 221 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 222 |
+
from functools import partial
|
| 223 |
+
transformer.enable_multi_gpus_inference()
|
| 224 |
+
transformer_2.enable_multi_gpus_inference()
|
| 225 |
+
if fsdp_dit:
|
| 226 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 227 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 228 |
+
pipeline.transformer_2 = shard_fn(pipeline.transformer_2)
|
| 229 |
+
print("Add FSDP DIT")
|
| 230 |
+
if fsdp_text_encoder:
|
| 231 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 232 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 233 |
+
print("Add FSDP TEXT ENCODER")
|
| 234 |
+
|
| 235 |
+
if compile_dit:
|
| 236 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 237 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 238 |
+
for i in range(len(pipeline.transformer_2.blocks)):
|
| 239 |
+
pipeline.transformer_2.blocks[i] = torch.compile(pipeline.transformer_2.blocks[i])
|
| 240 |
+
print("Add Compile")
|
| 241 |
+
|
| 242 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 243 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 244 |
+
replace_parameters_by_name(transformer_2, ["modulation",], device=device)
|
| 245 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 246 |
+
transformer_2.freqs = transformer_2.freqs.to(device=device)
|
| 247 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 248 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 249 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 250 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 251 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 252 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 253 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 254 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 255 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 256 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 257 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 258 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 259 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 260 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 261 |
+
pipeline.to(device=device)
|
| 262 |
+
else:
|
| 263 |
+
pipeline.to(device=device)
|
| 264 |
+
|
| 265 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 266 |
+
if coefficients is not None:
|
| 267 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 268 |
+
pipeline.transformer.enable_teacache(
|
| 269 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 270 |
+
)
|
| 271 |
+
pipeline.transformer_2.share_teacache(transformer=pipeline.transformer)
|
| 272 |
+
|
| 273 |
+
if cfg_skip_ratio is not None:
|
| 274 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 275 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 276 |
+
pipeline.transformer_2.share_cfg_skip(transformer=pipeline.transformer)
|
| 277 |
+
|
| 278 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 279 |
+
|
| 280 |
+
if lora_path is not None:
|
| 281 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 282 |
+
pipeline = merge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 283 |
+
|
| 284 |
+
with torch.no_grad():
|
| 285 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 286 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 287 |
+
|
| 288 |
+
if enable_riflex:
|
| 289 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 290 |
+
pipeline.transformer_2.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 291 |
+
|
| 292 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, None, video_length=video_length, sample_size=sample_size)
|
| 293 |
+
|
| 294 |
+
sample = pipeline(
|
| 295 |
+
prompt,
|
| 296 |
+
num_frames = video_length,
|
| 297 |
+
negative_prompt = negative_prompt,
|
| 298 |
+
height = sample_size[0],
|
| 299 |
+
width = sample_size[1],
|
| 300 |
+
generator = generator,
|
| 301 |
+
guidance_scale = guidance_scale,
|
| 302 |
+
num_inference_steps = num_inference_steps,
|
| 303 |
+
boundary = boundary,
|
| 304 |
+
|
| 305 |
+
video = input_video,
|
| 306 |
+
mask_video = input_video_mask,
|
| 307 |
+
shift = shift,
|
| 308 |
+
).videos
|
| 309 |
+
|
| 310 |
+
if lora_path is not None:
|
| 311 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 312 |
+
pipeline = unmerge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 313 |
+
|
| 314 |
+
def save_results():
|
| 315 |
+
if not os.path.exists(save_path):
|
| 316 |
+
os.makedirs(save_path, exist_ok=True)
|
| 317 |
+
|
| 318 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 319 |
+
prefix = str(index).zfill(8)
|
| 320 |
+
if video_length == 1:
|
| 321 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 322 |
+
|
| 323 |
+
image = sample[0, :, 0]
|
| 324 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 325 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 326 |
+
image = Image.fromarray(image)
|
| 327 |
+
image.save(video_path)
|
| 328 |
+
else:
|
| 329 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 330 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 331 |
+
|
| 332 |
+
if ulysses_degree * ring_degree > 1:
|
| 333 |
+
import torch.distributed as dist
|
| 334 |
+
if dist.get_rank() == 0:
|
| 335 |
+
save_results()
|
| 336 |
+
else:
|
| 337 |
+
save_results()
|
VideoX-Fun/examples/wan2.2/predict_s2v.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, AutoencoderKLWan3_8, AutoTokenizer, CLIPModel, WanAudioEncoder,
|
| 17 |
+
WanT5EncoderModel, Wan2_2Transformer3DModel_S2V)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import Wan2_2S2VPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent, get_image_latent,
|
| 24 |
+
save_videos_grid, merge_video_audio)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = True
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 62 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 63 |
+
teacache_threshold = 0.10
|
| 64 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 65 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 66 |
+
num_skip_start_steps = 5
|
| 67 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 68 |
+
teacache_offload = False
|
| 69 |
+
|
| 70 |
+
# Skip some cfg steps in inference
|
| 71 |
+
# Recommended to be set between 0.00 and 0.25
|
| 72 |
+
cfg_skip_ratio = 0
|
| 73 |
+
|
| 74 |
+
# Riflex config
|
| 75 |
+
enable_riflex = False
|
| 76 |
+
# Index of intrinsic frequency
|
| 77 |
+
riflex_k = 6
|
| 78 |
+
|
| 79 |
+
# Config and model path
|
| 80 |
+
config_path = "config/wan2.2/wan_civitai_s2v.yaml"
|
| 81 |
+
# model path
|
| 82 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-S2V-14B"
|
| 83 |
+
|
| 84 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 85 |
+
sampler_name = "Flow"
|
| 86 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 87 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 88 |
+
shift = 3
|
| 89 |
+
|
| 90 |
+
# Load pretrained model if need
|
| 91 |
+
# The transformer_path is used for low noise model, the transformer_high_path is used for high noise model.
|
| 92 |
+
transformer_path = None
|
| 93 |
+
transformer_high_path = None
|
| 94 |
+
vae_path = None
|
| 95 |
+
# Load lora model if need
|
| 96 |
+
# The lora_path is used for low noise model, the lora_high_path is used for high noise model.
|
| 97 |
+
lora_path = None
|
| 98 |
+
lora_high_path = None
|
| 99 |
+
|
| 100 |
+
# Other params
|
| 101 |
+
sample_size = [832, 480]
|
| 102 |
+
video_length = 80
|
| 103 |
+
fps = 16
|
| 104 |
+
|
| 105 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 106 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 107 |
+
weight_dtype = torch.bfloat16
|
| 108 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 109 |
+
ref_image = "asset/8.png"
|
| 110 |
+
audio_path = "asset/talk.wav"
|
| 111 |
+
|
| 112 |
+
# prompts
|
| 113 |
+
prompt = "一个女孩在海边说话。"
|
| 114 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 115 |
+
guidance_scale = 4.5
|
| 116 |
+
seed = 43
|
| 117 |
+
num_inference_steps = 40
|
| 118 |
+
# The lora_weight is used for low noise model, the lora_high_weight is used for high noise model.
|
| 119 |
+
lora_weight = 0.55
|
| 120 |
+
lora_high_weight = 0.55
|
| 121 |
+
save_path = "samples/wan-videos-speech2v"
|
| 122 |
+
|
| 123 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 124 |
+
config = OmegaConf.load(config_path)
|
| 125 |
+
boundary = config['transformer_additional_kwargs'].get('boundary', 0.900)
|
| 126 |
+
|
| 127 |
+
transformer = Wan2_2Transformer3DModel_S2V.from_pretrained(
|
| 128 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_low_noise_model_subpath', 'transformer')),
|
| 129 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 130 |
+
low_cpu_mem_usage=True,
|
| 131 |
+
torch_dtype=weight_dtype,
|
| 132 |
+
)
|
| 133 |
+
if config['transformer_additional_kwargs'].get('transformer_combination_type', 'single') == "moe":
|
| 134 |
+
transformer_2 = Wan2_2Transformer3DModel.from_pretrained(
|
| 135 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_high_noise_model_subpath', 'transformer')),
|
| 136 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 137 |
+
low_cpu_mem_usage=True,
|
| 138 |
+
torch_dtype=weight_dtype,
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
transformer_2 = None
|
| 142 |
+
|
| 143 |
+
if transformer_path is not None:
|
| 144 |
+
print(f"From checkpoint: {transformer_path}")
|
| 145 |
+
if transformer_path.endswith("safetensors"):
|
| 146 |
+
from safetensors.torch import load_file, safe_open
|
| 147 |
+
state_dict = load_file(transformer_path)
|
| 148 |
+
else:
|
| 149 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 150 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 151 |
+
|
| 152 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 153 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 154 |
+
|
| 155 |
+
if transformer_2 is not None:
|
| 156 |
+
if transformer_high_path is not None:
|
| 157 |
+
print(f"From checkpoint: {transformer_high_path}")
|
| 158 |
+
if transformer_high_path.endswith("safetensors"):
|
| 159 |
+
from safetensors.torch import load_file, safe_open
|
| 160 |
+
state_dict = load_file(transformer_high_path)
|
| 161 |
+
else:
|
| 162 |
+
state_dict = torch.load(transformer_high_path, map_location="cpu")
|
| 163 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 164 |
+
|
| 165 |
+
m, u = transformer_2.load_state_dict(state_dict, strict=False)
|
| 166 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 167 |
+
|
| 168 |
+
# Get Vae
|
| 169 |
+
Chosen_AutoencoderKL = {
|
| 170 |
+
"AutoencoderKLWan": AutoencoderKLWan,
|
| 171 |
+
"AutoencoderKLWan3_8": AutoencoderKLWan3_8
|
| 172 |
+
}[config['vae_kwargs'].get('vae_type', 'AutoencoderKLWan')]
|
| 173 |
+
vae = Chosen_AutoencoderKL.from_pretrained(
|
| 174 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 175 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 176 |
+
).to(weight_dtype)
|
| 177 |
+
|
| 178 |
+
if vae_path is not None:
|
| 179 |
+
print(f"From checkpoint: {vae_path}")
|
| 180 |
+
if vae_path.endswith("safetensors"):
|
| 181 |
+
from safetensors.torch import load_file, safe_open
|
| 182 |
+
state_dict = load_file(vae_path)
|
| 183 |
+
else:
|
| 184 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 185 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 186 |
+
|
| 187 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 188 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 189 |
+
|
| 190 |
+
# Get Tokenizer
|
| 191 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 192 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Get Text encoder
|
| 196 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 197 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 198 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 199 |
+
low_cpu_mem_usage=True,
|
| 200 |
+
torch_dtype=weight_dtype,
|
| 201 |
+
)
|
| 202 |
+
text_encoder = text_encoder.eval()
|
| 203 |
+
|
| 204 |
+
audio_encoder = WanAudioEncoder(
|
| 205 |
+
os.path.join(model_name, config['audio_encoder_kwargs'].get('audio_encoder_subpath', 'audio_encoder')),
|
| 206 |
+
"cpu"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Get Scheduler
|
| 210 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 211 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 212 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 213 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 214 |
+
}[sampler_name]
|
| 215 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 216 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 217 |
+
scheduler = Chosen_Scheduler(
|
| 218 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# Get Pipeline
|
| 222 |
+
pipeline = Wan2_2S2VPipeline(
|
| 223 |
+
transformer=transformer,
|
| 224 |
+
transformer_2=transformer_2,
|
| 225 |
+
vae=vae,
|
| 226 |
+
tokenizer=tokenizer,
|
| 227 |
+
text_encoder=text_encoder,
|
| 228 |
+
scheduler=scheduler,
|
| 229 |
+
audio_encoder=audio_encoder,
|
| 230 |
+
)
|
| 231 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 232 |
+
from functools import partial
|
| 233 |
+
transformer.enable_multi_gpus_inference()
|
| 234 |
+
if transformer_2 is not None:
|
| 235 |
+
transformer_2.enable_multi_gpus_inference()
|
| 236 |
+
if fsdp_dit:
|
| 237 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 238 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 239 |
+
if transformer_2 is not None:
|
| 240 |
+
pipeline.transformer_2 = shard_fn(pipeline.transformer_2)
|
| 241 |
+
print("Add FSDP DIT")
|
| 242 |
+
if fsdp_text_encoder:
|
| 243 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 244 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 245 |
+
print("Add FSDP TEXT ENCODER")
|
| 246 |
+
|
| 247 |
+
if compile_dit:
|
| 248 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 249 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 250 |
+
if transformer_2 is not None:
|
| 251 |
+
for i in range(len(pipeline.transformer_2.blocks)):
|
| 252 |
+
pipeline.transformer_2.blocks[i] = torch.compile(pipeline.transformer_2.blocks[i])
|
| 253 |
+
print("Add Compile")
|
| 254 |
+
|
| 255 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 256 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 257 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 258 |
+
if transformer_2 is not None:
|
| 259 |
+
replace_parameters_by_name(transformer_2, ["modulation",], device=device)
|
| 260 |
+
transformer_2.freqs = transformer_2.freqs.to(device=device)
|
| 261 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 262 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 263 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 264 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 265 |
+
if transformer_2 is not None:
|
| 266 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 267 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 268 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 269 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 270 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 271 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 272 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 273 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 274 |
+
if transformer_2 is not None:
|
| 275 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 276 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 277 |
+
pipeline.to(device=device)
|
| 278 |
+
else:
|
| 279 |
+
pipeline.to(device=device)
|
| 280 |
+
|
| 281 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 282 |
+
if coefficients is not None:
|
| 283 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 284 |
+
pipeline.transformer.enable_teacache(
|
| 285 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 286 |
+
)
|
| 287 |
+
if transformer_2 is not None:
|
| 288 |
+
pipeline.transformer_2.share_teacache(transformer=pipeline.transformer)
|
| 289 |
+
|
| 290 |
+
if cfg_skip_ratio is not None:
|
| 291 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 292 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 293 |
+
if transformer_2 is not None:
|
| 294 |
+
pipeline.transformer_2.share_cfg_skip(transformer=pipeline.transformer)
|
| 295 |
+
|
| 296 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 297 |
+
|
| 298 |
+
if lora_path is not None:
|
| 299 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 300 |
+
if transformer_2 is not None:
|
| 301 |
+
pipeline = merge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 302 |
+
|
| 303 |
+
with torch.no_grad():
|
| 304 |
+
video_length = video_length // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio if video_length != 1 else 1
|
| 305 |
+
latent_frames = video_length // vae.config.temporal_compression_ratio
|
| 306 |
+
|
| 307 |
+
if enable_riflex:
|
| 308 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 309 |
+
if transformer_2 is not None:
|
| 310 |
+
pipeline.transformer_2.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 311 |
+
|
| 312 |
+
if ref_image is not None:
|
| 313 |
+
ref_image = get_image_latent(ref_image, sample_size=sample_size)
|
| 314 |
+
|
| 315 |
+
sample = pipeline(
|
| 316 |
+
prompt,
|
| 317 |
+
num_frames = video_length,
|
| 318 |
+
negative_prompt = negative_prompt,
|
| 319 |
+
height = sample_size[0],
|
| 320 |
+
width = sample_size[1],
|
| 321 |
+
generator = generator,
|
| 322 |
+
guidance_scale = guidance_scale,
|
| 323 |
+
num_inference_steps = num_inference_steps,
|
| 324 |
+
boundary = boundary,
|
| 325 |
+
|
| 326 |
+
ref_image = ref_image,
|
| 327 |
+
audio_path = audio_path,
|
| 328 |
+
shift = shift,
|
| 329 |
+
fps = fps
|
| 330 |
+
).videos
|
| 331 |
+
|
| 332 |
+
if lora_path is not None:
|
| 333 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 334 |
+
pipeline = unmerge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 335 |
+
|
| 336 |
+
def save_results():
|
| 337 |
+
if not os.path.exists(save_path):
|
| 338 |
+
os.makedirs(save_path, exist_ok=True)
|
| 339 |
+
|
| 340 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 341 |
+
prefix = str(index).zfill(8)
|
| 342 |
+
if video_length == 1:
|
| 343 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 344 |
+
|
| 345 |
+
image = sample[0, :, 0]
|
| 346 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 347 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 348 |
+
image = Image.fromarray(image)
|
| 349 |
+
image.save(video_path)
|
| 350 |
+
else:
|
| 351 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 352 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 353 |
+
|
| 354 |
+
merge_video_audio(video_path=video_path, audio_path=audio_path)
|
| 355 |
+
|
| 356 |
+
if ulysses_degree * ring_degree > 1:
|
| 357 |
+
import torch.distributed as dist
|
| 358 |
+
if dist.get_rank() == 0:
|
| 359 |
+
save_results()
|
| 360 |
+
else:
|
| 361 |
+
save_results()
|
VideoX-Fun/examples/wan2.2/predict_t2v.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan, AutoencoderKLWan3_8, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
Wan2_2Transformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import Wan2_2Pipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = True
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 62 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 63 |
+
teacache_threshold = 0.10
|
| 64 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 65 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 66 |
+
num_skip_start_steps = 5
|
| 67 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 68 |
+
teacache_offload = False
|
| 69 |
+
|
| 70 |
+
# Skip some cfg steps in inference
|
| 71 |
+
# Recommended to be set between 0.00 and 0.25
|
| 72 |
+
cfg_skip_ratio = 0
|
| 73 |
+
|
| 74 |
+
# Riflex config
|
| 75 |
+
enable_riflex = False
|
| 76 |
+
# Index of intrinsic frequency
|
| 77 |
+
riflex_k = 6
|
| 78 |
+
|
| 79 |
+
# Config and model path
|
| 80 |
+
config_path = "config/wan2.2/wan_civitai_t2v.yaml"
|
| 81 |
+
# model path
|
| 82 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-T2V-A14B"
|
| 83 |
+
|
| 84 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 85 |
+
sampler_name = "Flow_Unipc"
|
| 86 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 87 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 88 |
+
shift = 12
|
| 89 |
+
|
| 90 |
+
# Load pretrained model if need
|
| 91 |
+
# The transformer_path is used for low noise model, the transformer_high_path is used for high noise model.
|
| 92 |
+
transformer_path = None
|
| 93 |
+
transformer_high_path = None
|
| 94 |
+
vae_path = None
|
| 95 |
+
# Load lora model if need
|
| 96 |
+
# The lora_path is used for low noise model, the lora_high_path is used for high noise model.
|
| 97 |
+
lora_path = None
|
| 98 |
+
lora_high_path = None
|
| 99 |
+
|
| 100 |
+
# Other params
|
| 101 |
+
sample_size = [480, 832]
|
| 102 |
+
video_length = 81
|
| 103 |
+
fps = 16
|
| 104 |
+
|
| 105 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 106 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 107 |
+
weight_dtype = torch.bfloat16
|
| 108 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 109 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 110 |
+
guidance_scale = 6.0
|
| 111 |
+
seed = 43
|
| 112 |
+
num_inference_steps = 50
|
| 113 |
+
# The lora_weight is used for low noise model, the lora_high_weight is used for high noise model.
|
| 114 |
+
lora_weight = 0.55
|
| 115 |
+
lora_high_weight = 0.55
|
| 116 |
+
save_path = "samples/wan-videos-t2v"
|
| 117 |
+
|
| 118 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 119 |
+
config = OmegaConf.load(config_path)
|
| 120 |
+
boundary = config['transformer_additional_kwargs'].get('boundary', 0.875)
|
| 121 |
+
|
| 122 |
+
transformer = Wan2_2Transformer3DModel.from_pretrained(
|
| 123 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_low_noise_model_subpath', 'transformer')),
|
| 124 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 125 |
+
low_cpu_mem_usage=True,
|
| 126 |
+
torch_dtype=weight_dtype,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
transformer_2 = Wan2_2Transformer3DModel.from_pretrained(
|
| 130 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_high_noise_model_subpath', 'transformer')),
|
| 131 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 132 |
+
low_cpu_mem_usage=True,
|
| 133 |
+
torch_dtype=weight_dtype,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if transformer_path is not None:
|
| 137 |
+
print(f"From checkpoint: {transformer_path}")
|
| 138 |
+
if transformer_path.endswith("safetensors"):
|
| 139 |
+
from safetensors.torch import load_file, safe_open
|
| 140 |
+
state_dict = load_file(transformer_path)
|
| 141 |
+
else:
|
| 142 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 143 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 144 |
+
|
| 145 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 146 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 147 |
+
|
| 148 |
+
if transformer_high_path is not None:
|
| 149 |
+
print(f"From checkpoint: {transformer_high_path}")
|
| 150 |
+
if transformer_high_path.endswith("safetensors"):
|
| 151 |
+
from safetensors.torch import load_file, safe_open
|
| 152 |
+
state_dict = load_file(transformer_high_path)
|
| 153 |
+
else:
|
| 154 |
+
state_dict = torch.load(transformer_high_path, map_location="cpu")
|
| 155 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 156 |
+
|
| 157 |
+
m, u = transformer_2.load_state_dict(state_dict, strict=False)
|
| 158 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 159 |
+
|
| 160 |
+
# Get Vae
|
| 161 |
+
Chosen_AutoencoderKL = {
|
| 162 |
+
"AutoencoderKLWan": AutoencoderKLWan,
|
| 163 |
+
"AutoencoderKLWan3_8": AutoencoderKLWan3_8
|
| 164 |
+
}[config['vae_kwargs'].get('vae_type', 'AutoencoderKLWan')]
|
| 165 |
+
vae = Chosen_AutoencoderKL.from_pretrained(
|
| 166 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 167 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 168 |
+
).to(weight_dtype)
|
| 169 |
+
|
| 170 |
+
if vae_path is not None:
|
| 171 |
+
print(f"From checkpoint: {vae_path}")
|
| 172 |
+
if vae_path.endswith("safetensors"):
|
| 173 |
+
from safetensors.torch import load_file, safe_open
|
| 174 |
+
state_dict = load_file(vae_path)
|
| 175 |
+
else:
|
| 176 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 177 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 178 |
+
|
| 179 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 180 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 181 |
+
|
| 182 |
+
# Get Tokenizer
|
| 183 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 184 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# Get Text encoder
|
| 188 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 189 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 190 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 191 |
+
low_cpu_mem_usage=True,
|
| 192 |
+
torch_dtype=weight_dtype,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Get Scheduler
|
| 196 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 197 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 198 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 199 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 200 |
+
}[sampler_name]
|
| 201 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 202 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 203 |
+
scheduler = Chosen_Scheduler(
|
| 204 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Get Pipeline
|
| 208 |
+
pipeline = Wan2_2Pipeline(
|
| 209 |
+
transformer=transformer,
|
| 210 |
+
transformer_2=transformer_2,
|
| 211 |
+
vae=vae,
|
| 212 |
+
tokenizer=tokenizer,
|
| 213 |
+
text_encoder=text_encoder,
|
| 214 |
+
scheduler=scheduler,
|
| 215 |
+
)
|
| 216 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 217 |
+
from functools import partial
|
| 218 |
+
transformer.enable_multi_gpus_inference()
|
| 219 |
+
transformer_2.enable_multi_gpus_inference()
|
| 220 |
+
if fsdp_dit:
|
| 221 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 222 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 223 |
+
pipeline.transformer_2 = shard_fn(pipeline.transformer_2)
|
| 224 |
+
print("Add FSDP DIT")
|
| 225 |
+
if fsdp_text_encoder:
|
| 226 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 227 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 228 |
+
print("Add FSDP TEXT ENCODER")
|
| 229 |
+
|
| 230 |
+
if compile_dit:
|
| 231 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 232 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 233 |
+
for i in range(len(pipeline.transformer_2.blocks)):
|
| 234 |
+
pipeline.transformer_2.blocks[i] = torch.compile(pipeline.transformer_2.blocks[i])
|
| 235 |
+
print("Add Compile")
|
| 236 |
+
|
| 237 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 238 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 239 |
+
replace_parameters_by_name(transformer_2, ["modulation",], device=device)
|
| 240 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 241 |
+
transformer_2.freqs = transformer_2.freqs.to(device=device)
|
| 242 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 243 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 244 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 245 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 246 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 247 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 248 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 249 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 250 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 251 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 252 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 253 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 254 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 255 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 256 |
+
pipeline.to(device=device)
|
| 257 |
+
else:
|
| 258 |
+
pipeline.to(device=device)
|
| 259 |
+
|
| 260 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 261 |
+
if coefficients is not None:
|
| 262 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 263 |
+
pipeline.transformer.enable_teacache(
|
| 264 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 265 |
+
)
|
| 266 |
+
pipeline.transformer_2.share_teacache(transformer=pipeline.transformer)
|
| 267 |
+
|
| 268 |
+
if cfg_skip_ratio is not None:
|
| 269 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 270 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 271 |
+
pipeline.transformer_2.share_cfg_skip(transformer=pipeline.transformer)
|
| 272 |
+
|
| 273 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 274 |
+
|
| 275 |
+
if lora_path is not None:
|
| 276 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 277 |
+
pipeline = merge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 278 |
+
|
| 279 |
+
with torch.no_grad():
|
| 280 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 281 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 282 |
+
|
| 283 |
+
if enable_riflex:
|
| 284 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 285 |
+
pipeline.transformer_2.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 286 |
+
|
| 287 |
+
sample = pipeline(
|
| 288 |
+
prompt,
|
| 289 |
+
num_frames = video_length,
|
| 290 |
+
negative_prompt = negative_prompt,
|
| 291 |
+
height = sample_size[0],
|
| 292 |
+
width = sample_size[1],
|
| 293 |
+
generator = generator,
|
| 294 |
+
guidance_scale = guidance_scale,
|
| 295 |
+
num_inference_steps = num_inference_steps,
|
| 296 |
+
boundary = boundary,
|
| 297 |
+
shift = shift,
|
| 298 |
+
).videos
|
| 299 |
+
|
| 300 |
+
if lora_path is not None:
|
| 301 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 302 |
+
pipeline = unmerge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 303 |
+
|
| 304 |
+
def save_results():
|
| 305 |
+
if not os.path.exists(save_path):
|
| 306 |
+
os.makedirs(save_path, exist_ok=True)
|
| 307 |
+
|
| 308 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 309 |
+
prefix = str(index).zfill(8)
|
| 310 |
+
if video_length == 1:
|
| 311 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 312 |
+
|
| 313 |
+
image = sample[0, :, 0]
|
| 314 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 315 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 316 |
+
image = Image.fromarray(image)
|
| 317 |
+
image.save(video_path)
|
| 318 |
+
else:
|
| 319 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 320 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 321 |
+
|
| 322 |
+
if ulysses_degree * ring_degree > 1:
|
| 323 |
+
import torch.distributed as dist
|
| 324 |
+
if dist.get_rank() == 0:
|
| 325 |
+
save_results()
|
| 326 |
+
else:
|
| 327 |
+
save_results()
|
VideoX-Fun/examples/wan2.2/predict_ti2v.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 7 |
+
from omegaconf import OmegaConf
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
current_file_path = os.path.abspath(__file__)
|
| 11 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 12 |
+
for project_root in project_roots:
|
| 13 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 14 |
+
|
| 15 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 16 |
+
from videox_fun.models import (AutoencoderKLWan3_8, AutoencoderKLWan, WanT5EncoderModel, AutoTokenizer,
|
| 17 |
+
Wan2_2Transformer3DModel)
|
| 18 |
+
from videox_fun.models.cache_utils import get_teacache_coefficients
|
| 19 |
+
from videox_fun.pipeline import Wan2_2TI2VPipeline
|
| 20 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 21 |
+
convert_weight_dtype_wrapper)
|
| 22 |
+
from videox_fun.utils.lora_utils import merge_lora, unmerge_lora
|
| 23 |
+
from videox_fun.utils.utils import (filter_kwargs, get_image_to_video_latent,
|
| 24 |
+
save_videos_grid)
|
| 25 |
+
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
|
| 26 |
+
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
|
| 27 |
+
|
| 28 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 29 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 30 |
+
#
|
| 31 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 32 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 33 |
+
#
|
| 34 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 35 |
+
#
|
| 36 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 37 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 38 |
+
#
|
| 39 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 40 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 41 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 42 |
+
# Multi GPUs config
|
| 43 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 44 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 45 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 46 |
+
ulysses_degree = 1
|
| 47 |
+
ring_degree = 1
|
| 48 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 49 |
+
fsdp_dit = False
|
| 50 |
+
fsdp_text_encoder = True
|
| 51 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 52 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 53 |
+
compile_dit = False
|
| 54 |
+
|
| 55 |
+
# TeaCache config
|
| 56 |
+
enable_teacache = True
|
| 57 |
+
# Recommended to be set between 0.05 and 0.30. A larger threshold can cache more steps, speeding up the inference process,
|
| 58 |
+
# but it may cause slight differences between the generated content and the original content.
|
| 59 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 60 |
+
# | Model Name | threshold | Model Name | threshold |
|
| 61 |
+
# | Wan2.2-T2V-A14B | 0.10~0.15 | Wan2.2-I2V-A14B | 0.15~0.20 |
|
| 62 |
+
# # --------------------------------------------------------------------------------------------------- #
|
| 63 |
+
teacache_threshold = 0.10
|
| 64 |
+
# The number of steps to skip TeaCache at the beginning of the inference process, which can
|
| 65 |
+
# reduce the impact of TeaCache on generated video quality.
|
| 66 |
+
num_skip_start_steps = 5
|
| 67 |
+
# Whether to offload TeaCache tensors to cpu to save a little bit of GPU memory.
|
| 68 |
+
teacache_offload = False
|
| 69 |
+
|
| 70 |
+
# Skip some cfg steps in inference
|
| 71 |
+
# Recommended to be set between 0.00 and 0.25
|
| 72 |
+
cfg_skip_ratio = 0
|
| 73 |
+
|
| 74 |
+
# Riflex config
|
| 75 |
+
enable_riflex = False
|
| 76 |
+
# Index of intrinsic frequency
|
| 77 |
+
riflex_k = 6
|
| 78 |
+
|
| 79 |
+
# Config and model path
|
| 80 |
+
config_path = "config/wan2.2/wan_civitai_5b.yaml"
|
| 81 |
+
# model path
|
| 82 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-TI2V-5B"
|
| 83 |
+
|
| 84 |
+
# Choose the sampler in "Flow", "Flow_Unipc", "Flow_DPM++"
|
| 85 |
+
sampler_name = "Flow_Unipc"
|
| 86 |
+
# [NOTE]: Noise schedule shift parameter. Affects temporal dynamics.
|
| 87 |
+
# Used when the sampler is in "Flow_Unipc", "Flow_DPM++".
|
| 88 |
+
shift = 5
|
| 89 |
+
|
| 90 |
+
# Load pretrained model if need
|
| 91 |
+
# The transformer_path is used for low noise model, the transformer_high_path is used for high noise model.
|
| 92 |
+
# Since Wan2.2-5b consists of only one model, only transformer_path is used.
|
| 93 |
+
transformer_path = None
|
| 94 |
+
transformer_high_path = None
|
| 95 |
+
vae_path = None
|
| 96 |
+
# Load lora model if need
|
| 97 |
+
# The lora_path is used for low noise model, the lora_high_path is used for high noise model.
|
| 98 |
+
# Since Wan2.2-5b consists of only one model, only lora_path is used.
|
| 99 |
+
lora_path = None
|
| 100 |
+
lora_high_path = None
|
| 101 |
+
|
| 102 |
+
# Other params
|
| 103 |
+
sample_size = [704, 1280]
|
| 104 |
+
video_length = 121
|
| 105 |
+
fps = 24
|
| 106 |
+
|
| 107 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 108 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 109 |
+
weight_dtype = torch.bfloat16
|
| 110 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 111 |
+
validation_image_start = "asset/1.png"
|
| 112 |
+
|
| 113 |
+
# prompts
|
| 114 |
+
prompt = "一只棕色的狗摇着头,坐在舒适房间里的浅色沙发上。在狗的后面,架子上有一幅镶框的画,周围是粉红色的花朵。房间里柔和温暖的灯光营造出舒适的氛围。"
|
| 115 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 116 |
+
guidance_scale = 6.0
|
| 117 |
+
seed = 43
|
| 118 |
+
num_inference_steps = 50
|
| 119 |
+
# The lora_weight is used for low noise model, the lora_high_weight is used for high noise model.
|
| 120 |
+
lora_weight = 0.55
|
| 121 |
+
lora_high_weight = 0.55
|
| 122 |
+
save_path = "samples/wan-videos-t2v"
|
| 123 |
+
|
| 124 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 125 |
+
config = OmegaConf.load(config_path)
|
| 126 |
+
boundary = config['transformer_additional_kwargs'].get('boundary', 0.875)
|
| 127 |
+
|
| 128 |
+
transformer = Wan2_2Transformer3DModel.from_pretrained(
|
| 129 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_low_noise_model_subpath', 'transformer')),
|
| 130 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 131 |
+
low_cpu_mem_usage=True,
|
| 132 |
+
torch_dtype=weight_dtype,
|
| 133 |
+
)
|
| 134 |
+
if config['transformer_additional_kwargs'].get('transformer_combination_type', 'single') == "moe":
|
| 135 |
+
transformer_2 = Wan2_2Transformer3DModel.from_pretrained(
|
| 136 |
+
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_high_noise_model_subpath', 'transformer')),
|
| 137 |
+
transformer_additional_kwargs=OmegaConf.to_container(config['transformer_additional_kwargs']),
|
| 138 |
+
low_cpu_mem_usage=True,
|
| 139 |
+
torch_dtype=weight_dtype,
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
transformer_2 = None
|
| 143 |
+
|
| 144 |
+
if transformer_path is not None:
|
| 145 |
+
print(f"From checkpoint: {transformer_path}")
|
| 146 |
+
if transformer_path.endswith("safetensors"):
|
| 147 |
+
from safetensors.torch import load_file, safe_open
|
| 148 |
+
state_dict = load_file(transformer_path)
|
| 149 |
+
else:
|
| 150 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 151 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 152 |
+
|
| 153 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 154 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 155 |
+
|
| 156 |
+
if transformer_2 is not None:
|
| 157 |
+
if transformer_high_path is not None:
|
| 158 |
+
print(f"From checkpoint: {transformer_high_path}")
|
| 159 |
+
if transformer_high_path.endswith("safetensors"):
|
| 160 |
+
from safetensors.torch import load_file, safe_open
|
| 161 |
+
state_dict = load_file(transformer_high_path)
|
| 162 |
+
else:
|
| 163 |
+
state_dict = torch.load(transformer_high_path, map_location="cpu")
|
| 164 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 165 |
+
|
| 166 |
+
m, u = transformer_2.load_state_dict(state_dict, strict=False)
|
| 167 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 168 |
+
|
| 169 |
+
# Get Vae
|
| 170 |
+
Chosen_AutoencoderKL = {
|
| 171 |
+
"AutoencoderKLWan": AutoencoderKLWan,
|
| 172 |
+
"AutoencoderKLWan3_8": AutoencoderKLWan3_8
|
| 173 |
+
}[config['vae_kwargs'].get('vae_type', 'AutoencoderKLWan')]
|
| 174 |
+
vae = Chosen_AutoencoderKL.from_pretrained(
|
| 175 |
+
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
|
| 176 |
+
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
|
| 177 |
+
).to(weight_dtype)
|
| 178 |
+
|
| 179 |
+
if vae_path is not None:
|
| 180 |
+
print(f"From checkpoint: {vae_path}")
|
| 181 |
+
if vae_path.endswith("safetensors"):
|
| 182 |
+
from safetensors.torch import load_file, safe_open
|
| 183 |
+
state_dict = load_file(vae_path)
|
| 184 |
+
else:
|
| 185 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 186 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 187 |
+
|
| 188 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 189 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 190 |
+
|
| 191 |
+
# Get Tokenizer
|
| 192 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 193 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# Get Text encoder
|
| 197 |
+
text_encoder = WanT5EncoderModel.from_pretrained(
|
| 198 |
+
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
|
| 199 |
+
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
|
| 200 |
+
low_cpu_mem_usage=True,
|
| 201 |
+
torch_dtype=weight_dtype,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Get Scheduler
|
| 205 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 206 |
+
"Flow": FlowMatchEulerDiscreteScheduler,
|
| 207 |
+
"Flow_Unipc": FlowUniPCMultistepScheduler,
|
| 208 |
+
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
|
| 209 |
+
}[sampler_name]
|
| 210 |
+
if sampler_name == "Flow_Unipc" or sampler_name == "Flow_DPM++":
|
| 211 |
+
config['scheduler_kwargs']['shift'] = 1
|
| 212 |
+
scheduler = Chosen_Scheduler(
|
| 213 |
+
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Get Pipeline
|
| 217 |
+
pipeline = Wan2_2TI2VPipeline(
|
| 218 |
+
transformer=transformer,
|
| 219 |
+
transformer_2=transformer_2,
|
| 220 |
+
vae=vae,
|
| 221 |
+
tokenizer=tokenizer,
|
| 222 |
+
text_encoder=text_encoder,
|
| 223 |
+
scheduler=scheduler,
|
| 224 |
+
)
|
| 225 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 226 |
+
from functools import partial
|
| 227 |
+
transformer.enable_multi_gpus_inference()
|
| 228 |
+
if transformer_2 is not None:
|
| 229 |
+
transformer_2.enable_multi_gpus_inference()
|
| 230 |
+
if fsdp_dit:
|
| 231 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 232 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 233 |
+
if transformer_2 is not None:
|
| 234 |
+
pipeline.transformer_2 = shard_fn(pipeline.transformer_2)
|
| 235 |
+
print("Add FSDP DIT")
|
| 236 |
+
if fsdp_text_encoder:
|
| 237 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 238 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 239 |
+
print("Add FSDP TEXT ENCODER")
|
| 240 |
+
|
| 241 |
+
if compile_dit:
|
| 242 |
+
for i in range(len(pipeline.transformer.blocks)):
|
| 243 |
+
pipeline.transformer.blocks[i] = torch.compile(pipeline.transformer.blocks[i])
|
| 244 |
+
if transformer_2 is not None:
|
| 245 |
+
for i in range(len(pipeline.transformer_2.blocks)):
|
| 246 |
+
pipeline.transformer_2.blocks[i] = torch.compile(pipeline.transformer_2.blocks[i])
|
| 247 |
+
print("Add Compile")
|
| 248 |
+
|
| 249 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 250 |
+
replace_parameters_by_name(transformer, ["modulation",], device=device)
|
| 251 |
+
transformer.freqs = transformer.freqs.to(device=device)
|
| 252 |
+
if transformer_2 is not None:
|
| 253 |
+
replace_parameters_by_name(transformer_2, ["modulation",], device=device)
|
| 254 |
+
transformer_2.freqs = transformer_2.freqs.to(device=device)
|
| 255 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 256 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 257 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 258 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 259 |
+
if transformer_2 is not None:
|
| 260 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 261 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 262 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 263 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 264 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 265 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 266 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=device)
|
| 267 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 268 |
+
if transformer_2 is not None:
|
| 269 |
+
convert_model_weight_to_float8(transformer_2, exclude_module_name=["modulation",], device=device)
|
| 270 |
+
convert_weight_dtype_wrapper(transformer_2, weight_dtype)
|
| 271 |
+
pipeline.to(device=device)
|
| 272 |
+
else:
|
| 273 |
+
pipeline.to(device=device)
|
| 274 |
+
|
| 275 |
+
coefficients = get_teacache_coefficients(model_name) if enable_teacache else None
|
| 276 |
+
if coefficients is not None:
|
| 277 |
+
print(f"Enable TeaCache with threshold {teacache_threshold} and skip the first {num_skip_start_steps} steps.")
|
| 278 |
+
pipeline.transformer.enable_teacache(
|
| 279 |
+
coefficients, num_inference_steps, teacache_threshold, num_skip_start_steps=num_skip_start_steps, offload=teacache_offload
|
| 280 |
+
)
|
| 281 |
+
if transformer_2 is not None:
|
| 282 |
+
pipeline.transformer_2.share_teacache(transformer=pipeline.transformer)
|
| 283 |
+
|
| 284 |
+
if cfg_skip_ratio is not None:
|
| 285 |
+
print(f"Enable cfg_skip_ratio {cfg_skip_ratio}.")
|
| 286 |
+
pipeline.transformer.enable_cfg_skip(cfg_skip_ratio, num_inference_steps)
|
| 287 |
+
if transformer_2 is not None:
|
| 288 |
+
pipeline.transformer_2.share_cfg_skip(transformer=pipeline.transformer)
|
| 289 |
+
|
| 290 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 291 |
+
|
| 292 |
+
if lora_path is not None:
|
| 293 |
+
pipeline = merge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 294 |
+
if transformer_2 is not None:
|
| 295 |
+
pipeline = merge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 296 |
+
|
| 297 |
+
with torch.no_grad():
|
| 298 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 299 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 300 |
+
|
| 301 |
+
if enable_riflex:
|
| 302 |
+
pipeline.transformer.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 303 |
+
if transformer_2 is not None:
|
| 304 |
+
pipeline.transformer_2.enable_riflex(k = riflex_k, L_test = latent_frames)
|
| 305 |
+
|
| 306 |
+
if validation_image_start is not None:
|
| 307 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, None, video_length=video_length, sample_size=sample_size)
|
| 308 |
+
else:
|
| 309 |
+
input_video, input_video_mask, clip_image = None, None, None
|
| 310 |
+
|
| 311 |
+
sample = pipeline(
|
| 312 |
+
prompt,
|
| 313 |
+
num_frames = video_length,
|
| 314 |
+
negative_prompt = negative_prompt,
|
| 315 |
+
height = sample_size[0],
|
| 316 |
+
width = sample_size[1],
|
| 317 |
+
generator = generator,
|
| 318 |
+
guidance_scale = guidance_scale,
|
| 319 |
+
num_inference_steps = num_inference_steps,
|
| 320 |
+
boundary = boundary,
|
| 321 |
+
|
| 322 |
+
video = input_video,
|
| 323 |
+
mask_video = input_video_mask,
|
| 324 |
+
shift = shift,
|
| 325 |
+
).videos
|
| 326 |
+
|
| 327 |
+
if lora_path is not None:
|
| 328 |
+
pipeline = unmerge_lora(pipeline, lora_path, lora_weight, device=device)
|
| 329 |
+
if transformer_2 is not None:
|
| 330 |
+
pipeline = unmerge_lora(pipeline, lora_high_path, lora_high_weight, device=device, sub_transformer_name="transformer_2")
|
| 331 |
+
|
| 332 |
+
def save_results():
|
| 333 |
+
if not os.path.exists(save_path):
|
| 334 |
+
os.makedirs(save_path, exist_ok=True)
|
| 335 |
+
|
| 336 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 337 |
+
prefix = str(index).zfill(8)
|
| 338 |
+
if video_length == 1:
|
| 339 |
+
video_path = os.path.join(save_path, prefix + ".png")
|
| 340 |
+
|
| 341 |
+
image = sample[0, :, 0]
|
| 342 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 343 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 344 |
+
image = Image.fromarray(image)
|
| 345 |
+
image.save(video_path)
|
| 346 |
+
else:
|
| 347 |
+
video_path = os.path.join(save_path, prefix + ".mp4")
|
| 348 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 349 |
+
|
| 350 |
+
if ulysses_degree * ring_degree > 1:
|
| 351 |
+
import torch.distributed as dist
|
| 352 |
+
if dist.get_rank() == 0:
|
| 353 |
+
save_results()
|
| 354 |
+
else:
|
| 355 |
+
save_results()
|
VideoX-Fun/examples/wan2.2_fun/app.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
current_file_path = os.path.abspath(__file__)
|
| 8 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 9 |
+
for project_root in project_roots:
|
| 10 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 11 |
+
|
| 12 |
+
from videox_fun.api.api import (infer_forward_api,
|
| 13 |
+
update_diffusion_transformer_api)
|
| 14 |
+
from videox_fun.ui.controller import flow_scheduler_dict
|
| 15 |
+
from videox_fun.ui.wan2_2_fun_ui import ui, ui_client, ui_host
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
# Choose the ui mode
|
| 19 |
+
# "normal" refers to the standard UI, which allows users to click to switch models, change model types, and more.
|
| 20 |
+
# "host" represents the hosting mode, where the model is loaded directly at startup and can be accessed via
|
| 21 |
+
# the API to return generation results.
|
| 22 |
+
# "client" represents the client mode, offering a simple UI that sends requests to a remote API for generation.
|
| 23 |
+
ui_mode = "normal"
|
| 24 |
+
|
| 25 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 26 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 27 |
+
#
|
| 28 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 29 |
+
#
|
| 30 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 31 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 32 |
+
#
|
| 33 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 34 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 35 |
+
GPU_memory_mode = "sequential_cpu_offload"
|
| 36 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 37 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 38 |
+
compile_dit = False
|
| 39 |
+
|
| 40 |
+
# Use torch.float16 if GPU does not support torch.bfloat16
|
| 41 |
+
# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat16
|
| 42 |
+
weight_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# Server ip
|
| 45 |
+
server_name = "0.0.0.0"
|
| 46 |
+
server_port = 7860
|
| 47 |
+
|
| 48 |
+
# Config path
|
| 49 |
+
config_path = "config/wan2.2/wan_civitai_i2v.yaml"
|
| 50 |
+
# Params below is used when ui_mode = "host"
|
| 51 |
+
# Model path of the pretrained model
|
| 52 |
+
model_name = "models/Diffusion_Transformer/Wan2.2-Fun-A14B-InP"
|
| 53 |
+
# "Inpaint" or "Control"
|
| 54 |
+
model_type = "Inpaint"
|
| 55 |
+
|
| 56 |
+
if ui_mode == "host":
|
| 57 |
+
demo, controller = ui_host(GPU_memory_mode, flow_scheduler_dict, model_name, model_type, config_path, compile_dit, weight_dtype)
|
| 58 |
+
elif ui_mode == "client":
|
| 59 |
+
demo, controller = ui_client(flow_scheduler_dict, model_name)
|
| 60 |
+
else:
|
| 61 |
+
demo, controller = ui(GPU_memory_mode, flow_scheduler_dict, config_path, compile_dit, weight_dtype)
|
| 62 |
+
|
| 63 |
+
def gr_launch():
|
| 64 |
+
# launch gradio
|
| 65 |
+
app, _, _ = demo.queue(status_update_rate=1).launch(
|
| 66 |
+
server_name=server_name,
|
| 67 |
+
server_port=server_port,
|
| 68 |
+
prevent_thread_lock=True
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# launch api
|
| 72 |
+
infer_forward_api(None, app, controller)
|
| 73 |
+
update_diffusion_transformer_api(None, app, controller)
|
| 74 |
+
|
| 75 |
+
gr_launch()
|
| 76 |
+
|
| 77 |
+
# not close the python
|
| 78 |
+
while True:
|
| 79 |
+
time.sleep(5)
|