File size: 6,281 Bytes
e5818d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
#!/usr/bin/env python3
"""Generate WSB candidates with pinned Hugging Face releases; never reuse audio."""
import argparse
import hashlib
import importlib.metadata
import json
import platform
from pathlib import Path

MODEL = "m-a-p/YuE2-3B"
MODEL_REVISION = "1a96eca688d6ae5d7f0feb88573fec89920fcd19"
VAE = "m-a-p/YuE2-Vae-legacy"
VAE_REVISION = "b54118f0fc462f08999d1ec07e88817f4ee3f770"
MODEL_SHA = "1d55c42c1a9875c34f5d736e15078449992b044e807ce2a138e6cf289a1e59e9"
VAE_SHA = "b6d283628913bb41145ba99e2314eef613905ee95f690eb70e8212d5f4965044"


def sha(path):
    h = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(8 << 20), b""):
            h.update(block)
    return h.hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, default=Path(__file__).resolve().parents[1] / "benchmark/reproduction_manifest.jsonl")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--candidates", type=int, choices=(2, 8), default=8)
    parser.add_argument("--backend", choices=("torch", "torch-eager", "vllm"), default="torch")
    parser.add_argument("--shard-index", type=int, default=0)
    parser.add_argument("--num-shards", type=int, default=1)
    parser.add_argument("--prompt-index", type=int, action="append", help="Optional diagnostic subset; repeat for multiple row indices")
    parser.add_argument("--cache-dir", type=Path)
    args = parser.parse_args()
    if not 0 <= args.shard_index < args.num_shards:
        parser.error("Require 0 <= shard-index < num-shards")
    if args.prompt_index is not None and (len(set(args.prompt_index)) != len(args.prompt_index)
            or any(not 0 <= i < 192 for i in args.prompt_index)):
        parser.error("Prompt indices must be distinct integers from 0 to 191")
    if args.output.exists() and any(args.output.iterdir()):
        parser.error("Use a new output directory so previous candidates cannot be reused or overwritten")
    all_rows = [json.loads(line) for line in args.manifest.read_text(encoding="utf-8").splitlines() if line.strip()]
    assert len(all_rows) == 192 and [r["prompt_index"] for r in all_rows] == list(range(192))
    bases = [831001, 831019, 831037, 831061, 831083, 831109, 831127, 831149]
    for row in all_rows:
        assert row["candidate_ar_seeds"] == [s + row["prompt_index"] for s in bases]
        assert row["candidate_ar_seeds"] == row["candidate_nar_seeds"]
    rows = [r for r in all_rows if r["prompt_index"] % args.num_shards == args.shard_index]
    if args.prompt_index is not None:
        rows = [r for r in rows if r["prompt_index"] in args.prompt_index]
    assert rows
    import torch
    from yue2 import YuE2Pipeline
    from yue2.protocol import SongRequest
    from yue2.storage import verify_result
    assert importlib.metadata.version("yue2-infer") == "0.1.3"
    args.output.mkdir(parents=True, exist_ok=True)
    evaluation_inputs = []
    for row in rows:
        for candidate_index, seed in enumerate(row["candidate_ar_seeds"][:args.candidates]):
            ident = f"wsb_{row['prompt_index']:03d}_r{candidate_index}_s{seed}"
            evaluation_inputs.append({"prompt_index": row["prompt_index"],
                                      "candidate_index": candidate_index, "seed": seed,
                                      "path": f"songs/{ident}"})
    (args.output / "evaluation_inputs.jsonl").write_text(
        "".join(json.dumps(row) + "\n" for row in evaluation_inputs))
    report = {"model": MODEL, "model_revision": MODEL_REVISION, "vae": VAE,
              "vae_revision": VAE_REVISION, "backend": args.backend,
              "manifest_sha256": sha(args.manifest), "python": platform.python_version(),
              "torch": torch.__version__, "gpu": torch.cuda.get_device_name(0),
              "shard_index": args.shard_index, "num_shards": args.num_shards,
              "prompt_indices": [r["prompt_index"] for r in rows],
              "expected_candidates": len(rows) * args.candidates, "results": [], "complete": False}
    with YuE2Pipeline.from_pretrained(MODEL, revision=MODEL_REVISION, vae=VAE,
            vae_revision=VAE_REVISION, cache_dir=args.cache_dir,
            backend=args.backend, device="cuda:0", memory_budget_gib=24) as pipe:
        assert sha(pipe.model_dir / "model.safetensors") == MODEL_SHA
        assert sha(pipe.vae_dir / "model.safetensors") == VAE_SHA
        report["generation_config"] = pipe.generation_config.to_dict()
        for row in rows:
            for candidate_index, seed in enumerate(row["candidate_ar_seeds"][:args.candidates]):
                ident = f"wsb_{row['prompt_index']:03d}_r{candidate_index}_s{seed}"
                request = dict(id=ident, style=row["style"], lyrics=row["lyrics"],
                               cot="full", cfg_scale=1.0, seed=seed)
                assert SongRequest(**request).text() == row["generation_prompt"]
                result = {"id": ident, "prompt_index": row["prompt_index"],
                          "candidate_index": candidate_index, "seed": seed}
                try:
                    song = pipe(**request)
                    song.save_artifacts(args.output / "songs" / ident)
                    receipt = verify_result(args.output / "songs" / ident)
                    result.update(status="complete", identity=receipt["identity"],
                                  truncated=receipt["truncated"], audio_seconds=receipt["audio_seconds"])
                    del song
                except Exception as exc:
                    result.update(status="failed", error=f"{type(exc).__name__}: {exc}")
                report["results"].append(result)
                (args.output / "generation_report.json").write_text(json.dumps(report, indent=2) + "\n")
                print(json.dumps(result), flush=True)
    report["complete"] = (len(report["results"]) == report["expected_candidates"]
                          and all(r["status"] == "complete" for r in report["results"]))
    (args.output / "generation_report.json").write_text(json.dumps(report, indent=2) + "\n")
    return 0 if report["complete"] else 1


if __name__ == "__main__":
    raise SystemExit(main())