Inference quality boost: 32-step Midpoint ODE, cfg=1.5, temp=0.667, whole-paragraph natural phrasing in narrate.py
Browse filesFiles changed (4)
- config.py+3-2
- models/flow_matching.py+18-18
- models/tts_engine.py+3
- narrate.py+61-38
67 unmodified lines686970717273747567 unmodified lines# Inference defaults (V1 lessons: min_frames=2 prevents short/edge char drop, speed=0.92 crisp)default_speed: float = 0.92min_frames: int = 2default_steps: int = 10default_cfg_scale: float = 2.0@dataclass67 unmodified lines68697071727374757667 unmodified lines# Inference defaults (V1 lessons: min_frames=2 prevents short/edge char drop, speed=0.92 crisp)default_speed: float = 0.92min_frames: int = 2default_steps: int = 32default_cfg_scale: float = 1.5default_temperature: float = 0.667@dataclass
113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147113 unmodified linesvector_field: ConvNeXtCFMVectorField,cond: torch.Tensor,prior_mel: Optional[torch.Tensor] = None,steps: int = 10,cfg_scale: float = 2.0,temperature: float = 0.85,) -> torch.Tensor:"""Midpoint / Euler OT-CFM ODE sampler with Classifier-Free Guidance (CFG)."""bsz, _, t_mel = cond.shapedevice = cond.devicedtype = cond.dtypex = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperatureif prior_mel is not None:# Light prior warm-start optional or pure noise; standard OT-CFM starts from N(0, I)passdt = 1.0 / float(steps)null_cond = torch.zeros_like(cond)for i in range(steps):t_cur = torch.full((bsz,), float(i) * dt, device=device, dtype=dtype)if cfg_scale > 1.0:x_in = torch.cat([x, x], dim=0)t_in = torch.cat([t_cur, t_cur], dim=0)c_in = torch.cat([cond, null_cond], dim=0)v_both = vector_field(x_in, t_in, c_in, mask=None)v_cond, v_uncond = v_both.chunk(2, dim=0)v = v_uncond + cfg_scale * (v_cond - v_uncond)else:v = vector_field(x, t_cur, cond, mask=None)x = x + v * dtreturn x113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147113 unmodified linesvector_field: ConvNeXtCFMVectorField,cond: torch.Tensor,prior_mel: Optional[torch.Tensor] = None,steps: int = 32,cfg_scale: float = 1.5,temperature: float = 0.667,) -> torch.Tensor:"""Midpoint OT-CFM ODE sampler with Classifier-Free Guidance (CFG) for clean articulation."""bsz, _, t_mel = cond.shapedevice = cond.devicedtype = cond.dtypex = torch.randn((bsz, vector_field.mel_dim, t_mel), device=device, dtype=dtype) * temperaturedt = 1.0 / float(steps)null_cond = torch.zeros_like(cond)def _eval_v(state: torch.Tensor, t_val: float) -> torch.Tensor:t_tensor = torch.full((bsz,), t_val, device=device, dtype=dtype)if cfg_scale > 1.0:x_in = torch.cat([state, state], dim=0)t_in = torch.cat([t_tensor, t_tensor], dim=0)c_in = torch.cat([cond, null_cond], dim=0)v_cond, v_uncond = vector_field(x_in, t_in, c_in, mask=None).chunk(2, dim=0)return v_uncond + cfg_scale * (v_cond - v_uncond)return vector_field(state, t_tensor, cond, mask=None)for i in range(steps):t_cur = float(i) * dtv1 = _eval_v(x, t_cur)x_mid = x + 0.5 * dt * v1v2 = _eval_v(x_mid, t_cur + 0.5 * dt)x = x + dt * v2return x
101 unmodified lines10210310410510610710810911011111211311 unmodified lines125126127128129101 unmodified linesspeed: Optional[float] = None,steps: Optional[int] = None,cfg_scale: Optional[float] = None,) -> torch.Tensor:self.eval()m = self.cfg.modelspeed = m.default_speed if speed is None else speedsteps = m.default_steps if steps is None else stepscfg_scale = m.default_cfg_scale if cfg_scale is None else cfg_scaletext_mask = token_ids != 0emotion_ids = torch.full((token_ids.shape[0],), int(emotion_id), dtype=torch.long, device=token_ids.device)11 unmodified linesprior_mel=prior_mel,steps=steps,cfg_scale=cfg_scale,)return mel_denorm * self.cfg.audio.mel_std + self.cfg.audio.mel_mean101 unmodified lines10210310410510610710810911011111211311411511 unmodified lines127128129130131132101 unmodified linesspeed: Optional[float] = None,steps: Optional[int] = None,cfg_scale: Optional[float] = None,temperature: Optional[float] = None,) -> torch.Tensor:self.eval()m = self.cfg.modelspeed = m.default_speed if speed is None else speedsteps = m.default_steps if steps is None else stepscfg_scale = m.default_cfg_scale if cfg_scale is None else cfg_scaletemperature = m.default_temperature if temperature is None else temperaturetext_mask = token_ids != 0emotion_ids = torch.full((token_ids.shape[0],), int(emotion_id), dtype=torch.long, device=token_ids.device)11 unmodified linesprior_mel=prior_mel,steps=steps,cfg_scale=cfg_scale,temperature=temperature,)return mel_denorm * self.cfg.audio.mel_std + self.cfg.audio.mel_mean
16 unmodified lines17181920212223242526272829303132333435363738394041422 unmodified lines45464748495051525354555657585960616263646566676869707172737475767716 unmodified linesdef script_chunks(text, tokenizer, limit=220):for paragraph in re.split(r"\n\s*\n", text.strip()):sentences = re.split(r"(?<=[।॥!?])\s*|(?<=\.)\s+(?=\S)", paragraph.strip())parts = []for sentence in filter(str.strip, sentences):words = []for word in sentence.split():if words and tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit:parts.append((" ".join(words), 70))words = []if tokenizer.text_to_ids(word).numel() > limit:raise ValueError("A single word exceeds the model chunk limit")words.append(word)if words:parts.append((" ".join(words), 180))if parts:parts[-1] = (parts[-1][0], 360)yield from parts@torch.inference_mode()def render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion="neutral", speed=None):device = next(model.parameters()).deviceemotion_id = EMOTION_TO_ID[emotion]destination = Path(destination)2 unmodified linesraise ValueError("Speed must be finite and positive")was_training = model.trainingmodel.eval()with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as f:temporary = f.nametry:with wave.open(temporary, "wb") as wav:wav.setparams((1, 2, cfg.audio.sample_rate, 0, "NONE", "not compressed"))pause = 0rendered = 0for chunk, next_pause in script_chunks(text, tokenizer):ids = tokenizer.text_to_ids(chunk)if not ids.numel():continuemel = model.synthesize(ids[None].to(device), emotion_id=emotion_id, speed=speed)samples = vocoder.decode(mel)[0].float().cpu().flatten()if not samples.numel() or not torch.isfinite(samples).all():raise ValueError("Vocoder returned invalid audio")fade = min(samples.numel() // 2, cfg.audio.sample_rate // 200)if fade:ramp = torch.linspace(0, 1, fade)samples[:fade] *= rampsamples[-fade:] *= ramp.flip(0)wav.writeframesraw(bytes(2 * round(cfg.audio.sample_rate * pause / 1000)))pcm = samples.clamp(-1, 1).mul(32767).round().short().numpy().astype("<i2", copy=False)wav.writeframesraw(pcm.tobytes())pause = next_pauserendered += 1if not rendered:raise ValueError("Script contains no speakable text")os.replace(temporary, destination)finally:Path(temporary).unlink(missing_ok=True)16 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354552 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910016 unmodified linesdef script_chunks(text, tokenizer, limit=220):for paragraph in re.split(r"\n\s*\n", text.strip()):sentences = list(filter(str.strip, re.split(r"(?<=[।॥!?])\s*|(?<=\.)\s+(?=\S)", paragraph.strip())))parts = []buf = []for sentence in sentences:cand = " ".join(buf + [sentence]) if buf else sentenceif buf and tokenizer.text_to_ids(cand).numel() <= limit:buf.append(sentence)continueif buf:parts.append((" ".join(buf), 180))buf = []if tokenizer.text_to_ids(sentence).numel() <= limit:buf.append(sentence)else:words = []for word in sentence.split():if words and tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit:parts.append((" ".join(words), 70))words = []if tokenizer.text_to_ids(word).numel() > limit:raise ValueError("A single word exceeds the model chunk limit")words.append(word)if words:buf.append(" ".join(words))if buf:parts.append((" ".join(buf), 320))if parts:parts[-1] = (parts[-1][0], 320)yield from parts@torch.inference_mode()def render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion="neutral", speed=None, seed=42):device = next(model.parameters()).deviceemotion_id = EMOTION_TO_ID[emotion]destination = Path(destination)2 unmodified linesraise ValueError("Speed must be finite and positive")was_training = model.trainingmodel.eval()devices = [device.index or 0] if device.type == "cuda" else []with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as f:temporary = f.nametry:with torch.random.fork_rng(devices=devices):if seed is not None:torch.manual_seed(int(seed))if device.type == "cuda":torch.cuda.manual_seed(int(seed))with wave.open(temporary, "wb") as wav:wav.setparams((1, 2, cfg.audio.sample_rate, 0, "NONE", "not compressed"))pause = 0rendered = 0for chunk, next_pause in script_chunks(text, tokenizer):ids = tokenizer.text_to_ids(chunk)if not ids.numel():continuemel = model.synthesize(ids[None].to(device), emotion_id=emotion_id, speed=speed)samples = vocoder.decode(mel)[0].float().cpu().flatten()if not samples.numel() or not torch.isfinite(samples).all():raise ValueError("Vocoder returned invalid audio")fade = min(samples.numel() // 2, cfg.audio.sample_rate // 200)if fade:ramp = torch.linspace(0, 1, fade)samples[:fade] *= rampsamples[-fade:] *= ramp.flip(0)if pause > 0:n_gap = round(cfg.audio.sample_rate * pause / 1000)room = (torch.randn(n_gap) * 1.5e-4).clamp(-0.002, 0.002)pcm_gap = room.mul(32767).round().short().numpy().astype("<i2", copy=False)wav.writeframesraw(pcm_gap.tobytes())pcm = samples.clamp(-1, 1).mul(32767).round().short().numpy().astype("<i2", copy=False)wav.writeframesraw(pcm.tobytes())pause = next_pauserendered += 1if not rendered:raise ValueError("Script contains no speakable text")os.replace(temporary, destination)finally:Path(temporary).unlink(missing_ok=True)
config.py+3-2
models/flow_matching.py+18-18
models/tts_engine.py+3
narrate.py+61-38