Spaces:
Running
on
Zero
Running
on
Zero
File size: 10,459 Bytes
5925ea4 b2baa38 c44ad11 b2baa38 5925ea4 b2baa38 5925ea4 c44ad11 5925ea4 b573d19 5925ea4 b573d19 11d4598 5925ea4 b573d19 5925ea4 b2baa38 c44ad11 b2baa38 5925ea4 b2baa38 ece32ef b2baa38 c44ad11 b573d19 b2baa38 ece32ef 5925ea4 b573d19 5925ea4 35a5c71 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 35a5c71 b2baa38 b573d19 3e5f523 b573d19 3e5f523 5925ea4 3e5f523 c44ad11 3e5f523 b573d19 3e5f523 b573d19 c44ad11 b573d19 c44ad11 5925ea4 b2baa38 c44ad11 b2baa38 5925ea4 c44ad11 b573d19 b2baa38 5925ea4 b2baa38 c44ad11 5925ea4 c44ad11 5925ea4 b2baa38 5925ea4 b2baa38 5925ea4 b2baa38 5925ea4 b2baa38 c44ad11 5925ea4 c44ad11 5925ea4 b2baa38 5925ea4 c44ad11 b2baa38 5925ea4 76410ab b573d19 c44ad11 b573d19 76410ab c44ad11 35a5c71 c44ad11 5925ea4 76410ab 5925ea4 b2baa38 c44ad11 5925ea4 b573d19 c44ad11 5925ea4 b573d19 5925ea4 c44ad11 b573d19 5925ea4 b573d19 5925ea4 b573d19 5925ea4 c44ad11 b573d19 5925ea4 b573d19 5925ea4 b573d19 c44ad11 5925ea4 c44ad11 b573d19 5925ea4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
import gradio as gr
import torch
import os
import sys
import subprocess
import tempfile
import numpy as np
import site
import importlib
from PIL import Image
from huggingface_hub import snapshot_download, hf_hub_download
# ============================================================
# 0️⃣ Install required packages
# ============================================================
subprocess.run(["pip3", "install", "-U", "cache-dit"], check=True)
import cache_dit
# ============================================================
# 1️⃣ Repository & Weights
# ============================================================
REPO_PATH = "LongCat-Video"
CHECKPOINT_DIR = os.path.join(REPO_PATH, "weights", "LongCat-Video")
if not os.path.exists(REPO_PATH):
subprocess.run(
["git", "clone", "https://github.com/meituan-longcat/LongCat-Video.git", REPO_PATH],
check=True
)
sys.path.insert(0, os.path.abspath(REPO_PATH))
from longcat_video.pipeline_longcat_video import LongCatVideoPipeline
from longcat_video.modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan
from longcat_video.modules.longcat_video_dit import LongCatVideoTransformer3DModel
from longcat_video.context_parallel import context_parallel_util
from transformers import AutoTokenizer, UMT5EncoderModel
from diffusers.utils import export_to_video
from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
if not os.path.exists(CHECKPOINT_DIR):
snapshot_download(
repo_id="meituan-longcat/LongCat-Video",
local_dir=CHECKPOINT_DIR,
local_dir_use_symlinks=False,
ignore_patterns=["*.md", "*.gitattributes", "assets/*"]
)
# ============================================================
# 2️⃣ Device & Models (with cache & quantization)
# ============================================================
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.bfloat16 if device=="cuda" else torch.float32
pipe = None
try:
cp_split_hw = context_parallel_util.get_optimal_split(1)
tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_DIR, subfolder="tokenizer", torch_dtype=torch_dtype)
# Text encoder with 4-bit quantization
text_encoder = UMT5EncoderModel.from_pretrained(
CHECKPOINT_DIR,
subfolder="text_encoder",
torch_dtype=torch_dtype,
quantization_config=TransformersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch_dtype
)
)
vae = AutoencoderKLWan.from_pretrained(CHECKPOINT_DIR, subfolder="vae", torch_dtype=torch_dtype)
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(CHECKPOINT_DIR, subfolder="scheduler", torch_dtype=torch_dtype)
# DiT model with FP8/4-bit quantization + cache
dit = LongCatVideoTransformer3DModel.from_pretrained(
CHECKPOINT_DIR,
enable_flashattn3=enable_fa3,
enable_xformers=True,
subfolder="dit",
cp_split_hw=cp_split_hw,
torch_dtype=torch_dtype
)
# Enable Cache-DiT
cache_dit.enable_cache(
cache_dit.BlockAdapter(
transformer=dit,
blocks=dit.blocks,
forward_pattern=cache_dit.ForwardPattern.Pattern_3,
check_forward_pattern=False,
has_separate_cfg=False
),
cache_config=cache_dit.DBCacheConfig(
Fn_compute_blocks=1,
Bn_compute_blocks=1,
max_warmup_steps=5,
max_cached_steps=50,
max_continuous_cached_steps=50,
residual_diff_threshold=0.01,
num_inference_steps=50
)
)
pipe = LongCatVideoPipeline(
tokenizer=tokenizer,
text_encoder=text_encoder,
vae=vae,
scheduler=scheduler,
dit=dit,
)
pipe.to(device)
print("✅ Models loaded with Cache-DiT and quantization")
except Exception as e:
print(f"❌ Failed to load models: {e}")
pipe = None
# ============================================================
# 3️⃣ Generation Helper
# ============================================================
def torch_gc():
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
def check_duration(
mode,
prompt,
neg_prompt,
image,
height, width, resolution,
seed,
use_distill,
use_refine,
progress
):
if use_distill and resolution=="480p":
return 180
elif resolution=="720p":
return 360
else:
return 900
@spaces.GPU(duration=180)
def generate_video(mode, prompt, neg_prompt, image, height, width, resolution,
seed, use_distill, use_refine, duration_sec, progress=gr.Progress(track_tqdm=True)):
if pipe is None:
raise gr.Error("Models not loaded")
fps = 15 if use_distill else 30
num_frames = int(duration_sec * fps)
generator = torch.Generator(device=device).manual_seed(int(seed))
is_distill = use_distill or use_refine
progress(0.2, desc="Stage 1: Base Video Generation")
pipe.dit.enable_loras(['cfg_step_lora'] if is_distill else [])
num_inference_steps = 12 if is_distill else 24
guidance_scale = 2.0 if is_distill else 4.0
curr_neg_prompt = "" if is_distill else neg_prompt
if mode=="t2v":
output = pipe.generate_t2v(
prompt=prompt,
negative_prompt=curr_neg_prompt,
height=height,
width=width,
num_frames=num_frames,
num_inference_steps=num_inference_steps,
use_distill=is_distill,
guidance_scale=guidance_scale,
generator=generator
)[0]
else:
pil_img = Image.fromarray(image)
output = pipe.generate_i2v(
image=pil_img,
prompt=prompt,
negative_prompt=curr_neg_prompt,
resolution=resolution,
num_frames=num_frames,
num_inference_steps=num_inference_steps,
use_distill=is_distill,
guidance_scale=guidance_scale,
generator=generator
)[0]
pipe.dit.disable_all_loras()
torch_gc()
if use_refine:
progress(0.5, desc="Stage 2: Refinement")
pipe.dit.enable_loras(['refinement_lora'])
pipe.dit.enable_bsa()
stage1_video_pil = [(frame*255).astype(np.uint8) for frame in output]
stage1_video_pil = [Image.fromarray(img) for img in stage1_video_pil]
refine_image = Image.fromarray(image) if mode=='i2v' else None
output = pipe.generate_refine(
image=refine_image,
prompt=prompt,
stage1_video=stage1_video_pil,
num_cond_frames=1 if mode=='i2v' else 0,
num_inference_steps=50,
generator=generator
)[0]
pipe.dit.disable_all_loras()
pipe.dit.disable_bsa()
torch_gc()
progress(1.0, desc="Exporting video")
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
export_to_video(output, f.name, fps=fps)
return f.name
# ============================================================
# 4️⃣ Gradio UI
# ============================================================
css=".fillable{max-width:960px !important}"
with gr.Blocks(css=css) as demo:
gr.Markdown("# 🎬 LongCat-Video with Cache-DiT & Quantization")
gr.Markdown("13.6B parameter dense video-generation model by Meituan — [[Model](https://huggingface.co/meituan-longcat/LongCat-Video)]")
with gr.Tabs():
# Text-to-Video
with gr.TabItem("Text-to-Video"):
mode_t2v = gr.State("t2v")
with gr.Row():
with gr.Column(scale=2):
prompt_t2v = gr.Textbox(label="Prompt", lines=4)
neg_prompt_t2v = gr.Textbox(label="Negative Prompt", lines=2, value="blurry, low quality")
height_t2v = gr.Slider(256,1024,step=64,value=480,label="Height")
width_t2v = gr.Slider(256,1024,step=64,value=832,label="Width")
seed_t2v = gr.Number(value=42,label="Seed")
distill_t2v = gr.Checkbox(value=True,label="Use Distill Mode")
refine_t2v = gr.Checkbox(value=False,label="Use Refine Mode")
duration_t2v = gr.Slider(1,20,step=1,value=2,label="Video Duration (seconds)")
t2v_button = gr.Button("Generate Video")
with gr.Column(scale=3):
video_output_t2v = gr.Video(label="Generated Video")
# Image-to-Video
with gr.TabItem("Image-to-Video"):
mode_i2v = gr.State("i2v")
with gr.Row():
with gr.Column(scale=2):
image_i2v = gr.Image(type="numpy", label="Input Image")
prompt_i2v = gr.Textbox(label="Prompt", lines=4)
neg_prompt_i2v = gr.Textbox(label="Negative Prompt", lines=2, value="blurry, low quality")
resolution_i2v = gr.Dropdown(["480p","720p"], value="480p", label="Resolution")
seed_i2v = gr.Number(value=42,label="Seed")
distill_i2v = gr.Checkbox(value=True,label="Use Distill Mode")
refine_i2v = gr.Checkbox(value=False,label="Use Refine Mode")
duration_i2v = gr.Slider(1,20,step=1,value=2,label="Video Duration (seconds)")
i2v_button = gr.Button("Generate Video")
with gr.Column(scale=3):
video_output_i2v = gr.Video(label="Generated Video")
# Bind events
t2v_button.click(
generate_video,
inputs=[mode_t2v, prompt_t2v, neg_prompt_t2v, gr.State(None),
height_t2v, width_t2v, gr.State("480p"),
seed_t2v, distill_t2v, refine_t2v, duration_t2v],
outputs=video_output_t2v
)
i2v_button.click(
generate_video,
inputs=[mode_i2v, prompt_i2v, neg_prompt_i2v, image_i2v,
gr.State(None), gr.State(None), resolution_i2v,
seed_i2v, distill_i2v, refine_i2v, duration_i2v],
outputs=video_output_i2v
)
# Launch
if __name__=="__main__":
demo.launch() |