File size: 6,760 Bytes
39a9ff0
 
b0ab773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9ff0
 
b0ab773
39a9ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0ab773
 
 
 
 
6228d3d
 
b0ab773
 
 
39a9ff0
 
 
 
 
 
 
 
 
b0ab773
 
 
 
39a9ff0
 
 
 
b0ab773
 
39a9ff0
 
b0ab773
 
39a9ff0
b0ab773
 
 
 
 
 
39a9ff0
b0ab773
 
39a9ff0
 
 
 
 
 
b0ab773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9ff0
 
 
 
 
 
 
 
 
 
 
b0ab773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9ff0
 
 
b0ab773
39a9ff0
b0ab773
 
39a9ff0
b0ab773
 
39a9ff0
b0ab773
39a9ff0
 
b0ab773
 
 
 
 
39a9ff0
 
 
 
 
 
 
 
 
 
b0ab773
 
 
39a9ff0
b0ab773
39a9ff0
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""Kaggle notebook body for the WebFM eval run. Not imported by the app.

Pulled and executed by the kernel `kkonda/webfm-ming-tts-eval`, which does
nothing but snapshot_download idefinity/webfm-eval and exec this file. The run
logic lives here so it can change without touching the kernel.

Stages, in order:

  1. install the pinned runtime, then prove `from ming_tts import MingTTS`
     imports — repairing missing modules by name, because guessing the
     transitive dependency set is how the first run died on `loguru`
  2. clone the repo at the pinned commit, download weights, pull the bundle
  3. bake prompt_latent / speaker_emb for the eight WebFM voices
  4. smoke: one voice, two sentences, teacher + 3step. Cheaper to find API
     drift here than 40 minutes into the matrix
  5. the full matrix, one voice shard per visible GPU
  6. score

Everything writes into /kaggle/working; ming_eval.py skips cells that already
have a row, so a killed session keeps its progress.
"""
import os
import re
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path("/kaggle/working")
REPO = ROOT / "Ming-3.0-tts"
MODEL = ROOT / "Ming-3.0-tts-0.5b"
BUNDLE = ROOT / "webfm-eval"
PIN = "e999c39"
WEIGHTS = "inclusionAI/Ming-3.0-tts-0.5B"
BUNDLE_REPO = "idefinity/webfm-eval"
MODELS = "teacher,3step,4step"
HF_MIRROR = "https://hf-mirror.com"

# requirements.txt at PIN, minus torch/torchaudio: Kaggle ships a newer CUDA
# build and downgrading it would cost the session.
DEPS = [
    "transformers==4.46.3", "tokenizers", "accelerate==1.3.0", "huggingface_hub",
    "soundfile==0.12.1", "tqdm", "loguru", "x_transformers==2.9.2",
    "diffusers==0.33.0", "onnxruntime", "onnx", "onnx_ir", "onnxscript",
    "inflect", "einops", "packaging",
]
ALIASES = {"cv2": "opencv-python", "yaml": "pyyaml", "PIL": "pillow", "sklearn": "scikit-learn"}


def sh(cmd: str, check: bool = True, env: dict | None = None) -> int:
    print(f"\n$ {cmd}", flush=True)
    rc = subprocess.run(cmd, shell=True, text=True, env=env).returncode
    if check and rc != 0:
        raise SystemExit(f"command failed ({rc}): {cmd}")
    return rc


def pip(*pkgs: str) -> None:
    sh("pip install -q " + " ".join(f'"{p}"' for p in pkgs), check=False)


def pull(repo_id: str, local_dir: Path, repo_type: str = "model") -> None:
    if local_dir.exists() and any(local_dir.iterdir()):
        print(f"{local_dir} already populated")
        return
    code = ("from huggingface_hub import snapshot_download as s; "
            f"s('{repo_id}', local_dir=r'{local_dir}', repo_type='{repo_type}')")
    if sh(f'python3 -c "{code}"', check=False) != 0:
        print("direct download failed, retrying through hf-mirror")
        sh(f'python3 -c "{code}"', env=dict(os.environ, HF_ENDPOINT=HF_MIRROR))


def stage_repo() -> None:
    """Clone before the import probe, which imports from this directory."""
    if not REPO.exists():
        sh(f"git clone https://github.com/inclusionAI/Ming-3.0-tts.git {REPO}")
    if sh(f"git -C {REPO} checkout {PIN}", check=False) != 0:
        print(f"WARNING: commit {PIN} not found, staying on the default branch")


def stage_deps() -> None:
    sh("nvidia-smi --query-gpu=name,memory.total --format=csv,noheader")
    import torch

    print("torch", torch.__version__, "cuda", torch.cuda.is_available(),
          "devices", torch.cuda.device_count())

    pip(*DEPS)
    probe = ("import sys; sys.path.insert(0, r'%s'); from ming_tts import MingTTS; "
             "print('import ok')" % REPO)
    for attempt in range(6):
        r = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True)
        if r.returncode == 0:
            print("ming_tts imports cleanly")
            return
        m = re.search(r"No module named '([^']+)'", r.stderr)
        if not m:
            print(r.stderr[-3000:])
            raise SystemExit("ming_tts import failed for a reason pip cannot repair")
        missing = m.group(1).split(".")[0]
        pkg = ALIASES.get(missing, missing)
        print(f"[{attempt+1}] missing '{missing}' -> installing '{pkg}'")
        pip(pkg)
    raise SystemExit("could not satisfy ming_tts imports")


def stage_prepare() -> None:
    pull(WEIGHTS, MODEL)
    pull(BUNDLE_REPO, BUNDLE, repo_type="dataset")


def stage_bake() -> None:
    if (ROOT / "baked/voices_baked.npz").exists():
        print("voices already baked, skipping")
        return
    sh(f"cd {ROOT} && EVAL_DATA={BUNDLE} python3 {BUNDLE}/kaggle/bake_voices.py")


def run_eval(tag: str, voices: list[str], models: str, limit: int, gpu: int = 0) -> subprocess.Popen:
    env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu), EVAL_DATA=str(BUNDLE),
               VOICES=",".join(voices), MODELS=models, LIMIT=str(limit))
    log = open(ROOT / f"eval_{tag}.log", "w")
    return subprocess.Popen([sys.executable, str(BUNDLE / "kaggle/ming_eval.py")],
                            env=env, stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))


def stage_smoke() -> None:
    """One voice, two sentences. Catches API drift before the long run."""
    if (ROOT / "smoke.ok").exists():
        return
    p = run_eval("smoke", ["v01"], "teacher,3step", 2)
    p.wait()
    rows = ROOT / "ming_eval/results.jsonl"
    n = sum(1 for _ in rows.open()) if rows.exists() else 0
    if n < 4:
        print((ROOT / "eval_smoke.log").read_text()[-4000:])
        raise SystemExit(f"smoke produced {n} rows, expected at least 4")
    (ROOT / "smoke.ok").write_text("ok")
    print(f"smoke ok ({n} rows)")


def stage_eval() -> None:
    import torch

    n_gpu = max(1, torch.cuda.device_count())
    voices = [f"v{i:02d}" for i in range(1, 9)]
    shards = [voices[i::n_gpu] for i in range(n_gpu)]
    print(f"{n_gpu} GPU(s), shards: {shards}")

    procs = [(gpu, run_eval(f"gpu{gpu}", shard, MODELS, 40, gpu))
             for gpu, shard in enumerate(shards)]
    last = 0.0
    while any(p.poll() is None for _, p in procs):
        time.sleep(60)
        rows = ROOT / "ming_eval/results.jsonl"
        n = sum(1 for _ in rows.open()) if rows.exists() else 0
        if n != last:
            print(f"[{time.strftime('%H:%M')}] rows={n}", flush=True)
            last = n
    for gpu, p in procs:
        print(f"gpu{gpu} exit={p.returncode}")


def stage_score() -> None:
    sh(f"python3 {BUNDLE}/eval/score.py aggregate "
       f"--results {ROOT}/ming_eval/results.jsonl --baseline teacher --by-bucket "
       f"--out {ROOT}/ming_eval/summary.json", check=False)


if __name__ == "__main__":
    stage_repo()
    stage_deps()
    stage_prepare()
    stage_bake()
    stage_smoke()
    stage_eval()
    stage_score()
    print("\nartifacts: baked/, ming_eval/results.jsonl, ming_eval/summary.json, ming_eval/wav/")