yang29's picture
Record CF training and evaluation implementation
f947839 verified
Raw History Blame Contribute Delete
5.8 kB
"""Contracts shared by automatic checkpoint export and VBench scoring."""
import hashlib
import json
from pathlib import Path
import re
import subprocess
REPO = Path(__file__).resolve().parents[2]
RUNTIME = Path("/hpctmp/e0833524/afd_vbench_b200")
VBENCH = Path("/nfs/home/svu/e0833524/VBench")
DIMENSIONS = ["subject_consistency", "background_consistency", "aesthetic_quality", "imaging_quality",
"object_class", "multiple_objects", "color", "spatial_relationship", "scene", "temporal_style",
"overall_consistency", "human_action", "temporal_flickering", "motion_smoothness",
"dynamic_degree", "appearance_style"]
def sha256(path):
digest = hashlib.sha256()
with Path(path).open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024**2), b""):
digest.update(chunk)
return digest.hexdigest()
def write_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
temporary.replace(path)
def git_state(directory):
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=directory, text=True).strip()
diff = subprocess.check_output(["git", "diff", "HEAD", "--"], cwd=directory)
return {"commit": commit, "diff_sha256": hashlib.sha256(diff).hexdigest()}
def implementation_hashes():
return {name: sha256(Path(__file__).parent / name)
for name in ("eval_common.py", "generate.py", "evaluate.py", "plan.py", "encode.py")}
def records(plan):
metadata = json.loads(Path(plan["metadata"]).read_text())
prompts = list(dict.fromkeys(row["prompt_en"] for row in metadata))
result = []
for index, prompt in enumerate(prompts):
for replica, seed in enumerate(plan["seeds"]):
filename = f"{prompt}-{replica}.mp4"
# Human-action scoring parses the action label from this filename.
if Path(filename).name != filename or len(filename.encode()) > 255 or "\0" in filename:
raise ValueError(f"Unsupported VBench filename: {filename!r}")
result.append({"prompt_index": index, "prompt": prompt, "replica": replica, "seed": seed,
"video": str(Path(plan["output_dir"]) / "videos" / filename)})
return result
def load_plan(path):
plan = json.loads(Path(path).read_text())
if sha256(plan["metadata"]) != plan["metadata_sha256"]:
raise ValueError("Evaluation metadata changed after preparation")
if not plan["smoke"]:
if git_state(plan["vbench_root"]) != plan["vbench_source"]:
raise ValueError("VBench source changed after preparation")
if implementation_hashes() != plan["implementation_sha256"]:
raise ValueError("Evaluation implementation changed after preparation")
if len(records(plan)) != plan["expected_videos"]:
raise ValueError("Prepared video count does not match metadata and seeds")
return plan
def selected_plan(path):
plan = load_plan(path)
if not plan["smoke"]:
selected = json.loads((Path(plan["output_dir"]) / "selected_checkpoint.json").read_text())
if selected["plan_sha256"] != sha256(path) or selected["method"] != plan["method"]:
raise ValueError("Selected checkpoint belongs to a different evaluation plan")
plan["checkpoint_step"] = selected["step"]
plan["selected_checkpoint"] = selected["checkpoint"]
plan["selected_checkpoint_sha256"] = selected["sha256"]
return plan
def checkpoint_candidates(plan):
root = Path(plan["checkpoint_run_dir"])
paths = root.glob("checkpoints_*/checkpoints/checkpoint-*/lora/adapter_model.bin") if plan["method"] == "astrolabe" else root.glob("checkpoints/step-*.pt")
candidates = []
for path in paths:
match = re.fullmatch(r"checkpoint-(\d+)", path.parent.parent.name) if plan["method"] == "astrolabe" else re.fullmatch(r"step-(\d+)\.pt", path.name)
if match and int(match.group(1)) > 0 and path.is_file() and path.stat().st_size > 0:
candidates.append((int(match.group(1)), path))
return sorted(candidates, key=lambda item: (item[0], item[1].stat().st_mtime_ns), reverse=True)
def checkpoint_path(plan):
root = Path(plan["checkpoint_run_dir"])
step = plan["checkpoint_step"]
if plan["method"] == "astrolabe":
paths = list(root.glob(f"checkpoints_*/checkpoints/checkpoint-{step}/lora/adapter_model.bin"))
if len(paths) != 1:
raise FileNotFoundError(f"Expected one complete Astrolabe checkpoint at step {step}, found {paths}")
path = paths[0]
if not path.with_name("adapter_config.json").is_file() or not (path.parent.parent / "optimizer.pt").is_file():
raise FileNotFoundError("Incomplete Astrolabe checkpoint")
else:
path = root / f"checkpoints/step-{step}.pt"
if not path.is_file() or path.stat().st_size == 0:
raise FileNotFoundError(f"Final trained checkpoint is not ready: {path}")
return path
def dimension_entries(plan, dimension):
by_prompt = {}
for item in records(plan):
path = Path(item["video"])
if not path.is_file() or path.stat().st_size == 0:
raise FileNotFoundError(f"Incomplete VBench generation: {path}")
by_prompt.setdefault(item["prompt"], []).append(str(path))
metadata = json.loads(Path(plan["metadata"]).read_text())
entries = []
for row in metadata:
if dimension in row["dimension"]:
entries.append({**row, "video_list": by_prompt[row["prompt_en"]]})
if not entries:
raise ValueError(f"No metadata for {dimension}")
return entries