File size: 7,039 Bytes
d0486d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# LongLive: validates outputs, checks prompts/tokens, writes per-episode metadata, timing table, run_manifest,
# and builds the release dir (~/longlive_run/release) in the same layout as ERCBench-ShotStream-400.
import csv, datetime as dt, hashlib, json, os, re, shutil, subprocess, sys
W = os.path.expanduser("~/longlive_run")
idx = json.load(open(os.path.expanduser("~/shotstream_run/inputs/prompts_index.json")))
DXB = dt.timezone(dt.timedelta(hours=4))
LAT = 21  # latent frames per shot (one prompt per 21 latents)

def pixel_start(lat):  # Wan VAE: latent 0 -> frame 0, latent i>=1 -> frames 4i-3..4i
    return 0 if lat == 0 else 4 * lat - 3

# ---- timing + config seeds from the run logs: run.log (single-GPU run on GPU 1) and, only if the owner's
# "eval finished early -> all GPUs on LongLive" switch fired, logs/run_gpu<g>.log (claim-based workers).
# Start/saved lines are paired within one log file; a later log wins for an episode that was redone.
import glob
logs = [(f"{W}/logs/run.log", 1)] + [(f, int(re.search(r"run_gpu(\d)", f).group(1)))
                                     for f in sorted(glob.glob(f"{W}/logs/run_gpu*.log"))]
timing, cfg_of, seeds, gpu_of = {}, {}, {}, {}
for path, gpu in logs:
    st, cur = {}, None
    for line in open(path, errors="replace"):
        m = re.search(r"\[CONFIG\] (\d)shot start", line)
        if m: cur = int(m.group(1))
        m = re.search(r"(\d{4}-\d\d-\d\dT[\d:.]+Z) \[EPISODE\] (start|saved) (\S+)", line)
        if not m: continue
        ts = dt.datetime.strptime(m.group(1), "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=dt.timezone.utc)
        eid = m.group(3)
        if m.group(2) == "start":
            st[eid] = ts; cfg_of[eid] = cur
            s = re.search(r"seed=(\d+)", line); seeds[eid] = int(s.group(1))
        elif eid in st:
            mem = re.search(r"peak_mem_gb=([\d.]+)", line)
            timing[eid] = {"seconds": round((ts - st[eid]).total_seconds(), 2), "start": st[eid], "end": ts,
                           "peak_mem_gb": float(mem.group(1)) if mem else None, "gpu": gpu,
                           "log": os.path.basename(path)}

# ---- prompt / token check. The tokenizer logs (tokens.jsonl + tokens_gpu<g>.jsonl) hold one record per prompt the
# model's tokenizer received. Records are matched to shots by exact prompt text (several workers interleave, and a
# run killed mid-episode leaves extra records), then sha256 and the untruncated token count are checked.
tok = []
for f in [f"{W}/logs/tokens.jsonl"] + sorted(glob.glob(f"{W}/logs/tokens_gpu*.jsonl")):
    tok += [json.loads(l) for l in open(f, encoding="utf-8") if l.strip()]
by_raw = {}
for r in tok: by_raw.setdefault(r["raw"], r)
tok_of, tok_problems, used = {}, [], set()
for eid, info in idx.items():
    recs = [by_raw.get(s["prompt"]) for s in info["shots"]]
    if None in recs: continue  # reported as "no token record" below
    for k, (r, s) in enumerate(zip(recs, info["shots"])):
        if hashlib.sha256(r["raw"].encode()).hexdigest() != s["sha256"]:
            tok_problems.append((eid, k + 1, "sha mismatch"))
        if r["n_tokens"] > r["seq_len"]:
            tok_problems.append((eid, k + 1, f"{r['n_tokens']} tokens > {r['seq_len']}"))
        used.add(r["raw"])
    tok_of[eid] = [r["n_tokens"] for r in recs]
extra_tok = sum(1 for r in tok if r["raw"] not in used)

def probe(p):
    out = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries",
        "stream=width,height,r_frame_rate,nb_read_frames", "-of", "json", p], capture_output=True, text=True)
    s = json.loads(out.stdout)["streams"][0]
    dec = subprocess.run(["ffmpeg", "-v", "error", "-xerror", "-i", p, "-f", "null", "-"], capture_output=True, text=True)
    return s, dec.returncode == 0 and not dec.stderr.strip()

rel = f"{W}/release"; problems = []; rows = []
for eid, info in sorted(idx.items(), key=lambda x: x[1]["priority"]):
    n = info["shot_count"]; src = f"{W}/outputs/{eid}.mp4"; nf = pixel_start(LAT * n)  # = 84n - 3
    if not os.path.exists(src): problems.append((eid, "missing")); continue
    s, ok = probe(src)
    if not (s["width"] == 832 and s["height"] == 480 and s["r_frame_rate"] == "16/1" and int(s["nb_read_frames"]) == nf and ok):
        problems.append((eid, s, ok)); continue
    if eid not in timing: problems.append((eid, "no timing")); continue
    if eid not in tok_of: problems.append((eid, "no token record")); continue
    starts = [pixel_start(LAT * k) for k in range(n)] + [nf]
    d = f"{rel}/episodes/{eid}"; os.makedirs(d, exist_ok=True)
    shutil.copy2(src, f"{d}/episode.mp4")
    vsha = hashlib.sha256(open(src, "rb").read()).hexdigest()
    t = timing[eid]
    md = {"episode_id": eid, "priority": info["priority"], "shot_count": n,
          "shot_frame_ranges": [[starts[k], starts[k + 1]] for k in range(n)],
          "cut_frames": starts[1:-1],
          "cut_type": "prompt_switch (LongLive interactive prompt switch every 21 latent frames; not a hard cut)",
          "prompt_switch_latent_frames": [LAT * k for k in range(1, n)],
          "latent_frames": LAT * n, "fps": 16, "resolution": {"width": 832, "height": 480},
          "num_frames": nf, "seed": seeds[eid], "seed_scope": f"set once per process; one process per shot-count config ({n}-shot); every process draws the noise of all episodes in order, so the noise per episode does not depend on which process/GPU generated it",
          "global_caption": None,
          "shots": [{"shot": p["shot"], "prompt": p["prompt"], "prompt_sha256": p["sha256"], "umt5_tokens": tok_of[eid][i]}
                    for i, p in enumerate(info["shots"])],
          "video_sha256": vsha, "generation_seconds": t["seconds"], "peak_mem_gb": t["peak_mem_gb"], "gpu_index": t["gpu"],
          "generated_at_dubai": t["end"].astimezone(DXB).isoformat(), "source_log": t["log"]}
    json.dump(md, open(f"{d}/metadata.json", "w"), ensure_ascii=False, indent=2)
    rows.append([eid, info["priority"], n, t["gpu"], t["seconds"], round(t["seconds"] / n, 2),
                 t["start"].astimezone(DXB).isoformat(), t["end"].astimezone(DXB).isoformat(), vsha])

print("ok episodes:", len(rows), "problems:", len(problems), "| token problems:", len(tok_problems),
      "| extra tokenizer records:", extra_tok)
for p in problems[:20]: print("PROBLEM", p)
for p in tok_problems[:20]: print("TOKEN PROBLEM", p)
allt = [x for v in tok_of.values() for x in v]
if allt: print("tokens per shot: max", max(allt), "min", min(allt))
os.makedirs(f"{rel}/runs", exist_ok=True)
with open(f"{rel}/runs/timing.csv", "w", newline="") as f:
    w = csv.writer(f); w.writerow(["episode_id", "priority", "shot_count", "gpu", "seconds", "seconds_per_shot", "start_dubai", "end_dubai", "video_sha256"])
    w.writerows(rows)
if rows:
    tot_s = sum(r[4] for r in rows); tot_shots = sum(r[2] for r in rows)
    print("sum gen seconds", round(tot_s, 1), "shots", tot_shots, "avg s/shot", round(tot_s / tot_shots, 3))
sys.exit(1 if problems or tok_problems else 0)