File size: 4,659 Bytes
cc5e704 | 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 | """Regression tests for the scratch-training audit."""
import io
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import torch
from scipy.io import wavfile
from config import AudioConfig, MurliV15Config
from data.dataset import MurliV15Dataset, _map_emotion
from data.text_cleaner import BilingualTextTokenizer
from train import train
class ScratchTrainingTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.shard = self.root / "small.parquet"
self.rows = []
for idx in range(7):
stream = io.BytesIO()
pcm = np.sin(np.arange(19200) * (0.04 + 0.005 * idx)) * 8000
wavfile.write(stream, 24000, pcm.astype(np.int16))
self.rows.append(dict(text=f"story {idx}", speaker="reader", audio={"bytes": stream.getvalue()}))
pq.write_table(pa.Table.from_pylist(self.rows), self.shard, row_group_size=2)
def dataset(self, **kw):
return MurliV15Dataset(parquet_paths=[str(self.shard)], target_speaker="reader",
cache_dir=str(self.root / "features"), skip_invalid=False, **kw)
def test_filter_split_cache_and_silence(self):
ds = self.dataset()
train_set, val_set = ds.split()
self.assertEqual((len(train_set), len(val_set)), (6, 1))
self.assertTrue({r["uid"] for r in train_set.rows}.isdisjoint(r["uid"] for r in val_set.rows))
self.assertTrue(all("audio_bytes" not in r for r in ds.rows))
self.assertEqual(ds[0]["mel"].shape[1], 76)
self.assertEqual(self.dataset(audio_cfg=AudioConfig(hop_length=128))[0]["mel"].shape[1], 151)
with self.assertRaisesRegex(ValueError, "Silent"):
ds.proc.normalize_waveform(torch.zeros(24000), 24000)
self.assertEqual(_map_emotion("narration"), 7)
self.assertEqual(_map_emotion(None), 0)
def test_spoken_numbers(self):
t = BilingualTextTokenizer(use_g2p_en=False)
for a, b, lang in [
("12 years", "twelve years", None), ("12 साल", "बारह साल", "hi"), ("३.५%", "तीन दशमलव पाँच प्रतिशत", "hi"),
("-12.05%", "minus twelve point zero five percent", "en"),
("1,25,000", "एक लाख पच्चीस हज़ार", "hi"), ("007", "शून्य शून्य सात", "hi"),
]:
self.assertEqual(t.text_to_ids(a, lang).tolist(), t.text_to_ids(b, lang).tolist())
def test_resume_matches_uninterrupted_training(self):
args = SimpleNamespace(subdirs=None, parquet=[str(self.shard)], target_speaker="reader",
cache_dir=str(self.root / "features"), checkpoint_dir=str(self.root / "first"),
num_workers=0, batch_size=2, max_steps=3, resume=None)
def config():
cfg = MurliV15Config()
m = cfg.model
m.text_dim, m.text_heads, m.text_layers = 32, 2, 1
m.prosody_layers, m.cfm_blocks, m.cfm_hidden_dim, m.cfm_time_dim = 1, 1, 32, 16
cfg.train.save_every = cfg.train.val_every = 1
return cfg
train(args, config())
first = Path(args.checkpoint_dir)
target = torch.load(first / "murli_v15_final.pt", weights_only=True)
self.assertEqual({int(v["step"]) for v in target["optimizer"]["state"].values()}, {3})
for path in ("murli_v15_best.pt", "murli_v15_final.pt"):
checkpoint = torch.load(first / path, weights_only=True)
self.assertTrue({"optimizer","rng","scaler","epoch","offset"} <= checkpoint.keys())
args.resume = str(first / "murli_v15_step_000001.pt")
args.checkpoint_dir = str(self.root / "resumed")
train(args, config())
resumed = torch.load(self.root / "resumed" / "murli_v15_final.pt", weights_only=True)
self.assertEqual((target["step"], target["epoch"], target["offset"]),
(resumed["step"], resumed["epoch"], resumed["offset"]))
self.assertTrue(all(torch.equal(tensor, resumed["model"][key]) for key,tensor in target["model"].items()))
self.assertEqual(target["best_val_cfm"], resumed["best_val_cfm"])
args.resume = str(self.root / "missing.pt")
with self.assertRaises(FileNotFoundError):
train(args, config())
|