zziang commited on
Commit
94c5d1d
·
verified ·
1 Parent(s): acf1687

director: Qwen3.5-0.8B probe against the TTS contract

Browse files
Files changed (1) hide show
  1. kaggle/director_probe.py +118 -0
kaggle/director_probe.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probe: can Qwen3.5-0.8B write a script that the TTS front end can consume?
2
+
3
+ The failure in v2/v3 was not the schema alone. A line that is *valid JSON* can
4
+ still be unusable for Ming: five characters is long enough for the whisper voice
5
+ to collapse, digits and Latin words bypass the normaliser we turned off, and
6
+ emoji break the text encoder. So this measures the contract, not just the syntax.
7
+
8
+ Runs on transformers 5.x, which cannot share a process with Ming (pinned at
9
+ 4.46.3). That is why the director is a separate stage with its own JSON file.
10
+ """
11
+ import json
12
+ import os
13
+ import re
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import torch
18
+
19
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
20
+ MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
21
+ OUT = ROOT / "director"
22
+ N_SAMPLES = int(os.environ.get("N_SAMPLES", "6"))
23
+
24
+ STYLES = {"开场", "叙述", "故事", "耳语"}
25
+ MIN_CHARS, MAX_CHARS = 8, 30
26
+ # Anything outside this set has to be handled by a normaliser we deliberately
27
+ # turned off, so the director is not allowed to emit it.
28
+ ALLOWED = re.compile(r"^[\u4e00-\u9fff,。?!、;:…—]+$")
29
+
30
+ PROMPT = """你是一档深夜电台的编剧。写一段约 60 秒的节目串词,一共 6 句。
31
+
32
+ 硬性规则:
33
+ 1. 正好 6 句,顺序是:开场、叙述、故事、叙述、耳语、耳语。
34
+ 2. 每句 8 到 30 个汉字。
35
+ 3. 只能用汉字和中文标点(,。?!),不要数字、英文、emoji、括号、引号。
36
+ 4. 内容要连贯:讲一件小事,最后两句压低声音收尾。
37
+
38
+ 只输出一个 JSON 数组,不要解释,不要代码块。格式:
39
+ [{"style":"开场","text":"..."},{"style":"叙述","text":"..."},{"style":"故事","text":"..."},{"style":"叙述","text":"..."},{"style":"耳语","text":"..."},{"style":"耳语","text":"..."}]"""
40
+
41
+
42
+ def log(msg: str) -> None:
43
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
44
+
45
+
46
+ def parse(raw: str) -> list[dict]:
47
+ """Same tolerant extraction the runtime uses: pair-scan, not json.loads."""
48
+ pairs = re.findall(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', raw)
49
+ if not pairs:
50
+ pairs = [(s, t) for t, s in re.findall(
51
+ r'"text"\s*:\s*"([^"]*)"\s*,\s*"style"\s*:\s*"([^"]*)"', raw)]
52
+ return [{"style": s, "text": t} for s, t in pairs if t.strip()]
53
+
54
+
55
+ def check(lines: list[dict]) -> dict:
56
+ """Every reason the TTS front end would have to reject this script."""
57
+ bad = []
58
+ if len(lines) != 6:
59
+ bad.append(f"count={len(lines)}")
60
+ if lines and lines[0].get("style") != "开场":
61
+ bad.append("first!=开场")
62
+ for i, l in enumerate(lines):
63
+ t = l.get("text", "")
64
+ if l.get("style") not in STYLES:
65
+ bad.append(f"L{i}:style={l.get('style')!r}")
66
+ if not (MIN_CHARS <= len(t) <= MAX_CHARS):
67
+ bad.append(f"L{i}:len={len(t)}")
68
+ if not ALLOWED.match(t):
69
+ bad.append(f"L{i}:chars")
70
+ whisper_at = [i for i, l in enumerate(lines) if l.get("style") == "耳语"]
71
+ if whisper_at and whisper_at[-1] < len(lines) - 2:
72
+ bad.append("whisper not at the end")
73
+ return {"ok": not bad, "violations": bad}
74
+
75
+
76
+ def main() -> None:
77
+ from transformers import AutoModelForCausalLM, AutoTokenizer
78
+
79
+ OUT.mkdir(parents=True, exist_ok=True)
80
+ log(f"loading {MODEL_ID}")
81
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
82
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=torch.float16).cuda().eval()
83
+ log(f"loaded, {sum(p.numel() for p in model.parameters())/1e6:.0f}M params")
84
+
85
+ msgs = [{"role": "user", "content": PROMPT}]
86
+ text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
87
+ ids = tok([text], return_tensors="pt").to("cuda")
88
+
89
+ results = []
90
+ for k in range(N_SAMPLES):
91
+ t0 = time.time()
92
+ with torch.no_grad():
93
+ gen = model.generate(**ids, max_new_tokens=512, do_sample=True,
94
+ temperature=0.8, top_p=0.9, top_k=20,
95
+ presence_penalty=1.0, repetition_penalty=1.05,
96
+ pad_token_id=tok.eos_token_id)
97
+ raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
98
+ dt = time.time() - t0
99
+ lines = parse(raw)
100
+ v = check(lines)
101
+ results.append({"sample": k, "seconds": round(dt, 1),
102
+ "n_tokens": int(gen.shape[1] - ids["input_ids"].shape[1]),
103
+ "lines": lines, "raw": raw, **v})
104
+ log(f"#{k} {dt:.0f}s parsed={len(lines)} ok={v['ok']} {v['violations'][:4]}")
105
+ for l in lines:
106
+ log(f" [{l.get('style')}] {len(l.get('text',''))}字 {l.get('text')}")
107
+
108
+ ok = sum(1 for r in results if r["ok"])
109
+ log(f"pass {ok}/{len(results)}")
110
+ lens = [len(l["text"]) for r in results for l in r["lines"]]
111
+ if lens:
112
+ lens.sort()
113
+ log(f"line length: min {lens[0]} median {lens[len(lens)//2]} max {lens[-1]}")
114
+ (OUT / "probe.json").write_text(json.dumps(results, ensure_ascii=False, indent=1))
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()