trajloc / app.py
multimodalart's picture
multimodalart HF Staff
default 25 steps, measured duration
12e9dee verified
Raw History Blame Contribute Delete
19.1 kB
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import base64 # noqa: E402
import io # noqa: E402
import json # noqa: E402
import random # noqa: E402
import re # noqa: E402
import tempfile # noqa: E402
import time # noqa: E402
from pathlib import Path # noqa: E402
import cv2 # noqa: E402
import gradio as gr # noqa: E402
import numpy as np # noqa: E402
import torch # noqa: E402
import yaml # noqa: E402
from diffusers import ( # noqa: E402
AutoencoderKLCogVideoX,
CogVideoXDPMScheduler,
CogVideoXImageToVideoPipeline,
)
from diffusers.utils import export_to_video # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
from PIL import Image # noqa: E402
from safetensors.torch import load_file # noqa: E402
from transformers import T5EncoderModel, T5Tokenizer # noqa: E402
from canvas import CSS_TEMPLATE, HTML_TEMPLATE, JS_ON_LOAD # noqa: E402
from trajloc.backbones.cogvideox.constants import ( # noqa: E402
LATENT_SCALE,
MODEL_ID,
MODEL_REVISION,
TEXT_TOKEN_STD,
VAE_MODEL_ID,
VAE_MODEL_REVISION,
)
from trajloc.backbones.cogvideox.modules import build_conditioner # noqa: E402
from trajloc.backbones.cogvideox.stage2 import ( # noqa: E402
CogVideoXPromptEncoder,
CogVideoXVideoEncoder,
)
from trajloc.backbones.trajloc_modules import load_trajloc_modules # noqa: E402
from trajloc.core.conditioning import TrajectoryInputs # noqa: E402
from trajloc.core.config import TrajLocConfig # noqa: E402
from trajloc.core.trajectory_encoder import ( # noqa: E402
NUM_TRAJECTORY_TOKENS,
TrajectoryEncoder,
TrajectoryProjection,
TrajectoryTokenEncoder,
trajectory_token_strings,
)
from trajloc.datasets.caches import LatentCache, TextCache # noqa: E402
from trajloc.datasets.layout import CLIP_NUM_FRAMES, DatasetRoot # noqa: E402
from trajloc.generation.scene import SceneError, parse_scene # noqa: E402
from trajloc.preprocess.stage1.geometry import center_crop_window # noqa: E402
from trajloc.preprocess.stage1.records import write_json # noqa: E402
from trajloc.preprocess.stage2.models import TRAJECTORY_ENCODER_FRAMES # noqa: E402
from trajloc.preprocess.stage2.text_cache import TextCacheStep # noqa: E402
CKPT_REPO = "Omer-Sela/TrajLoc-CogVideoX-5B-I2V"
CKPT_REVISION = "237b326bfd1f667481beb78a46f055d5d7b116c4"
LORA_FILE = "pytorch_lora_weights.safetensors"
FPS = 8 # the authors' output frame rate
STEM = "scene"
DEVICE = "cuda"
# Exact inference-time speedup of the authors' attention processor: its full
# SDPA's video rows are overwritten by the supervised decomposition, so only
# the text rows of that SDPA are computed here (same output, ~half the attention).
import torch.nn.functional as F # noqa: E402
from trajloc.backbones.cogvideox.attention import SupervisedJointAttnProcessor # noqa: E402
_orig_supervised_attention = SupervisedJointAttnProcessor._supervised_attention
def _fast_supervised_attention(self, query, key, value, attention_mask, text_seq_length, batch_size):
if self._batched_mode or attention_mask is not None:
return _orig_supervised_attention(
self, query, key, value, attention_mask, text_seq_length, batch_size
)
text_out = F.scaled_dot_product_attention(
query[:, :, :text_seq_length], key, value, dropout_p=0.0, is_causal=False
)
video_out = self._supervised_video_rows(
query=query,
key=key,
value=value,
text_seq_length=text_seq_length,
supervised_positions=self.per_sample_positions[0],
heatmaps=self._flat_heatmaps.to(query.device, query.dtype).detach(),
batch_size=batch_size,
)
return torch.cat([text_out, video_out], dim=2)
SupervisedJointAttnProcessor._supervised_attention = _fast_supervised_attention
# --------------------------------------------------------------------- models
ckpt_dir = Path(
snapshot_download(
CKPT_REPO,
revision=CKPT_REVISION,
allow_patterns=["config.yaml", "*.safetensors"],
)
)
config = yaml.safe_load((ckpt_dir / "config.yaml").read_text())
trajloc_config = TrajLocConfig.from_mapping(config["trajloc"])
# Stage 2 (authors' preprocessing): the CogVideoX-5B (T2V) VAE for the frame-0
# latent, the I2V T5 (fp16) with the <traj_i> tokens added, the trajectory encoder.
video_encoder = CogVideoXVideoEncoder()
video_encoder.vae = AutoencoderKLCogVideoX.from_pretrained(
VAE_MODEL_ID, subfolder="vae", revision=VAE_MODEL_REVISION, torch_dtype=torch.bfloat16
).to(DEVICE).eval()
video_encoder.vae.enable_tiling()
video_encoder.vae.enable_slicing()
video_encoder.device = DEVICE
prompt_encoder = CogVideoXPromptEncoder()
_tok = T5Tokenizer.from_pretrained(MODEL_ID, subfolder="tokenizer", revision=MODEL_REVISION)
_te = T5EncoderModel.from_pretrained(
MODEL_ID, subfolder="text_encoder", revision=MODEL_REVISION, torch_dtype=torch.float16
)
_tok.add_tokens(trajectory_token_strings())
_te.resize_token_embeddings(len(_tok))
prompt_encoder.tokenizer = _tok
prompt_encoder.text_encoder = _te.to(DEVICE).eval()
prompt_encoder.device = DEVICE
trajectory_encoder = TrajectoryTokenEncoder(
TrajectoryEncoder(num_frames=TRAJECTORY_ENCODER_FRAMES, coords_dim=4, hidden=64, latent_dim=32),
TrajectoryProjection(latent_dim=32, text_embed_dim=4096),
token_std=TEXT_TOKEN_STD,
)
trajectory_encoder.load_state_dict(load_file(str(ckpt_dir / "trajectory_encoder.safetensors")))
trajectory_encoder = trajectory_encoder.to(DEVICE).eval()
# Generation: the I2V pipeline with the TrajLoc LoRA fused (scale 1.0), the
# trailing DPM scheduler, VAE slicing/tiling. The prompt embedding comes from
# Stage 2, so the pipeline's own T5 is not loaded.
pipe = CogVideoXImageToVideoPipeline.from_pretrained(
MODEL_ID, revision=MODEL_REVISION, text_encoder=None, torch_dtype=torch.bfloat16
)
pipe.load_lora_weights(str(ckpt_dir), weight_name=LORA_FILE, adapter_name="trajloc")
pipe.fuse_lora(components=["transformer"], lora_scale=1.0)
pipe.unload_lora_weights()
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
pipe.to(DEVICE)
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()
conditioner = build_conditioner(trajloc_config)
load_trajloc_modules(ckpt_dir, conditioner.supervisor, conditioner.appearance_encoder)
conditioner.to(DEVICE).eval()
# -------------------------------------------------------------------- helpers
def crop_first_frame(image) -> np.ndarray:
"""The image center-cropped to 3:2 and resized to 720x480 (RGB uint8), as the authors do."""
if isinstance(image, (str, Path)):
image = Image.open(image)
rgb = np.array(image.convert("RGB"))
h, w = rgb.shape[:2]
return center_crop_window(w, h).warp(rgb)
def to_data_url(rgb: np.ndarray) -> str:
buf = io.BytesIO()
Image.fromarray(rgb).save(buf, format="JPEG", quality=88)
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
_TRAJ = re.compile(r"<traj_(\d+)>")
def build_scene(prompt: str, trajectories: str):
"""A checked TrajLoc scene from the prompt and the trajectories JSON."""
prompt = " ".join((prompt or "").split())
try:
objects = json.loads(trajectories or "[]")
except json.JSONDecodeError as e:
raise gr.Error(f"Trajectories are not valid JSON: {e}")
if isinstance(objects, dict) and "objects" in objects:
objects = objects["objects"]
if not isinstance(objects, list) or not objects:
raise gr.Error("Draw at least one path on the first frame.")
if len(objects) > NUM_TRAJECTORY_TOKENS:
raise gr.Error(f"At most {NUM_TRAJECTORY_TOKENS} objects are supported.")
words = prompt.split()
found = sorted(int(m) for m in _TRAJ.findall(prompt))
if found != list(range(len(objects))):
tokens = " ".join(f"<traj_{i}>" for i in range(len(objects)))
raise gr.Error(
f"You drew {len(objects)} path(s), so the prompt needs exactly these tokens, each once, "
f"right after its object's noun: {tokens} (e.g. 'A green boat <traj_0>, a red boat <traj_1>. ...')"
)
scene_objects = []
for i, obj in enumerate(objects):
if not isinstance(obj, dict):
raise gr.Error(f"Object {i} must be a JSON object with 'keyframes' or 'positions'.")
obj = dict(obj)
if not obj.get("noun"):
# Default noun: the word right before <traj_i>.
idx = next(k for k, w in enumerate(words) if w.rstrip(",.") == f"<traj_{i}>")
if idx == 0:
raise gr.Error(f"<traj_{i}> must come right after its object's noun.")
obj["noun"] = words[idx - 1].rstrip(",.")
scene_objects.append(obj)
try:
return parse_scene({"prompt": prompt, "objects": scene_objects})
except SceneError as e:
raise gr.Error(str(e))
def _duration(image, prompt, trajectories, num_steps=25, *args, **kwargs):
# Measured on ZeroGPU: ~17 s fixed (Stage 2 + VAE decode) + ~6.6 s per step; +15%.
return int((20 + 6.7 * int(num_steps)) * 1.15)
# ----------------------------------------------------------------- inference
@spaces.GPU(duration=_duration)
@torch.no_grad()
def generate(
image,
prompt: str,
trajectories: str,
num_steps: int = 25,
guidance_scale: float = 6.0,
seed: int = 42,
randomize_seed: bool = False,
progress=gr.Progress(track_tqdm=True),
):
"""Animate a first frame so that each object follows its own trajectory (TrajLoc, CogVideoX-5B-I2V).
Args:
image: the first frame (center-cropped to 3:2, resized to 720x480).
prompt: the video description, with one `<traj_i>` token after each object's noun,
e.g. "A green boat <traj_0>, another fishing boat <traj_1>. Boats sail on a calm sea."
trajectories: JSON list, one entry per object i (= `<traj_i>`): {"keyframes": [[frame, x, y], ...]}
(frames 0..48, linearly interpolated) or {"positions": [[x, y] or null] * 49}; x, y in [0, 1]
relative to the 3:2 crop. An optional "noun" overrides the word before `<traj_i>`.
num_steps: sampling steps.
guidance_scale: classifier-free guidance scale (dynamic CFG).
seed: random seed.
randomize_seed: pick a random seed instead.
Returns:
The generated 49-frame 720x480 video (8 fps) and the seed used.
"""
if image is None:
raise gr.Error("Upload a first frame.")
if randomize_seed:
seed = random.randint(0, 2**31 - 1)
seed = int(seed)
frame = crop_first_frame(image) # (480, 720, 3) RGB
scene = build_scene(prompt, trajectories)
t0 = time.perf_counter()
with tempfile.TemporaryDirectory() as tmp:
root = DatasetRoot(Path(tmp))
for d in (root.trajectories_dir, root.prompts_dir):
d.mkdir(parents=True)
prompts_rec, traj_rec = scene.records(frame.shape[1], frame.shape[0])
files = root.clip_files(STEM)
write_json(files.prompts, prompts_rec)
write_json(files.trajectories, traj_rec)
# Stage 2: the frame-0 latent (VAE samples with the global RNG) ...
torch.manual_seed(seed)
video = torch.from_numpy(np.stack([frame] * CLIP_NUM_FRAMES)).permute(0, 3, 1, 2)
video = video.float() / 127.5 - 1.0
latent_cache = LatentCache.from_payload(
video_encoder.encode(video, f"{STEM}.mp4").to_payload()
)
# ... and the text cache (<traj_i> embeddings written into the prompt).
step = TextCacheStep(root.path, "cogvideox", dataset_name="generate", device=DEVICE,
encoder=prompt_encoder)
step.trajectory_encoder = trajectory_encoder
payload = step.process(STEM)
if payload is None:
raise gr.Error("Could not build the trajectory conditioning for this scene.")
cache = TextCache.from_payload(payload)
print(f"[trajloc] stage 2 done in {time.perf_counter() - t0:.1f}s", flush=True)
# Generation, as CogVideoXGenerator.generate.
frame0_latent = latent_cache.frame0_latent
clip_height, clip_width = trajloc_config.video_size
prompt_embedding = cache.prompt_embedding.unsqueeze(0).to(DEVICE, dtype=torch.bfloat16)
inputs = TrajectoryInputs(
frame0_latents=frame0_latent.unsqueeze(0).to(DEVICE, dtype=torch.float32),
trajectory_coords=cache.trajectory_coords.unsqueeze(0).to(DEVICE, dtype=torch.bfloat16),
trajectory_starts=cache.trajectory_starts.unsqueeze(0).to(DEVICE, dtype=torch.float32),
num_objects=torch.tensor([cache.num_objects]),
trajectory_token_positions=[cache.trajectory_token_positions],
noun_token_positions=[cache.noun_token_positions],
)
with conditioner.conditioned(pipe.transformer, prompt_embedding, inputs) as cond_prompt:
frames = pipe(
image=Image.fromarray(frame),
prompt_embeds=cond_prompt,
negative_prompt_embeds=torch.zeros_like(cond_prompt),
num_frames=trajloc_config.num_frames,
height=clip_height,
width=clip_width,
num_inference_steps=int(num_steps),
guidance_scale=float(guidance_scale),
use_dynamic_cfg=True,
generator=torch.Generator(device=DEVICE).manual_seed(seed),
).frames[0]
print(f"[trajloc] generated {len(frames)} frames in {time.perf_counter() - t0:.1f}s "
f"(steps={num_steps}, objects={cache.num_objects})", flush=True)
out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
export_to_video(frames, out, fps=FPS)
return out, seed
def on_image(image):
if image is None:
return gr.HTML(image_url="")
return gr.HTML(image_url=to_data_url(crop_first_frame(image)))
# --------------------------------------------------------------------- examples
def _kf(*pts):
"""Uniform-speed keyframes over 49 frames through the given (x, y) points."""
n = len(pts)
return [[round(48 * k / (n - 1)), x, y] for k, (x, y) in enumerate(pts)]
_boats = json.loads(Path("examples/boats.json").read_text())
EXAMPLES = [
[
"examples/boats.png",
_boats["prompt"],
json.dumps([{"positions": o["positions"]} for o in _boats["objects"]]),
],
[
"examples/rubber_ducks.jpg",
"A small rubber duck <traj_0>, a medium rubber duck <traj_1>, and a large rubber duck "
"<traj_2>. The camera remains stationary. Three yellow rubber ducks glide across a glossy "
"black reflective surface, each casting a clear mirror reflection beneath it, against a "
"completely black background with dramatic side lighting.",
json.dumps([
{"keyframes": _kf((0.221, 0.45), (0.16, 0.48), (0.10, 0.52))},
{"keyframes": _kf((0.426, 0.40), (0.47, 0.47), (0.50, 0.55))},
{"keyframes": _kf((0.698, 0.37), (0.76, 0.37), (0.84, 0.38))},
]),
],
[
"examples/sailboat_ocean.jpg",
"A white sailboat <traj_0> sails across the vast deep-blue rippled open ocean. The camera "
"remains stationary. A hazy pale-blue sky sits above a high horizon, cool even daylight, "
"the small vessel dwarfed by the water as it glides steadily to the right.",
json.dumps([{"keyframes": _kf((0.508, 0.39), (0.66, 0.40), (0.82, 0.41))}]),
],
]
# ------------------------------------------------------------------------- UI
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks() as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# TrajLoc: Trajectory-Attention Localization for Multi-Object Motion Control\n"
"Upload a first frame, **drag one path per object**, and write a prompt with "
"`<traj_i>` right after each object's noun. TrajLoc (CogVideoX-5B-I2V) generates a "
"49-frame video where every object follows its own path. \n"
"[Paper](https://huggingface.co/papers/2607.00861) 路 "
"[Project page](https://sela-omer.github.io/traj-loc/) 路 "
"[Code](https://github.com/Sela-Omer/traj-loc) 路 "
"[Model](https://huggingface.co/Omer-Sela/TrajLoc-CogVideoX-5B-I2V)"
)
with gr.Row():
with gr.Column(scale=1):
image = gr.Image(label="First frame (center-cropped to 3:2)", type="pil", height=260)
editor = gr.HTML(
value="[]",
html_template=HTML_TEMPLATE,
css_template=CSS_TEMPLATE,
js_on_load=JS_ON_LOAD,
image_url="",
label="Trajectory editor",
)
prompt = gr.Textbox(
label="Prompt",
lines=3,
placeholder="A green boat <traj_0>, another fishing boat <traj_1>. Two fishing boats sail on the calm sea. The camera remains stationary.",
)
run = gr.Button("Generate video", variant="primary")
with gr.Column(scale=1):
video_out = gr.Video(label="Generated video", autoplay=True, loop=True)
with gr.Accordion("Advanced settings", open=False):
trajectories = gr.Textbox(
label="Trajectories (JSON, synced with the editor)",
value="[]",
lines=4,
info='One entry per object i = <traj_i>: {"keyframes": [[frame, x, y], ...]} '
'or {"positions": [[x, y] | null] x 49}; optional "noun".',
)
num_steps = gr.Slider(10, 50, value=25, step=1, label="Sampling steps (paper: 50)")
guidance_scale = gr.Slider(1.0, 12.0, value=6.0, step=0.5, label="Guidance scale")
with gr.Row():
seed = gr.Number(label="Seed", value=42, precision=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
gr.Examples(
examples=EXAMPLES,
inputs=[image, prompt, trajectories],
outputs=[video_out, seed],
fn=generate,
cache_examples=True,
cache_mode="lazy",
)
image.change(on_image, inputs=image, outputs=editor, api_visibility="private")
editor.change(lambda v: v, inputs=editor, outputs=trajectories, api_visibility="private")
trajectories.change(lambda v: v, inputs=trajectories, outputs=editor, api_visibility="private")
run.click(
generate,
inputs=[image, prompt, trajectories, num_steps, guidance_scale, seed, randomize_seed],
outputs=[video_out, seed],
api_name="generate",
concurrency_limit=1,
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)