JoaoK90's picture
Run Style-SALAD generation on ZeroGPU with the released 47 styles
cec303b verified
Raw History Blame Contribute Delete
12.4 kB
"""One shared model, serialized requests, isolated output directories."""
from pathlib import Path
import json
import os
import random
import sys
import tempfile
import threading
import time
import numpy as np
import yaml
from bootstrap import ensure_assets, UPSTREAM_COMMIT
from bvh_export import export_bvh
from catalog import ReferenceCatalog, dataset_root
from motion_io import FPS, read_motion, take_window, load_stats, normalize
from render import render_mp4
class Engine:
def __init__(self, source_root=None, output_root=None):
default_source = r"C:\Aulas\HTI Project\style-salad" if os.name == "nt" else "/opt/style-salad"
self.root = Path(source_root or os.environ.get("STYLE_SALAD_ROOT", default_source)).resolve()
self.outputs = Path(output_root or os.environ.get(
"SPACE_OUTPUT_DIR", str(Path(__file__).resolve().parent / "outputs"))).resolve()
self.lock = threading.Lock()
self.model = None
self.catalog = ReferenceCatalog(dataset_root(self.root), self.root)
def _load(self, report):
if self.model is not None:
return
if not (self.root / "configs/ours.yaml").is_file():
raise RuntimeError("Set STYLE_SALAD_ROOT to the Style-SALAD checkout.")
import torch
if not torch.cuda.is_available() and os.environ.get("ALLOW_CPU", "0") != "1":
raise RuntimeError("A CUDA GPU is required. CPU tests require ALLOW_CPU=1.")
ensure_assets(self.root, report)
# Upstream resolves checkpoint and CLIP paths relative to its cwd.
os.chdir(self.root)
for folder in (self.root, self.root / "src"):
if str(folder) not in sys.path:
sys.path.insert(0, str(folder))
from style_salad.models.t2sm import Text2StylizedMotion
from style_salad.utils.motion import recover_from_ric
config = yaml.safe_load((self.root / "configs/ours.yaml").read_text(encoding="utf-8"))
mean, std = load_stats(self.root / config["dataset_style"]["mean_path"],
self.root / config["dataset_style"]["std_path"])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
report("Loading the model and text encoder...")
model = Text2StylizedMotion(config["model"]).to(device)
checkpoint = self.root / "checkpoints/t2sm/ours/epoch_0100.ckpt"
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
# The published Style-SALAD checkpoint contains only trainable parameters.
# VAE loading is strict upstream; CLIP is loaded by from_pretrained.
# The frozen denoiser parameters come from the separate SALAD checkpoint.
denoiser_checkpoint = (Path(model.opt.checkpoints_dir) / model.opt.dataset_name
/ model.opt.name / "model" / "net_best_fid.tar")
base_denoiser = torch.load(denoiser_checkpoint, map_location="cpu", weights_only=True)
base_denoiser_keys = {"denoiser." + key for key in base_denoiser["denoiser"]}
model_keys = set(model.state_dict())
unknown_base_keys = base_denoiser_keys - model_keys
if unknown_base_keys:
raise RuntimeError("Incompatible base denoiser checkpoint: "
+ str(sorted(unknown_base_keys)[:8]))
preloaded_keys = (
{"vae." + key for key in model.vae.state_dict()}
| base_denoiser_keys
| {"denoiser.clip_model." + key for key in model.denoiser.clip_model.state_dict()}
)
trainable_keys = {name for name, parameter in model.named_parameters()
if parameter.requires_grad}
allowed_missing = preloaded_keys - trainable_keys
del base_denoiser
incompatible = model.load_state_dict(state, strict=False)
unexpected = list(incompatible.unexpected_keys)
missing = [key for key in incompatible.missing_keys
if key not in allowed_missing]
if missing or unexpected:
raise RuntimeError(f"Incompatible checkpoint: missing={missing[:8]}, unexpected={unexpected[:8]}")
model.eval()
for parameter in model.parameters():
parameter.requires_grad_(False)
self.config, self.mean, self.std = config, mean, std
self.device, self.recover = device, recover_from_ric
self.model = model
def run(self, style_path, caption, frames=120, seed=42, steps=34,
text_weight=7.5, style_weight=1.5, style_guidance=0.75,
content_path=None, report=lambda message: None, reference_info=None):
caption = str(caption or "").strip()
if not caption or len(caption) > 300:
raise ValueError("Describe the action in English, using at most 300 characters.")
frames, seed, steps = int(frames), int(seed), int(steps)
if not 40 <= frames <= 196 or frames % 4:
raise ValueError("Use 40 to 196 frames, in multiples of 4.")
if not 0 <= seed <= 2**31 - 1 or not 5 <= steps <= 100:
raise ValueError("Invalid seed or diffusion step count.")
for value, upper in [(text_weight, 15), (style_weight, 5), (style_guidance, 2)]:
if not np.isfinite(value) or not 0 <= value <= upper:
raise ValueError("Guidance value outside the allowed range.")
# Validate uploads before allocating GPU/model memory.
style_raw = read_motion(style_path)
content_raw = read_motion(content_path) if content_path else None
with self.lock:
self._load(report)
import torch
started = time.perf_counter()
style = take_window(style_raw, drop_first=self.config["dataset_style"].get("drop_first_frame", False))
content = take_window(content_raw, max_frames=frames) if content_raw is not None else None
length = content.frames if content is not None else frames
ref = torch.from_numpy(normalize(style.features, self.mean, self.std)).unsqueeze(0).to(self.device)
ref_lengths = torch.tensor([style.frames], device=self.device, dtype=torch.long)
lengths = torch.tensor([length], device=self.device, dtype=torch.long)
init_motion = None if content is None else torch.from_numpy(
normalize(content.features, self.mean, self.std)).unsqueeze(0).to(self.device)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if self.device.type == "cuda":
torch.cuda.manual_seed_all(seed)
self.model.config.update(text_weight=float(text_weight), style_weight=float(style_weight),
style_guidance=float(style_guidance))
guidance = {"num_inference_steps": steps}
if content is not None:
guidance["inversion"] = {"conditioning": "text"}
report("Generating motion..." if content is None else "Inverting and stylizing the content motion...")
if self.device.type == "cuda":
torch.cuda.synchronize()
inference_started = time.perf_counter()
try:
# Sampling guidance differentiates wrt latent z, even with frozen weights.
# inference_mode/no_grad would disable this upstream guidance.
with torch.enable_grad():
generated, _ = self.model.generate(
ref, [caption], lengths, ref_lengths, guidance=guidance,
init_motion=init_motion, init_lengths=lengths if content is not None else None,
)
generated = generated.detach()
if self.device.type == "cuda":
torch.cuda.synchronize()
inference_seconds = time.perf_counter() - inference_started
with torch.no_grad():
mean = torch.as_tensor(self.mean, device=self.device)
std = torch.as_tensor(self.std, device=self.device)
features = (generated[0, :length] * std + mean).cpu().numpy()
joints = self.recover(torch.from_numpy(features).unsqueeze(0), 22)[0].numpy()
ref_joints = self.recover(torch.from_numpy(style.features).unsqueeze(0), 22)[0].numpy()
content_joints = None if content is None else self.recover(
torch.from_numpy(content.features).unsqueeze(0), 22)[0].numpy()
if not np.isfinite(features).all() or not np.isfinite(joints).all():
raise RuntimeError("Generation produced invalid values. Try another reference or different settings.")
self.outputs.mkdir(parents=True, exist_ok=True)
folder = Path(tempfile.mkdtemp(prefix="motion-", dir=self.outputs))
report("Rendering videos...")
video = render_mp4(joints, folder / "generated.mp4", FPS)
reference = render_mp4(ref_joints, folder / "style_reference.mp4", FPS)
content_video = None if content_joints is None else render_mp4(
content_joints, folder / "content_reference.mp4", FPS)
report("Exporting the generated motion to BVH...")
bvh = export_bvh(joints, folder / "generated.bvh", FPS)
np.save(folder / "generated_features.npy", features.astype(np.float32), allow_pickle=False)
np.savez_compressed(folder / "generated_motion.npz", features=features, joints=joints,
fps=np.array(FPS), caption=np.array(caption))
info = {
"upstream_commit": UPSTREAM_COMMIT,
"checkpoint": "epoch_0100.ckpt", "caption": caption, "seed": seed,
"frames": length, "fps": FPS, "steps": steps,
"text_weight": float(text_weight), "style_weight": float(style_weight),
"style_guidance": float(style_guidance),
"style_reference": reference_info or {"selection": "upload", "filename": Path(style_path).name},
"style_first_frame": style.first_frame, "style_frames": style.frames,
"style_original_frames": style.original_frames,
"style_drop_first_frame": bool(self.config["dataset_style"].get("drop_first_frame", False)),
"content_first_frame": None if content is None else content.first_frame,
"content_frames": None if content is None else content.frames,
"content_original_frames": None if content is None else content.original_frames,
"mode": "text_and_style" if content is None else "ddim_inversion_experimental",
"device": str(self.device), "inference_seconds": inference_seconds,
"processing_seconds": time.perf_counter() - started,
"render": "22-joint skeleton; camera follows root; world-fixed 0.5 m checkerboard and trail",
"mp4_source": "generated features -> recover_from_ric -> joint positions (not BVH)",
"bvh": {key: value for key, value in bvh.items() if key != "path"},
}
(folder / "metadata.json").write_text(json.dumps(info, indent=2, ensure_ascii=False), encoding="utf-8")
return {
"video": str(video), "reference": str(reference),
"content_video": None if content_video is None else str(content_video),
"features": str(folder / "generated_features.npy"),
"motion": str(folder / "generated_motion.npz"),
"bvh": bvh["path"],
"metadata": str(folder / "metadata.json"), "info": info,
}
finally:
self.model.denoiser.remove_clip_cache()
self.model.denoiser.clear_hyper_lora_cache()
if self.device.type == "cuda":
torch.cuda.empty_cache()