File size: 4,593 Bytes
ff5b803
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Print the model's internal structure so the ONNX export can be written
against real APIs instead of guesses.

The original export notebook is gone, and the graphs it produced died with it.
Everything downstream (browser bundle, quantization) hangs off being able to
re-export, so this dumps the exact callable signatures, module classes and
parameter shapes needed to write that exporter once and correctly.

Writes /kaggle/working/structure.json and prints a readable summary.
"""
import inspect
import json
import sys
from pathlib import Path

ROOT = Path("/kaggle/working")
REPO = ROOT / "Ming-3.0-tts"
MODEL = ROOT / "Ming-3.0-tts-0.5b"
OUT = ROOT / "structure.json"


def describe(name: str, fn) -> dict:
    try:
        sig = str(inspect.signature(fn))
    except Exception:
        sig = "<no signature>"
    return {"name": name, "type": type(fn).__name__, "signature": sig,
            "doc": (inspect.getdoc(fn) or "")[:400]}


def main() -> None:
    import torch

    sys.path.insert(0, str(REPO))
    for name in ("ming_tts.py", "modeling_bailingmm.py"):
        p = REPO / name
        s = p.read_text()
        s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
        s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
        s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
        p.write_text(s)

    from ming_tts import MingTTS
    import tts_tasks

    tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
    mm = tts.model

    info = {"mm_class": type(mm).__name__, "attrs": [a for a in dir(mm) if not a.startswith("_")][:80]}

    lm = getattr(mm, "model", None)
    info["lm_class"] = type(lm).__name__ if lm is not None else None
    if lm is not None:
        cfg = getattr(lm, "config", None)
        info["lm_config"] = {k: v for k, v in vars(cfg).items()
                             if isinstance(v, (int, float, str, bool, list))} if cfg else None
        info["lm_forward"] = describe("lm.forward", lm.forward)

    for attr in ("linear_proj_audio", "prepare_input_embed", "prepare_prompt", "synthesize"):
        if hasattr(mm, attr):
            info[attr] = describe(attr, getattr(mm, attr))
        if hasattr(tts, attr):
            info[f"tts.{attr}"] = describe(attr, getattr(tts, attr))

    audio = getattr(mm, "audio", None)
    info["audio_class"] = type(audio).__name__ if audio is not None else None
    for m in ("encode", "decode", "quantize", "dequantize"):
        if audio is not None and hasattr(audio, m):
            info[f"audio.{m}"] = describe(m, getattr(audio, m))
    if audio is not None:
        cfg = getattr(audio, "config", None)
        info["audio_config"] = {k: v for k, v in vars(cfg).items()
                                if isinstance(v, (int, float, str, bool))} if cfg else None

    flow = getattr(mm, "flowloss", None)
    info["flow_class"] = type(flow).__name__ if flow is not None else None
    if flow is not None:
        info["flow_attrs"] = [a for a in dir(flow) if not a.startswith("_")]
        dit = getattr(getattr(flow, "cfm", None), "model", None)
        if dit is not None:
            info["dit_forward"] = describe("dit.forward", dit.forward)

    totals = {}
    for name, mod in (("lm", lm), ("audio", audio), ("flow", flow)):
        if mod is not None and hasattr(mod, "parameters"):
            totals[name] = sum(p.numel() for p in mod.parameters())
    if hasattr(mm, "linear_proj_audio") and hasattr(mm.linear_proj_audio, "parameters"):
        totals["linear_proj_audio"] = sum(p.numel() for p in mm.linear_proj_audio.parameters())
    info["param_counts"] = totals

    heads = {}
    for h in ("stop_head", "spk_head", "fc1"):
        for owner, label in ((mm, f"mm.{h}"), (audio, f"audio.{h}")):
            if owner is not None and hasattr(owner, h):
                mod = getattr(owner, h)
                n = sum(p.numel() for p in mod.parameters()) if hasattr(mod, "parameters") else None
                heads[label] = n
    info["heads"] = heads

    OUT.write_text(json.dumps(info, ensure_ascii=False, indent=1))
    print(json.dumps({k: v for k, v in info.items() if k in
                      ("mm_class", "lm_class", "audio_class", "flow_class",
                       "param_counts", "heads", "lm_config", "audio_config")},
                     ensure_ascii=False, indent=1)[:4000])
    print("\nsignatures:")
    for k, v in info.items():
        if isinstance(v, dict) and "signature" in v:
            print(f"  {k}{v['signature']}")


if __name__ == "__main__":
    main()