Add sequential shard cache warmup (eliminates 72-shard Parquet random I/O & 100% host RAM thrash)
Browse filesFiles changed (4)
47 unmodified lines48495047 unmodified lines- **2026-12-01 (Speed Tuning):** Removed full-tensor FP32 allocation in `ConvNeXt1DBlock` GRN (`layers.py`) and added `prefetch_factor=4` + `float32_matmul_precision("high")` in `train.py`.- **2026-12-01 (13:19 Audit & Verification):** Verified user hardening edits (`ज्ञान→gjaːn̪`, `मतलब→mət̪ləb`, `प्रगति→pɾəgət̪ɪ`, English `"3.5 percent"`, `150 Hz F0` non-zero separation, corrupt audio skip + `--strict_dataset`, batched `B>1` padded synthesis, `cfm_step.onnx` reduced to `69.71 MiB`). `test_v16.py` → `Ran 3 tests in 49.749s — OK`. Pushed to `ViuAI/Murli-V1.6-Code`.- **2026-12-01 (Host RAM Fix):** Added `use_threads=False` + `pa.default_memory_pool().release_unused()` in `dataset.py` and lowered `prefetch_factor=2` in `train.py` to eliminate 100% host RAM thrashing across DataLoader workers.47 unmodified lines4849505147 unmodified lines- **2026-12-01 (Speed Tuning):** Removed full-tensor FP32 allocation in `ConvNeXt1DBlock` GRN (`layers.py`) and added `prefetch_factor=4` + `float32_matmul_precision("high")` in `train.py`.- **2026-12-01 (13:19 Audit & Verification):** Verified user hardening edits (`ज्ञान→gjaːn̪`, `मतलब→mət̪ləb`, `प्रगति→pɾəgət̪ɪ`, English `"3.5 percent"`, `150 Hz F0` non-zero separation, corrupt audio skip + `--strict_dataset`, batched `B>1` padded synthesis, `cfm_step.onnx` reduced to `69.71 MiB`). `test_v16.py` → `Ran 3 tests in 49.749s — OK`. Pushed to `ViuAI/Murli-V1.6-Code`.- **2026-12-01 (Host RAM Fix):** Added `use_threads=False` + `pa.default_memory_pool().release_unused()` in `dataset.py` and lowered `prefetch_factor=2` in `train.py` to eliminate 100% host RAM thrashing across DataLoader workers.- **2026-12-01 (1.0x Sequential Cache Warmup):** Diagnosed random 72-shard Parquet row-group read amplification (`13% GPU / 100% Host RAM` in Vast.ai dashboard). Added `warm_cache_by_shard()` (`dataset.py`, wired in `train.py`) so each Parquet shard is read sequentially once before GPU training starts.
8 unmodified lines91011121314285 unmodified lines3003013028 unmodified linesimport mathimport osimport warningsfrom copy import copyfrom dataclasses import asdictfrom pathlib import Path285 unmodified lines"speaker_ids": speaker_ids,"emotion_ids": emotion_ids,}8 unmodified lines910111213141516285 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893908 unmodified linesimport mathimport osimport warningsfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutorfrom copy import copyfrom dataclasses import asdictfrom pathlib import Path285 unmodified lines"speaker_ids": speaker_ids,"emotion_ids": emotion_ids,}def _warm_shard_worker(task: Tuple[str, List[Dict[str, Any]], AudioConfig, str, str]) -> Tuple[int, int]:"""Decode and cache all uncached rows of ONE Parquet shard sequentially (1.0x disk read)."""import pyarrow as paimport pyarrow.parquet as pqshard_path, entries, audio_cfg, cache_dir, feature_version = taskproc = AudioProcessor(audio_cfg)tokenizer = BilingualTextTokenizer(use_g2p_en=False)by_group: Dict[int, List[Dict[str, Any]]] = defaultdict(list)for r in entries:cache_path = os.path.join(cache_dir, f"{r['uid']}-{feature_version}.pt")if not os.path.exists(cache_path):by_group[r["group"]].append(r)if not by_group:return 0, 0pf = pq.ParquetFile(shard_path)done = skipped = 0for group_idx in sorted(by_group):group_rows = by_group[group_idx]audio_col = group_rows[0]["audio_column"]col = pf.read_row_group(group_idx, columns=[audio_col], use_threads=False).column(0)for r in group_rows:cache_path = os.path.join(cache_dir, f"{r['uid']}-{feature_version}.pt")try:val = col[r["offset"]].as_py()raw_bytes = val.get("bytes") if isinstance(val, dict) else valwav, sr = read_audio_bytes(raw_bytes)if sr <= 0 or not 0.8 <= wav.shape[-1] / sr <= 18.0:raise ValueError("Duration outside 0.8-18.0s")wav_norm = proc.normalize_waveform(wav, sr)mel_raw, f0, energy = proc.extract_features(wav_norm)mel = (mel_raw - audio_cfg.mel_mean) / audio_cfg.mel_stdtokens = tokenizer.text_to_ids(r["text"])if tokens.numel() == 0 or mel.shape[1] < tokens.numel():raise ValueError("MAS infeasible")atomic_save({"tokens": tokens, "mel": mel, "f0": f0, "energy": energy}, cache_path)done += 1except Exception:skipped += 1del colpa.default_memory_pool().release_unused()return done, skippeddef warm_cache_by_shard(dataset: MurliV16Dataset, num_workers: int = 4) -> None:"""Pre-build Mel/F0/Energy cache sequentially per Parquet shard so training never thrashes host RAM."""if not dataset.cache_dir or not dataset.rows:returnos.makedirs(dataset.cache_dir, exist_ok=True)by_shard: Dict[str, List[Dict[str, Any]]] = defaultdict(list)missing = 0for r in dataset.rows:p = os.path.join(dataset.cache_dir, f"{r['uid']}-{dataset.feature_version}.pt")if not os.path.exists(p):by_shard[r["path"]].append(r)missing += 1if missing == 0:print(f"[Cache Ready] All {len(dataset.rows)} clips already cached in {dataset.cache_dir}/", flush=True)returntasks = [(shard_path, rows, dataset.audio_cfg, dataset.cache_dir, dataset.feature_version)for shard_path, rows in sorted(by_shard.items())]print(f"[Cache Warmup] Extracting {missing} clips sequentially across {len(tasks)} shards ({num_workers} workers)...", flush=True)total_done = total_skip = 0if num_workers <= 1:for idx, t in enumerate(tasks, 1):d, s = _warm_shard_worker(t)total_done += dtotal_skip += sif idx % 5 == 0 or idx == len(tasks):print(f"[Cache Warmup] Shards {idx}/{len(tasks)} | Cached={total_done}/{missing} | Skipped={total_skip}", flush=True)else:with ProcessPoolExecutor(max_workers=num_workers) as ex:for idx, (d, s) in enumerate(ex.map(_warm_shard_worker, tasks), 1):total_done += dtotal_skip += sif idx % 5 == 0 or idx == len(tasks):print(f"[Cache Warmup] Shards {idx}/{len(tasks)} | Cached={total_done}/{missing} | Skipped={total_skip}", flush=True)
18 unmodified lines1920212223242576 unmodified lines10210310410510610718 unmodified linesfrom config import MurliV16Configfrom data.audio_processor import AudioProcessorfrom data.dataset import MurliV16Datasetfrom data.text_cleaner import BilingualTextTokenizer, hindi_word_to_ipafrom export_onnx import export_acoustic_onnxfrom models.flow_matching import AdaLNZeroDiTBlock76 unmodified lines})pq.write_table(table, pq_path)def make_cfg(ckpt_dir):c = MurliV16Config()c.model.text_dim, c.model.text_heads, c.model.text_layers = 32, 2, 118 unmodified lines1920212223242576 unmodified lines10210310410510610710810911011118 unmodified linesfrom config import MurliV16Configfrom data.audio_processor import AudioProcessorfrom data.dataset import MurliV16Dataset, warm_cache_by_shardfrom data.text_cleaner import BilingualTextTokenizer, hindi_word_to_ipafrom export_onnx import export_acoustic_onnxfrom models.flow_matching import AdaLNZeroDiTBlock76 unmodified lines})pq.write_table(table, pq_path)warm_ds = MurliV16Dataset(parquet_paths=[str(pq_path)], cache_dir=str(root / "warm_cache"))warm_cache_by_shard(warm_ds, num_workers=1)self.assertEqual(len(list((root / "warm_cache").glob("*.pt"))), 7)def make_cfg(ckpt_dir):c = MurliV16Config()c.model.text_dim, c.model.text_heads, c.model.text_layers = 32, 2, 1
1234566 unmodified lines13141516171819158 unmodified lines178179180181182183"""Train Murli V1.6 (2026 Hybrid DiT+ConvNeXt, 3 Studio Voices) from scratch or resume."""import argparseimport hashlibimport mathimport os6 unmodified linesfrom torch.utils.data import DataLoaderfrom config import EMOTION_TO_ID, MurliV16Configfrom data.dataset import MurliV16Dataset, _map_emotion, v16_collate_fnfrom data.text_cleaner import BilingualTextTokenizerfrom models.tts_engine import MurliV16Enginefrom models.vocoder import MurliVocoder158 unmodified linesemotions = Counter(_map_emotion(row["emotion"]) for row in train_ds.rows)print("Emotion counts", {name: emotions[idx] for name, idx in EMOTION_TO_ID.items()}, flush=True)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")if device.type == "cuda":torch.set_float32_matmul_precision("high")12345676 unmodified lines14151617181920158 unmodified lines179180181182183184185186187188"""Train Murli V1.6 (2026 Hybrid DiT+ConvNeXt, 3 Studio Voices) from scratch or resume."""import argparseimport gcimport hashlibimport mathimport os6 unmodified linesfrom torch.utils.data import DataLoaderfrom config import EMOTION_TO_ID, MurliV16Configfrom data.dataset import MurliV16Dataset, _map_emotion, v16_collate_fn, warm_cache_by_shardfrom data.text_cleaner import BilingualTextTokenizerfrom models.tts_engine import MurliV16Enginefrom models.vocoder import MurliVocoder158 unmodified linesemotions = Counter(_map_emotion(row["emotion"]) for row in train_ds.rows)print("Emotion counts", {name: emotions[idx] for name, idx in EMOTION_TO_ID.items()}, flush=True)if tc.cache_dir and len(dataset.rows) >= 64:warm_cache_by_shard(dataset, num_workers=max(1, tc.num_workers))gc.collect()device = torch.device("cuda" if torch.cuda.is_available() else "cpu")if device.type == "cuda":torch.set_float32_matmul_precision("high")
RULEBOOK_V1_6.md+1
data/dataset.py+88
tests/test_v16.py+5-1
train.py+6-1