temp / Helios /_DEV2 /bench_infer.py
Cccccz's picture
Add files using upload-large-folder tool
29b7783 verified
Raw
History Blame Contribute Delete
20.7 kB
"""
Helios Benchmark Inference Script
- Runs T2V inference for a single model version on a single GPU
- Uses the first N prompts from a txt file
- Saves videos in two layouts: by_prompt/<slug>/<version>.mp4
by_version/<version>/<slug>.mp4
- Records per-video timing to timing_<version>.txt and computes summary stats
"""
import importlib
import os
import re
import shutil
import sys
import time
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
import argparse
import subprocess
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_PROMPT_FILE = SCRIPT_DIR / "demo_data" / "MovieGenVideoBench_extended.txt"
DEFAULT_MODEL_ROOT = SCRIPT_DIR / "checkpoints"
DEFAULT_OUTPUT_ROOT = SCRIPT_DIR / "output_helios" / "bench"
def pick_gpu_by_free_vram(min_free_mib=20000):
"""Pick physical GPU index with the most free memory (via nvidia-smi). No torch import."""
try:
out = subprocess.check_output(
[
"nvidia-smi",
"--query-gpu=index,memory.free",
"--format=csv,noheader,nounits",
],
text=True,
stderr=subprocess.DEVNULL,
)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
raise RuntimeError("nvidia-smi failed; specify --gpu explicitly") from e
best_idx, best_free = None, -1
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 2:
continue
idx, free = int(parts[0]), int(parts[1])
if free > best_free:
best_free, best_idx = free, idx
if best_idx is None:
raise RuntimeError("Could not parse nvidia-smi GPU list")
if best_free < min_free_mib:
print(
f"[warn] Best GPU {best_idx} has only {best_free} MiB free "
f"(<{min_free_mib} MiB); OOM risk — consider --enable_low_vram_mode",
file=sys.stderr,
)
return best_idx, best_free
def _apply_cuda_visible_devices_before_torch():
"""CUDA_VISIBLE_DEVICES must be set before `import torch` (first CUDA init)."""
pre = argparse.ArgumentParser(add_help=False)
pre.add_argument("--gpu", type=str, default="auto")
known, _ = pre.parse_known_args()
g = known.gpu.strip().lower()
if g == "auto":
idx, free = pick_gpu_by_free_vram()
os.environ["CUDA_VISIBLE_DEVICES"] = str(idx)
os.environ["_BENCH_PHYSICAL_GPU"] = f"{idx} ({free} MiB free)"
else:
os.environ["CUDA_VISIBLE_DEVICES"] = known.gpu.strip()
os.environ["_BENCH_PHYSICAL_GPU"] = known.gpu.strip()
os.environ["_BENCH_GPU_ARG"] = known.gpu.strip()
_apply_cuda_visible_devices_before_torch()
import torch
from tqdm import tqdm
if importlib.util.find_spec("torch_npu") is not None:
import torch_npu # noqa: F401
from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
from helios.modules.helios_kernels import (
replace_all_norms_with_flash_norms,
replace_rmsnorm_with_fp32,
replace_rope_with_flash_rope,
)
from diffusers.models import AutoencoderKLWan
from diffusers.utils import export_to_video
# ── per-version inference presets (matching official scripts) ─────────────────
MODEL_PRESETS = {
"base": dict(
model_dir="Helios-Base",
num_frames=99,
num_inference_steps=50,
guidance_scale=5.0,
is_enable_stage2=False,
pyramid_num_inference_steps_list=[20, 20, 20],
is_amplify_first_chunk=False,
use_zero_init=False,
zero_steps=1,
),
"mid": dict(
model_dir="Helios-Mid",
num_frames=99,
num_inference_steps=50,
guidance_scale=5.0,
is_enable_stage2=True,
pyramid_num_inference_steps_list=[20, 20, 20],
is_amplify_first_chunk=False,
use_zero_init=True,
zero_steps=1,
),
"distilled": dict(
model_dir="Helios-Distilled",
num_frames=240,
num_inference_steps=50,
guidance_scale=1.0,
is_enable_stage2=True,
pyramid_num_inference_steps_list=[2, 2, 2],
is_amplify_first_chunk=True,
use_zero_init=False,
zero_steps=1,
),
}
NEGATIVE_PROMPT = (
"Bright tones, overexposed, static, blurred details, subtitles, style, "
"works, paintings, images, static, overall gray, worst quality, low quality, "
"JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, "
"poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, "
"still picture, messy background, three legs, many people in the background, "
"walking backwards"
)
def sanitize_filename(text, max_len=80):
"""Turn a prompt into a filesystem-safe slug."""
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "_", text)
text = text.strip("_")
return text[:max_len]
def load_prompt_indices(path):
indices = []
with open(path, "r", encoding="utf-8") as f:
for line_no, raw_line in enumerate(f, start=1):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
try:
idx = int(line)
except ValueError as exc:
raise ValueError(
f"Invalid prompt index at {path}:{line_no}: {line!r}"
) from exc
if idx < 0:
raise ValueError(f"Prompt index must be >= 0 at {path}:{line_no}")
indices.append(idx)
return indices
def load_prompts(path, prompt_start=0, prompt_end=None, prompt_indices=None):
with open(path, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f if line.strip()]
if prompt_indices is not None:
selected = []
total = len(lines)
for idx in prompt_indices:
if idx >= total:
raise ValueError(
f"Prompt index {idx} is out of range; prompt file has {total} prompts"
)
selected.append((idx, lines[idx]))
return selected
if prompt_start < 0:
raise ValueError("prompt_start must be >= 0")
if prompt_end is not None and prompt_end < prompt_start:
raise ValueError("prompt_end must be >= prompt_start")
selected = lines[prompt_start:prompt_end]
return [(prompt_start + offset, prompt) for offset, prompt in enumerate(selected)]
def build_expected_outputs(prompts, version, by_version_dir):
version_dir = os.path.join(by_version_dir, version)
expected = []
for idx, prompt in prompts:
slug = sanitize_filename(prompt)
vid_name = f"{idx:04d}_{slug}"
expected.append((idx, slug, os.path.join(version_dir, f"{vid_name}.mp4")))
return version_dir, expected
def output_exists(path):
return os.path.isfile(path) and os.path.getsize(path) > 0
def find_missing_outputs(expected_outputs):
return [item for item in expected_outputs if not output_exists(item[2])]
def make_timing_line(version, idx, elapsed, slug):
return (
f" {version:10s} #{idx:04d} {elapsed:8.2f}s "
f"({elapsed / 60:5.2f}min) {slug[:50]}"
)
def load_existing_timing_records(timing_file, version):
if not os.path.exists(timing_file):
return {}
pattern = re.compile(
rf"^\s*{re.escape(version)}\s+#(\d+)\s+([0-9.]+)s\s+\([^)]+\)\s+(.*)$"
)
records = {}
with open(timing_file, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.rstrip("\n")
match = pattern.match(line)
if not match:
continue
idx = int(match.group(1))
elapsed = float(match.group(2))
slug = match.group(3)
records[idx] = (elapsed, slug)
return records
def build_pipeline(
model_path,
device,
weight_dtype,
enable_low_vram=False,
group_offloading_type="leaf_level",
num_blocks_per_group=4,
):
transformer = HeliosTransformer3DModel.from_pretrained(
model_path, subfolder="transformer", torch_dtype=weight_dtype,
)
transformer = replace_rmsnorm_with_fp32(transformer)
transformer = replace_all_norms_with_flash_norms(transformer)
replace_rope_with_flash_rope()
cuda_major = torch.cuda.get_device_capability()[0]
if cuda_major >= 9:
try:
transformer.set_attention_backend("_flash_3_hub")
except Exception:
transformer.set_attention_backend("flash_hub")
else:
transformer.set_attention_backend("flash_hub")
vae = AutoencoderKLWan.from_pretrained(
model_path, subfolder="vae", torch_dtype=torch.float32,
)
scheduler = HeliosScheduler.from_pretrained(model_path, subfolder="scheduler")
pipe = HeliosPipeline.from_pretrained(
model_path,
transformer=transformer,
vae=vae,
scheduler=scheduler,
torch_dtype=weight_dtype,
)
if enable_low_vram:
nbg = int(num_blocks_per_group) if group_offloading_type == "block_level" else None
pipe.enable_group_offload(
onload_device=torch.device("cuda"),
offload_device=torch.device("cpu"),
offload_type=group_offloading_type,
num_blocks_per_group=nbg,
use_stream=True,
record_stream=True,
)
else:
pipe = pipe.to(device)
return pipe
def run_single(pipe, prompt, preset, height, width, seed):
gen = torch.Generator(device="cuda").manual_seed(seed)
t0 = time.time()
with torch.no_grad():
output = pipe(
prompt=prompt,
negative_prompt=NEGATIVE_PROMPT,
height=height,
width=width,
num_frames=preset["num_frames"],
num_inference_steps=preset["num_inference_steps"],
guidance_scale=preset["guidance_scale"],
generator=gen,
history_sizes=[16, 2, 1],
num_latent_frames_per_chunk=9,
keep_first_frame=True,
is_enable_stage2=preset["is_enable_stage2"],
pyramid_num_inference_steps_list=preset["pyramid_num_inference_steps_list"],
is_skip_first_chunk=False,
is_amplify_first_chunk=preset["is_amplify_first_chunk"],
use_zero_init=preset["use_zero_init"],
zero_steps=preset["zero_steps"],
).frames[0]
elapsed = time.time() - t0
return output, elapsed
def _parse_gpu(s):
if isinstance(s, str) and s.lower() == "auto":
return "auto"
return int(s)
def parse_args():
p = argparse.ArgumentParser(description="Helios benchmark inference for one model version")
p.add_argument("--prompt_file", type=str,
default=str(DEFAULT_PROMPT_FILE))
p.add_argument("--prompt_start", type=int, default=0)
p.add_argument("--prompt_end", type=int, default=100,
help="Exclusive end index for prompts, e.g. 50 means up to #49")
p.add_argument("--prompt_indices_file", type=str, default=None,
help="Optional file containing exact prompt indices to run, one per line")
p.add_argument("--model_root", type=str, default=str(DEFAULT_MODEL_ROOT),
help="Parent dir containing Helios-Base / Helios-Mid / Helios-Distilled")
p.add_argument("--output_root", type=str, default=str(DEFAULT_OUTPUT_ROOT))
p.add_argument("--version", type=str, choices=sorted(MODEL_PRESETS.keys()), required=True,
help="Which model version to run")
p.add_argument("--timing_file", type=str, default=None,
help="Optional override for timing report path")
p.add_argument("--height", type=int, default=384)
p.add_argument("--width", type=int, default=640)
p.add_argument("--num_frames", type=int, default=None,
help="Override preset frame count for all selected versions")
p.add_argument("--seed", type=int, default=42)
p.add_argument(
"--gpu",
type=_parse_gpu,
default="auto",
help='Physical GPU id or "auto" (pick most free VRAM via nvidia-smi)',
)
p.add_argument(
"--enable_low_vram_mode",
action="store_true",
help="CPU group-offload (slower, less VRAM); use if GPU is shared or OOM",
)
p.add_argument(
"--group_offloading_type",
type=str,
choices=["leaf_level", "block_level"],
default="leaf_level",
)
p.add_argument("--num_blocks_per_group", type=int, default=4)
return p.parse_args()
def main():
args = parse_args()
if not os.path.isfile(args.prompt_file):
raise FileNotFoundError(f"Prompt file not found: {args.prompt_file}")
if not os.path.isdir(args.model_root):
raise FileNotFoundError(f"Model root not found: {args.model_root}")
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
device = torch.device("cuda")
weight_dtype = torch.bfloat16
prompt_indices = None
if args.prompt_indices_file:
if not os.path.isfile(args.prompt_indices_file):
raise FileNotFoundError(f"Prompt indices file not found: {args.prompt_indices_file}")
prompt_indices = load_prompt_indices(args.prompt_indices_file)
prompts = load_prompts(
args.prompt_file,
args.prompt_start,
args.prompt_end,
prompt_indices=prompt_indices,
)
prompt_map = dict(prompts)
if args.prompt_indices_file:
print(
f"Loaded {len(prompts)} prompts from {args.prompt_file} "
f"(indices: {args.prompt_indices_file})"
)
else:
print(
f"Loaded {len(prompts)} prompts from {args.prompt_file} "
f"(range: {args.prompt_start}:{args.prompt_end})"
)
if args.num_frames is not None:
MODEL_PRESETS[args.version]["num_frames"] = args.num_frames
by_prompt_dir = os.path.join(args.output_root, "by_prompt")
by_version_dir = os.path.join(args.output_root, "by_version")
timing_file = args.timing_file or os.path.join(args.output_root, f"timing_{args.version}.txt")
os.makedirs(args.output_root, exist_ok=True)
preset = MODEL_PRESETS[args.version]
model_path = os.path.join(args.model_root, preset["model_dir"])
timing_records = load_existing_timing_records(timing_file, args.version)
selected_indices = set(prompt_map)
timing_records = {
idx: record for idx, record in timing_records.items() if idx in selected_indices
}
ver_dir, expected_outputs = build_expected_outputs(prompts, args.version, by_version_dir)
missing_outputs = find_missing_outputs(expected_outputs)
if not os.path.isdir(model_path):
raise FileNotFoundError(f"Model not found: {model_path}")
peak_mem = None
if not missing_outputs:
print(
f"[SKIP] All outputs already exist for version={args.version} under {ver_dir}"
)
else:
header = (
f"\n{'=' * 60}\n"
f" Version: {args.version} | Model: {preset['model_dir']}\n"
f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
f"{'=' * 60}\n"
)
print(header)
pipe = build_pipeline(
model_path,
device,
weight_dtype,
enable_low_vram=args.enable_low_vram_mode,
group_offloading_type=args.group_offloading_type,
num_blocks_per_group=args.num_blocks_per_group,
)
os.makedirs(ver_dir, exist_ok=True)
print(
f"[resume] version={args.version} existing={len(expected_outputs) - len(missing_outputs)} "
f"missing={len(missing_outputs)} timed={len(timing_records)}"
)
for idx, slug, ver_out in tqdm(missing_outputs, desc=f"[{args.version}]"):
if os.path.exists(ver_out):
print(f" [skip] {ver_out}")
continue
try:
frames, elapsed = run_single(
pipe, prompt_map[idx], preset, args.height, args.width, args.seed,
)
except Exception as e:
msg = f" [FAIL] {args.version} #{idx:04d}: {e}"
print(msg)
continue
export_to_video(frames, ver_out, fps=24)
vid_name = os.path.splitext(os.path.basename(ver_out))[0]
prompt_dir = os.path.join(by_prompt_dir, vid_name)
os.makedirs(prompt_dir, exist_ok=True)
shutil.copy2(ver_out, os.path.join(prompt_dir, f"{args.version}.mp4"))
timing_records[idx] = (elapsed, slug)
print(make_timing_line(args.version, idx, elapsed, slug))
peak_mem = torch.cuda.max_memory_allocated() / 1024 ** 3
print(f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB")
del pipe
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
sorted_records = [timing_records[idx] for idx in sorted(timing_records)]
all_timings = [elapsed for elapsed, _ in sorted_records]
with open(timing_file, "w", encoding="utf-8") as tf:
tf.write(f"{'=' * 80}\n")
tf.write(f" Helios Benchmark Inference Timing Report\n")
tf.write(f" {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
tf.write(
f" Prompts: {len(prompts)} | Range: {args.prompt_start}:{args.prompt_end} "
f"| Version: {args.version}\n"
)
if args.prompt_indices_file:
tf.write(f" Prompt indices file: {args.prompt_indices_file}\n")
tf.write(
f" Resolution: {args.width}x{args.height} | Seed: {args.seed} | "
f"GPU: {args.gpu} | low_vram: {args.enable_low_vram_mode}\n"
)
tf.write(f"{'=' * 80}\n\n")
tf.write(
f"\n{'=' * 60}\n"
f" Version: {args.version} | Model: {preset['model_dir']}\n"
f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
f"{'=' * 60}\n"
)
tf.write(
f" Existing timing records: {len(timing_records)} / expected outputs: {len(expected_outputs)}\n"
)
for idx in sorted(timing_records):
elapsed, slug = timing_records[idx]
tf.write(make_timing_line(args.version, idx, elapsed, slug) + "\n")
if all_timings:
avg_t = sum(all_timings) / len(all_timings)
total_t = sum(all_timings)
summary = (
f"\n >> [{args.version}] completed {len(all_timings)} videos | "
f"avg: {avg_t:.2f}s ({avg_t / 60:.2f}min) | "
f"total: {total_t:.1f}s ({total_t / 60:.1f}min)\n"
)
else:
summary = f"\n >> [{args.version}] no timing records available\n"
print(summary)
tf.write(summary)
if peak_mem is not None:
mem_line = f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB\n"
tf.write(mem_line)
sep = f"\n{'=' * 80}\n"
tf.write(sep)
tf.write(" FINAL SUMMARY\n")
tf.write(f"{'=' * 80}\n")
print(sep)
print(" FINAL SUMMARY")
print(f"{'=' * 80}")
fmt = " {ver:12s} | videos: {n:3d} | avg: {avg:8.2f}s ({avgm:5.2f}min) | min: {mn:8.2f}s | max: {mx:8.2f}s | total: {tot:8.1f}s ({totm:5.1f}min)"
if all_timings:
line = fmt.format(
ver=args.version, n=len(all_timings),
avg=sum(all_timings) / len(all_timings), avgm=sum(all_timings) / len(all_timings) / 60,
mn=min(all_timings), mx=max(all_timings),
tot=sum(all_timings), totm=sum(all_timings) / 60,
)
else:
line = f" {args.version:12s} | N/A (no timing records)"
print(line)
tf.write(line + "\n")
tf.write(f"{'=' * 80}\n")
print(f"{'=' * 80}")
print(f"\nTiming report: {timing_file}")
print(f"Videos: {by_prompt_dir}")
print(f" {by_version_dir}")
if __name__ == "__main__":
main()