File size: 12,981 Bytes
d4101a0 | 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | """Shared training utilities for Lua Nova V1."""
from __future__ import annotations
from collections import defaultdict
import json
import math
from pathlib import Path
import torch
from torch import nn
from ..config import CHECKPOINT_FORMAT, CFMConfig
from ..data.dataset import AnnotatedDataset, collate
from ..models.bigvgan import BigVGANMelExtractor
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import masked_mean
from ..text.phonemizer import frontend_fingerprint, frontend_identity
from ..utils.checkpoint import atomic_save
VALIDATION_SAMPLE_TEXTS = (
"Amanhã de manhã eu vou pôr o pão na mesa para os irmãos.",
"Eu almoço cedo quando o almoço está pronto no jogo.",
"Dia vinte e dois de março às quatorze horas custou duzentos reais.",
"Você tem certeza de que ele vem hoje à tarde?",
)
def masked_std(value: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Standard deviation per row over valid masked positions, returning ``[B]``."""
count = mask.sum(1).clamp_min(1)
mean = (value * mask).sum(1) / count
return (((value - mean[:, None]).square() * mask).sum(1) / count + 1e-8).sqrt()
def balanced_indices(dataset: AnnotatedDataset, limit: int) -> list[int]:
"""Deterministic round-robin sample indices balanced across speakers."""
groups: dict[str, list[int]] = defaultdict(list)
for i, row in enumerate(dataset.rows):
groups[row["speaker"]].append(i)
limit = min(max(limit, len(groups)), len(dataset.rows))
selected: list[int] = []
for offset in range(limit):
for voice in sorted(groups):
if offset < len(groups[voice]):
selected.append(groups[voice][offset])
if len(selected) == limit:
return selected
return selected
def check_leakage(train: AnnotatedDataset, validation: AnnotatedDataset) -> None:
"""Ensure zero ID or text overlap between training and validation splits."""
ids = {r["id"] for r in train.rows}
texts: dict[str, list[str]] = defaultdict(list)
for row in train.rows:
texts[row["text_hash"]].append(row["id"])
collisions = []
for row in validation.rows:
if row["id"] in ids or row["text_hash"] in texts:
collisions.append(
{
"validation_id": row["id"],
"train_ids": texts.get(row["text_hash"], [])[:3],
"text": row.get("text", "")[:160],
}
)
if len(collisions) == 5:
break
if collisions:
raise ValueError("train/validation leakage detected: " + json.dumps(collisions, ensure_ascii=False))
def cosine_lr(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float) -> float:
"""Linear warmup followed by cosine decay down to ``min_lr``."""
if step < warmup:
return base_lr * (step + 1) / max(warmup, 1)
prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))
def update_ema(ema_model: nn.Module, model: nn.Module, decay: float, on_cpu: bool = False) -> None:
"""Update exponential moving average parameters matching trainable flags on GPU or CPU."""
with torch.no_grad():
for p_ema, p in zip(ema_model.parameters(), model.parameters()):
if p.requires_grad:
src = p.detach().cpu() if on_cpu else p
p_ema.mul_(decay).add_(src, alpha=1.0 - decay)
def export_cfm_checkpoint(model: LuaNovaCFM, path: Path | str, step: int, annotation: str | None = None) -> None:
"""Save a portable LuaNovaCFM checkpoint containing config, frontend identity, and state_dict."""
atomic_save(
{
"format_version": CHECKPOINT_FORMAT,
"arch": "lua_nova_v1_cfm",
"cfm_config": model.cfm_config.to_dict(),
"step": int(step),
"frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
"annotation": annotation,
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()},
},
path,
)
def load_cfm_model(
path: Path | str,
device: str = "cpu",
load_vocos: bool | None = None,
) -> LuaNovaCFM:
"""Load a LuaNovaCFM checkpoint (either full or stripped of legacy Vocos buffers)."""
state = torch.load(path, map_location="cpu", weights_only=True)
cfg = CFMConfig.from_dict(state["cfm_config"])
use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
model = LuaNovaCFM(cfg, load_vocos=use_vocos)
sd = state["model"]
if not use_vocos:
# Filter unused legacy Vocos weights while keeping strict validation over all active tensors.
sd = {
k: v.float()
for k, v in sd.items()
if not (k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"))
}
model.load_state_dict(sd, strict=True)
return model.to(device).eval()
class MelDatasetView:
"""In-memory view overriding ``vocos_mel`` with precomputed BigVGAN Slaney-100 mels."""
def __init__(self, ds: AnnotatedDataset, mels: dict[int, torch.Tensor]) -> None:
self.ds = ds
self.mels = mels
def __getitem__(self, idx: int) -> dict:
item = dict(self.ds[idx])
item["vocos_mel"] = self.mels[idx].float()
return item
@torch.no_grad()
def precompute_bigvgan_mels(
ds: AnnotatedDataset,
indices: list[int],
extractor: BigVGANMelExtractor,
device: str,
compute_stats: bool = False,
) -> tuple[dict[int, torch.Tensor], torch.Tensor | None, torch.Tensor | None]:
"""Extract unpadded 24 kHz 100-band Slaney log-mels in RAM without rewriting disk files."""
mels: dict[int, torch.Tensor] = {}
sum_1 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
sum_2 = torch.zeros(extractor.n_mels, dtype=torch.float64, device=device)
total_frames = 0
for idx in indices:
wav = ds[idx]["wave"].to(device=device, dtype=torch.float32)
mel = extractor(wav)[0]
if compute_stats:
mf64 = mel.double()
sum_1 += mf64.sum(dim=0)
sum_2 += mf64.square().sum(dim=0)
total_frames += int(mel.shape[0])
mels[idx] = mel.half().cpu()
if not compute_stats:
return mels, None, None
mean = (sum_1 / max(total_frames, 1)).float().cpu()
var = (sum_2 / max(total_frames, 1) - (sum_1 / max(total_frames, 1)).square()).clamp_min(1e-8)
scale = var.sqrt().float().clamp_min(1e-4).cpu()
return mels, mean, scale
def cfm_loss_step(
model: LuaNovaCFM,
batch: dict,
teacher_prob: float = 0.15,
prior_weight: float = 1.0,
delta_weight: float = 0.6,
freq_delta_weight: float = 0.35,
hf_boost: float = 1.35,
f0_smooth_prob: float = 0.0,
training: bool = True,
) -> tuple[torch.Tensor, dict]:
"""Compute prior-centered OT-CFM objective plus temporal and frequency derivative losses."""
c = model.config
cfg = model.cfm_config
with torch.no_grad() if model._frontend_frozen else torch.enable_grad():
hidden, token_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
prosody_token_ctx, clause_ctx_tok = model.encode_prosody_context(
hidden, batch["tokens"], batch["stress"], token_mask
)
acoustic_frames, prosody_frames, frame_mask, lengths = model.expand_with_context(
hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
)
if teacher_prob >= 1.0 and cfg.acoustic_from_frames:
prosody_hidden = None
prediction = None
else:
prosody_hidden, prediction, _ = model.sample_prosody(prosody_frames, frame_mask, seed=0)
target_prosody = batch["prosody"]
if teacher_prob >= 1.0:
condition = target_prosody
elif training and teacher_prob > 0:
teacher = torch.rand(len(lengths), device=lengths.device) < teacher_prob
condition = torch.where(teacher[:, None, None], target_prosody, model.hard_prosody(prediction.detach()))
else:
condition = model.hard_prosody(prediction.detach())
if training and f0_smooth_prob > 0:
condition = smooth_f0_channel(condition, f0_smooth_prob)
base_h = acoustic_frames if cfg.acoustic_from_frames else prosody_hidden
cond, prior_mel = model.condition_and_prior(base_h, condition, frame_mask)
f0_feats = f0_features(condition, frame_mask) if cfg.use_f0_harmonics else None
gate = energy_noise_gate(condition, frame_mask) if cfg.use_energy_gate else 1.0
x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * frame_mask[..., None]
if hf_boost != 1.0:
ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
ch_w[..., 60:] = hf_boost
ch_w = ch_w / ch_w.mean()
else:
ch_w = 1.0
prior_loss = masked_mean(((prior_mel - x1).abs() * ch_w).mean(-1), frame_mask)
b = x1.shape[0]
if training:
t = torch.sigmoid(torch.randn(b, device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
else:
t = torch.full((b,), 0.5, device=x1.device, dtype=torch.float32)
eps = torch.randn_like(x1)
x0 = (prior_mel.detach() + cfg.prior_sigma * gate * eps) * frame_mask[..., None]
t_view = t[:, None, None]
x_t = ((1.0 - t_view) * x0 + t_view * x1) * frame_mask[..., None]
v_target = (x1 - x0) * frame_mask[..., None]
if training and cfg.cfg_dropout > 0:
drop = (torch.rand(b, device=x1.device) < cfg.cfg_dropout)[:, None, None]
cond_in = torch.where(drop, torch.zeros_like(cond), cond)
prior_in = torch.where(drop, torch.zeros_like(prior_mel), prior_mel.detach())
f0_in = torch.where(drop, torch.zeros_like(f0_feats), f0_feats) if f0_feats is not None else None
else:
cond_in = cond
prior_in = prior_mel.detach()
f0_in = f0_feats
v_pred = model.flow(x_t, t, cond_in, prior_in, frame_mask, f0_feats=f0_in)
cfm_loss = masked_mean(((v_pred - v_target).abs() * ch_w).mean(-1), frame_mask)
x1_hat = x_t + (1.0 - t_view) * v_pred
pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
t_weight = t[:, None]
delta_err = ((x1_hat[:, 1:] - x1_hat[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1)
delta_loss = masked_mean(delta_err * t_weight, pair_mask)
if freq_delta_weight > 0:
f_err = ((x1_hat[..., 1:] - x1_hat[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1)
freq_delta_loss = masked_mean(f_err * t_weight, frame_mask)
else:
freq_delta_loss = x1.new_zeros(())
loss = cfm_loss + prior_weight * prior_loss + delta_weight * delta_loss + freq_delta_weight * freq_delta_loss
metrics = {
"loss": float(loss.detach()),
"cfm": float(cfm_loss.detach()),
"prior": float(prior_loss.detach()),
"delta": float(delta_loss.detach()),
"f_delta": float(freq_delta_loss.detach()),
}
return loss, metrics
@torch.no_grad()
def validate_cfm(
model: LuaNovaCFM,
dataset,
indices: list[int],
device: str,
delta_weight: float = 0.6,
freq_delta_weight: float = 0.35,
hf_boost: float = 1.35,
) -> dict:
"""Evaluate OT-CFM losses in both predicted-prosody and teacher-forced modes."""
was_training = model.training
model.eval()
totals: dict[str, float] = defaultdict(float)
weight = 0
for start in range(0, len(indices), 8):
batch = collate([dataset[i] for i in indices[start : start + 8]], device)
sz = len(batch["frame_lengths"])
_, m = cfm_loss_step(
model,
batch,
teacher_prob=0.0,
delta_weight=delta_weight,
freq_delta_weight=freq_delta_weight,
hf_boost=hf_boost,
training=False,
)
for k, v in m.items():
totals[f"val_{k}"] += v * sz
_, m_gt = cfm_loss_step(
model,
batch,
teacher_prob=1.0,
delta_weight=delta_weight,
freq_delta_weight=freq_delta_weight,
hf_boost=hf_boost,
training=False,
)
for k, v in m_gt.items():
totals[f"val_gt_{k}"] += v * sz
weight += sz
if was_training:
model.train()
return {k: v / max(weight, 1) for k, v in totals.items()}
|