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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end radio segment: a small LLM writes the script, Ming speaks it.
|
| 2 |
+
|
| 3 |
+
This is the product loop in miniature. A 0.5B instruct model plans a late-night
|
| 4 |
+
segment (narration easing into a whisper), the segment is cast onto the mined
|
| 5 |
+
voices, and the whole thing is rendered twice - once by the 10-step CFG teacher
|
| 6 |
+
and once by the 4-step student - so the shipped model can be judged on a real
|
| 7 |
+
programme rather than on isolated sentences.
|
| 8 |
+
|
| 9 |
+
Two passes on purpose: the teacher and the student cannot both sit on a 15 GB
|
| 10 |
+
card alongside the 1.48 B backbone.
|
| 11 |
+
|
| 12 |
+
Outputs under /kaggle/working/radio:
|
| 13 |
+
script.json the LLM's plan, plus the fallback if parsing failed
|
| 14 |
+
radio_teacher.wav the segment, teacher
|
| 15 |
+
radio_student.wav the segment, student
|
| 16 |
+
lines/*.wav each line separately
|
| 17 |
+
report.json per-line CER, duration, wall time
|
| 18 |
+
"""
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
import traceback
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
|
| 30 |
+
REPO = ROOT / "Ming-3.0-tts"
|
| 31 |
+
MODEL = ROOT / "Ming-3.0-tts-0.5b"
|
| 32 |
+
BUNDLE = ROOT / "webfm-eval"
|
| 33 |
+
OUT = ROOT / "radio"
|
| 34 |
+
CKPT = BUNDLE / "student4_rc.pt"
|
| 35 |
+
SEED = 20261031
|
| 36 |
+
STEPS = 4
|
| 37 |
+
GAP_S = 0.7
|
| 38 |
+
SR = 44100
|
| 39 |
+
|
| 40 |
+
SCRIPT_LLM = os.environ.get("SCRIPT_LLM", "Qwen/Qwen2.5-0.5B-Instruct")
|
| 41 |
+
CAST = {"叙述": "a08", "故事": "a08", "耳语": "a01", "开场": "a05", "收尾": "a08"}
|
| 42 |
+
|
| 43 |
+
FALLBACK = [
|
| 44 |
+
{"style": "开场", "text": "晚上好,这里是深夜频道,我是今晚陪你的人。"},
|
| 45 |
+
{"style": "叙述", "text": "窗外的雨下了一整晚,路灯把水汽照成一片模糊的黄。"},
|
| 46 |
+
{"style": "故事", "text": "很多年前,这条街上有一家很小的唱片店,老板总在打烊前放同一首歌。"},
|
| 47 |
+
{"style": "耳语", "text": "后来店关了,歌还在。"},
|
| 48 |
+
{"style": "叙述", "text": "如果你还醒着,就把灯关小一点,让声音替你把今天收好。"},
|
| 49 |
+
{"style": "耳语", "text": "晚安,我们明天见。"},
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def log(msg: str) -> None:
|
| 54 |
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def patch_fp32() -> None:
|
| 58 |
+
for name in ("ming_tts.py", "modeling_bailingmm.py"):
|
| 59 |
+
p = REPO / name
|
| 60 |
+
s = p.read_text()
|
| 61 |
+
s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
|
| 62 |
+
s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
|
| 63 |
+
s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
|
| 64 |
+
p.write_text(s)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def write_script() -> tuple[list[dict], str]:
|
| 68 |
+
"""Ask a small instruct model for the segment; fall back to a fixed script."""
|
| 69 |
+
import torch
|
| 70 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 71 |
+
|
| 72 |
+
prompt = (
|
| 73 |
+
"你是一个深夜电台的编剧。写一段约 60 秒的节目串词,共 6 句,每句 8 到 28 个字。\n"
|
| 74 |
+
"要求:前两句是正常叙述,中间讲一小段故事,最后两句逐渐转为耳语,收在很轻的一句上。\n"
|
| 75 |
+
"只输出 JSON 数组,不要任何解释、不要代码块标记。格式:\n"
|
| 76 |
+
'[{"style":"开场","text":"..."},{"style":"叙述","text":"..."},'
|
| 77 |
+
'{"style":"故事","text":"..."},{"style":"耳语","text":"..."}]\n'
|
| 78 |
+
"style 只能取 开场、叙述、故事、耳语 四个值之一。"
|
| 79 |
+
)
|
| 80 |
+
try:
|
| 81 |
+
tok = AutoTokenizer.from_pretrained(SCRIPT_LLM)
|
| 82 |
+
model = AutoModelForCausalLM.from_pretrained(SCRIPT_LLM, torch_dtype=torch.float32).cuda().eval()
|
| 83 |
+
msgs = [{"role": "user", "content": prompt}]
|
| 84 |
+
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 85 |
+
ids = tok([text], return_tensors="pt").to("cuda")
|
| 86 |
+
with torch.no_grad():
|
| 87 |
+
gen = model.generate(**ids, max_new_tokens=420, do_sample=True,
|
| 88 |
+
temperature=0.8, top_p=0.9,
|
| 89 |
+
pad_token_id=tok.eos_token_id)
|
| 90 |
+
raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 91 |
+
log(f"llm raw: {raw[:400]}")
|
| 92 |
+
del model
|
| 93 |
+
torch.cuda.empty_cache()
|
| 94 |
+
|
| 95 |
+
m = re.search(r"\[.*\]", raw, re.S)
|
| 96 |
+
rows = json.loads(m.group(0) if m else raw)
|
| 97 |
+
rows = [r for r in rows if isinstance(r, dict) and r.get("text")]
|
| 98 |
+
if len(rows) >= 4:
|
| 99 |
+
return rows[:8], "llm"
|
| 100 |
+
except Exception:
|
| 101 |
+
log("script LLM failed\n" + traceback.format_exc())
|
| 102 |
+
return FALLBACK, "fallback"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def cast(rows: list[dict]) -> list[dict]:
|
| 106 |
+
"""Assign a voice to each line and keep the plan explicit in the report."""
|
| 107 |
+
out = []
|
| 108 |
+
for i, r in enumerate(rows):
|
| 109 |
+
style = r.get("style") or "叙述"
|
| 110 |
+
slot = CAST.get(style, "a08")
|
| 111 |
+
out.append({"index": i, "style": style, "text": r["text"], "slot": slot})
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def main() -> None:
|
| 116 |
+
import torch
|
| 117 |
+
import soundfile as sf
|
| 118 |
+
from transformers import pipeline
|
| 119 |
+
|
| 120 |
+
(OUT / "lines").mkdir(parents=True, exist_ok=True)
|
| 121 |
+
torch.manual_seed(SEED)
|
| 122 |
+
|
| 123 |
+
plan, source = write_script()
|
| 124 |
+
lines = cast(plan)
|
| 125 |
+
(OUT / "script.json").write_text(json.dumps({"source": source, "lines": lines},
|
| 126 |
+
ensure_ascii=False, indent=1))
|
| 127 |
+
log(f"script from {source}: {len(lines)} lines")
|
| 128 |
+
for l in lines:
|
| 129 |
+
log(f" [{l['style']}] {l['slot']} {l['text']}")
|
| 130 |
+
|
| 131 |
+
voices = {v["slot"]: v for v in
|
| 132 |
+
json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"]}
|
| 133 |
+
|
| 134 |
+
sys.path.insert(0, str(REPO))
|
| 135 |
+
patch_fp32()
|
| 136 |
+
from ming_tts import MingTTS
|
| 137 |
+
import tts_tasks
|
| 138 |
+
sys.path.insert(0, str(BUNDLE / "eval"))
|
| 139 |
+
from score import load_t2s, score_row
|
| 140 |
+
|
| 141 |
+
table = load_t2s()
|
| 142 |
+
tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
|
| 143 |
+
report = {"script_source": source, "lines": [], "renders": {}}
|
| 144 |
+
|
| 145 |
+
def render(tag: str, use_student: bool) -> dict:
|
| 146 |
+
import copy
|
| 147 |
+
|
| 148 |
+
mm = tts.model
|
| 149 |
+
task_prompt = tts_tasks.build_tts_prompt("Chinese")
|
| 150 |
+
device = next(mm.parameters()).device
|
| 151 |
+
dtype = next(mm.parameters()).dtype
|
| 152 |
+
sampler = None
|
| 153 |
+
if use_student:
|
| 154 |
+
state = {k: v.float() for k, v in torch.load(CKPT, map_location="cpu").items()}
|
| 155 |
+
dit = copy.deepcopy(mm.flowloss.cfm.model.float())
|
| 156 |
+
dit.load_state_dict(state)
|
| 157 |
+
dit = dit.to(device).eval()
|
| 158 |
+
|
| 159 |
+
def sampler(z, hist, noise):
|
| 160 |
+
y = noise
|
| 161 |
+
for i in range(STEPS):
|
| 162 |
+
v = dit(x=y, t=torch.full((y.shape[0],), i / STEPS, device=device),
|
| 163 |
+
c=z, latent_history=hist, mask=None)[:, -1:, :]
|
| 164 |
+
y = y + v * (1.0 / STEPS)
|
| 165 |
+
return y.detach()
|
| 166 |
+
|
| 167 |
+
pieces, rows = [], []
|
| 168 |
+
for line in lines:
|
| 169 |
+
v = voices[line["slot"]]
|
| 170 |
+
wav_path = str(BUNDLE / v["wav"])
|
| 171 |
+
t0 = time.time()
|
| 172 |
+
try:
|
| 173 |
+
if use_student:
|
| 174 |
+
latent, spk = tts.prepare_prompt(wav_path, use_spk_emb=True)
|
| 175 |
+
latent = latent.to(device=device, dtype=dtype)
|
| 176 |
+
spk = [x.to(device=device, dtype=dtype) for x in spk]
|
| 177 |
+
ref = tts.synthesize(task="TTS", text=line["text"], language_id="Chinese",
|
| 178 |
+
prompt_wav_path=wav_path, prompt_text=v["prompt_text"],
|
| 179 |
+
use_spk_emb=True, raw_text=True,
|
| 180 |
+
max_decode_steps=max(32, min(400, int(len(line["text"]) * 3.5))))
|
| 181 |
+
ref = ref.cpu().numpy().reshape(-1)
|
| 182 |
+
frames = max(16, int(round(ref.size / 3528)))
|
| 183 |
+
y = _ar(mm, sampler, line["text"], task_prompt, latent,
|
| 184 |
+
v["prompt_text"], spk, frames)
|
| 185 |
+
else:
|
| 186 |
+
y = tts.synthesize(task="TTS", text=line["text"], language_id="Chinese",
|
| 187 |
+
prompt_wav_path=wav_path, prompt_text=v["prompt_text"],
|
| 188 |
+
use_spk_emb=True, raw_text=True,
|
| 189 |
+
max_decode_steps=max(32, min(400, int(len(line["text"]) * 3.5))))
|
| 190 |
+
y = y.cpu().numpy().reshape(-1)
|
| 191 |
+
except Exception:
|
| 192 |
+
log(f"{tag} line {line['index']} failed\n{traceback.format_exc()}")
|
| 193 |
+
continue
|
| 194 |
+
wall = time.time() - t0
|
| 195 |
+
p = OUT / "lines" / f"{tag}_{line['index']:02d}.wav"
|
| 196 |
+
sf.write(str(p), y, SR)
|
| 197 |
+
rows.append({**line, "seconds": round(y.size / SR, 2), "wall": round(wall, 1),
|
| 198 |
+
"rtf": round(wall / max(1e-6, y.size / SR), 2),
|
| 199 |
+
"wav": str(p)})
|
| 200 |
+
log(f"{tag} {line['index']} {line['style']} {y.size/SR:.2f}s wall {wall:.1f}s")
|
| 201 |
+
pieces.append(y)
|
| 202 |
+
pieces.append(np.zeros(int(GAP_S * SR), dtype=np.float32))
|
| 203 |
+
|
| 204 |
+
if not pieces:
|
| 205 |
+
return {"rows": [], "seconds": 0}
|
| 206 |
+
full = np.concatenate(pieces[:-1])
|
| 207 |
+
peak = float(np.abs(full).max()) or 1.0
|
| 208 |
+
full = (full / peak * 0.92).astype(np.float32)
|
| 209 |
+
sf.write(str(OUT / f"radio_{tag}.wav"), full, SR)
|
| 210 |
+
return {"rows": rows, "seconds": round(full.size / SR, 1)}
|
| 211 |
+
|
| 212 |
+
teacher = render("teacher", use_student=False)
|
| 213 |
+
report["renders"]["teacher"] = teacher
|
| 214 |
+
log(f"teacher segment: {teacher['seconds']}s, {len(teacher['rows'])} lines")
|
| 215 |
+
|
| 216 |
+
student = render("student", use_student=True)
|
| 217 |
+
report["renders"]["student"] = student
|
| 218 |
+
log(f"student segment: {student['seconds']}s, {len(student['rows'])} lines")
|
| 219 |
+
|
| 220 |
+
# Transcribe once at the end: whisper is ~1 GB and does not need to be
|
| 221 |
+
# resident while the two DiTs and the backbone are generating.
|
| 222 |
+
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small",
|
| 223 |
+
device=0, torch_dtype=torch.float16)
|
| 224 |
+
|
| 225 |
+
def transcribe(y):
|
| 226 |
+
out = asr({"array": y.astype(np.float32), "sampling_rate": SR},
|
| 227 |
+
generate_kwargs={"language": "zh", "task": "transcribe"})
|
| 228 |
+
return (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
|
| 229 |
+
|
| 230 |
+
for tag in ("teacher", "student"):
|
| 231 |
+
rs = report["renders"][tag]["rows"]
|
| 232 |
+
for r in rs:
|
| 233 |
+
y, _ = sf.read(r["wav"], dtype="float32")
|
| 234 |
+
r["hyp"] = transcribe(y)
|
| 235 |
+
r["cer"] = score_row({"text": r["text"], "hyp_text": r["hyp"]}, table)["cer_norm"]
|
| 236 |
+
if rs:
|
| 237 |
+
log(f"{tag}: mean cer {np.mean([r['cer'] for r in rs]):.3f} "
|
| 238 |
+
f"mean rtf {np.mean([r['rtf'] for r in rs]):.2f}")
|
| 239 |
+
|
| 240 |
+
(OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=1))
|
| 241 |
+
log("done")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _ar(mm, sampler, text, task_prompt, prompt_latent, prompt_text, spk, frames):
|
| 245 |
+
import torch
|
| 246 |
+
|
| 247 |
+
device = next(mm.parameters()).device
|
| 248 |
+
dtype = next(mm.parameters()).dtype
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
input_ids, inputs_embeds = mm.prepare_input_embed(
|
| 251 |
+
prompt=task_prompt, text=text, spk_emb=spk,
|
| 252 |
+
prompt_latent=prompt_latent, prompt_text=prompt_text)
|
| 253 |
+
attention_mask = torch.ones(input_ids.shape, device=device)
|
| 254 |
+
position_ids = (attention_mask.cumsum(-1) - 1).masked_fill_(attention_mask == 0, 1)
|
| 255 |
+
past = None
|
| 256 |
+
hist = torch.zeros(1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype)
|
| 257 |
+
start = mm.history_patch_size - prompt_latent.size(1)
|
| 258 |
+
if start < 0:
|
| 259 |
+
hist[:] = prompt_latent[:, -start:, :]
|
| 260 |
+
else:
|
| 261 |
+
hist[:, start:, :] = prompt_latent
|
| 262 |
+
out = []
|
| 263 |
+
for _ in range(frames):
|
| 264 |
+
with torch.no_grad():
|
| 265 |
+
hidden = mm.model(attention_mask=attention_mask, position_ids=position_ids,
|
| 266 |
+
inputs_embeds=inputs_embeds, audio_mask=None, image_mask=None,
|
| 267 |
+
output_hidden_states=True, return_dict=True, use_cache=True,
|
| 268 |
+
past_key_values=past)
|
| 269 |
+
past = hidden.past_key_values
|
| 270 |
+
z = hidden.hidden_states[-1][:, -1:, :]
|
| 271 |
+
noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype)
|
| 272 |
+
with torch.no_grad():
|
| 273 |
+
latent = sampler(z, hist, noise).to(device=device, dtype=dtype)
|
| 274 |
+
out.append(latent.detach())
|
| 275 |
+
inputs_embeds = mm.linear_proj_audio(latent)
|
| 276 |
+
position_ids = position_ids[:, -1:] + 1
|
| 277 |
+
attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device)
|
| 278 |
+
hist[:, :-mm.patch_size, :] = hist[:, mm.patch_size:, :].clone()
|
| 279 |
+
hist[:, -mm.patch_size:, :] = latent
|
| 280 |
+
with torch.no_grad():
|
| 281 |
+
speech = mm.audio.decode(torch.cat(out, dim=1), past_key_values=None,
|
| 282 |
+
use_cache=False, last_chunk=True)[0]
|
| 283 |
+
return speech.cpu().float().reshape(-1).numpy()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|