zziang commited on
Commit
1a6c3bd
·
verified ·
1 Parent(s): 85c0836

director: few-shot prompt + honest contract (8-40 chars)

Browse files
Files changed (1) hide show
  1. kaggle/director_probe.py +115 -64
kaggle/director_probe.py CHANGED
@@ -1,12 +1,17 @@
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
@@ -14,37 +19,55 @@ 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(
@@ -53,65 +76,93 @@ def parse(raw: str) -> list[dict]:
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, 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
- 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__":
 
1
+ """Director stage: turn a topic into a script the TTS front end can consume.
2
 
3
+ Why the contract and not just "valid JSON": a line that parses can still be
4
+ unusable. Five characters is short enough for the whisper voice to collapse into
5
+ silence, digits and Latin words bypass the normaliser we turned off, and emoji
6
+ break the text encoder. So the checks here are the ones the radio stage needs.
7
 
8
+ Runs on transformers 5.x. Ming pins 4.46.3, so this is a separate process and
9
+ leaves a JSON file behind rather than calling TTS directly.
10
+
11
+ Modes (`MODE`):
12
+ probe - N samples with the prompt as written, report pass rate
13
+ collect - rejection-sample accepted scripts into sft.jsonl
14
+ eval - score the current model on a fixed topic list
15
  """
16
  import json
17
  import os
 
19
  import time
20
  from pathlib import Path
21
 
 
 
22
  ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
23
  MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
24
+ ADAPTER = os.environ.get("ADAPTER", "")
25
+ MODE = os.environ.get("MODE", "probe")
26
  N_SAMPLES = int(os.environ.get("N_SAMPLES", "6"))
27
+ OUT = ROOT / "director"
28
 
29
+ N_LINES = 6
30
+ STYLES = ["开场", "叙述", "故事", "叙述", "耳语", "耳语"]
31
+ MIN_CHARS, MAX_CHARS = 8, 40
32
+ ALLOWED = re.compile(r"^[\u4e00-\u9fff,。?!、;:…——“”‘’「」《》]+$")
 
33
 
34
+ TOPICS = [
35
+ "雨夜的末班公交", "一家很老的唱片店", "海边的灯塔", "凌晨的便利店",
36
+ "搬家时翻出的旧照片", "楼下那棵一直没有开花的树", "深夜的收音机",
37
+ "一场没有下完的雨",
38
+ ]
39
 
40
+ SYSTEM = "你是深夜电台的编剧,只输出 JSON 数组,不解释,不用代码块。"
 
 
 
 
41
 
42
+ RULES = """写一段约 60 秒的深夜电台串词。
43
+
44
+ 规则:
45
+ 1. 正好 6 组,style 依次是:开场、叙述、故事、叙述、耳语、耳语。
46
+ 2. 每组是一个独立的大括号对象,形如 {"style":"叙述","text":"..."},六组之间用逗号隔开。
47
+ 3. text 每句 8 到 40 个汉字,只能有汉字和,。?!这几种标点。
48
+ 4. 不要数字、英文、emoji、引号、括号;不要提前结束,一定写满 6 组。"""
49
+
50
+ SHOT = """例子:
51
+ [{"style":"开场","text":"晚上好,这里是深夜频道,我是今晚陪你的人。"},{"style":"叙述","text":"窗外的雨下了一整晚,路灯把水汽照成一片模糊的黄。"},{"style":"故事","text":"很多年前这条街上有一家很小的唱片店,老板总在打烊前放同一首歌。"},{"style":"叙述","text":"如果你还醒着,就把灯关小一点,让声音替你把今天收好。"},{"style":"耳语","text":"后来店关了,歌还在。"},{"style":"耳语","text":"晚安,我们明天见。"}]"""
52
 
53
 
54
  def log(msg: str) -> None:
55
  print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
56
 
57
 
58
+ def build_prompt(topic: str, few_shot: bool = True) -> str:
59
+ head = RULES if few_shot else "写一段约 60 秒的深夜电台串词,正好 6 组 style 依次是开场、叙述、故事、叙述、耳语、耳语。"
60
+ body = f"{head}\n\n{SHOT}\n\n现在写「{topic}」。" if few_shot else f"{head}\n\n题目:{topic}。只输出 JSON 数组。"
61
+ return body
62
+
63
+
64
  def parse(raw: str) -> list[dict]:
65
+ """Pair-scan instead of json.loads.
66
+
67
+ The 0.8B model reliably writes the fields and unreliably the braces: one
68
+ observed answer opened a single object and repeated "style"/"text" six
69
+ times. Scanning for the pairs survives that; json.loads cannot.
70
+ """
71
  pairs = re.findall(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', raw)
72
  if not pairs:
73
  pairs = [(s, t) for t, s in re.findall(
 
76
 
77
 
78
  def check(lines: list[dict]) -> dict:
 
79
  bad = []
80
+ if len(lines) != N_LINES:
81
  bad.append(f"count={len(lines)}")
 
 
82
  for i, l in enumerate(lines):
83
  t = l.get("text", "")
84
+ if i < N_LINES and l.get("style") != STYLES[i]:
85
  bad.append(f"L{i}:style={l.get('style')!r}")
86
  if not (MIN_CHARS <= len(t) <= MAX_CHARS):
87
  bad.append(f"L{i}:len={len(t)}")
88
  if not ALLOWED.match(t):
89
  bad.append(f"L{i}:chars")
 
 
 
90
  return {"ok": not bad, "violations": bad}
91
 
92
 
93
+ def load_model():
94
+ import torch
95
  from transformers import AutoModelForCausalLM, AutoTokenizer
96
 
 
 
97
  tok = AutoTokenizer.from_pretrained(MODEL_ID)
98
+ model = AutoModelForCausalLM.from_pretrained(
99
+ MODEL_ID, dtype=torch.float16, device_map="cuda:0").eval()
100
+ if ADAPTER and Path(ADAPTER).exists():
101
+ from peft import PeftModel
102
+ model = PeftModel.from_pretrained(model, ADAPTER).eval()
103
+ log(f"adapter {ADAPTER}")
104
+ log(f"loaded {MODEL_ID} -> {sum(p.numel() for p in model.parameters())/1e6:.0f}M params")
105
+ return tok, model
106
+
107
 
108
+ def sample(tok, model, topic: str, few_shot: bool = True) -> dict:
109
+ import torch
110
+
111
+ msgs = [{"role": "system", "content": SYSTEM},
112
+ {"role": "user", "content": build_prompt(topic, few_shot)}]
113
  text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
114
  ids = tok([text], return_tensors="pt").to("cuda")
115
+ t0 = time.time()
116
+ with torch.no_grad():
117
+ gen = model.generate(**ids, max_new_tokens=512, do_sample=True,
118
+ temperature=0.8, top_p=0.9, top_k=20,
119
+ repetition_penalty=1.05,
120
+ pad_token_id=tok.eos_token_id)
121
+ raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
122
+ lines = parse(raw)
123
+ return {"topic": topic, "seconds": round(time.time() - t0, 1),
124
+ "n_tokens": int(gen.shape[1] - ids["input_ids"].shape[1]),
125
+ "lines": lines, "raw": raw, **check(lines)}
126
+
127
 
128
+ def main() -> None:
129
+ OUT.mkdir(parents=True, exist_ok=True)
130
+ tok, model = load_model()
131
+
132
+ if MODE == "probe":
133
+ rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)]
134
+ for r in rows:
135
+ log(f"{r['topic'][:8]:<10} {r['seconds']:>4}s n={len(r['lines'])} ok={r['ok']} {r['violations'][:3]}")
136
+ for l in r["lines"]:
137
+ log(f" [{l.get('style')}] {len(l.get('text',''))}字 {l.get('text')}")
138
+ ok = sum(r["ok"] for r in rows)
139
+ log(f"pass {ok}/{len(rows)}")
140
+ (OUT / "probe.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
141
+
142
+ elif MODE == "collect":
143
+ target = int(os.environ.get("TARGET", "120"))
144
+ got = []
145
+ tries = 0
146
+ ticks = 0
147
+ while len(got) < target and ticks < 40:
148
+ topic = TOPICS[ticks % len(TOPICS)]
149
+ r = sample(tok, model, topic)
150
+ tries += 1
151
+ ticks += 1
152
+ if r["ok"]:
153
+ got.append({"topic": topic, "lines": r["lines"]})
154
+ if tries % 10 == 0:
155
+ log(f"{tries} tried, {len(got)} kept ({len(got)/tries:.0%})")
156
+ with open(OUT / "sft.jsonl", "w") as f:
157
+ for g in got:
158
+ f.write(json.dumps(g, ensure_ascii=False) + "\n")
159
+ log(f"kept {len(got)} of {tries}")
160
+
161
+ elif MODE == "eval":
162
+ rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)]
163
+ ok = sum(r["ok"] for r in rows)
164
+ log(f"pass {ok}/{len(rows)}")
165
+ (OUT / "eval.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
166
 
167
 
168
  if __name__ == "__main__":