Fix fork/OpenMP deadlock in warm_cache_by_shard using spawn (2 workers, 1 thread each) + per-shard progress
Browse filesFiles changed (3)
- RULEBOOK_V1_6.md+1
- data/dataset.py+25-15
- train.py+1-1
48 unmodified lines49505148 unmodified lines- **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.48 unmodified lines4950515248 unmodified lines- **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.- **2026-12-01 (Spawn Warmup Hang Fix):** Fixed Linux `fork()` + PyTorch/OpenMP mutex deadlock & RAM spike inside `warm_cache_by_shard` by switching to `mp.get_context("spawn")` (`max_workers=2`, `torch.set_num_threads(1)`) with per-shard live `as_completed` logging.
3 unmodified lines45678910111213141516287 unmodified lines3043053063073083093103113123133143 unmodified lines31831932032132232332432521 unmodified lines34734834935035135235335435535635713 unmodified lines3713723733743753763773783793803813823833843853863873883893903 unmodified linestranscript-disjoint split, versioned cache invalidation, and real-time download progress."""import hashlibimport jsonimport mathimport osimport warningsfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutorfrom copy import copyfrom dataclasses import asdictfrom pathlib import Path287 unmodified lines}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)3 unmodified linesif 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 = 021 unmodified linesskipped += 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)13 unmodified lines(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)3 unmodified lines456789101112131415161718287 unmodified lines3063073083093103113123133143153163173183193 unmodified lines32332432532632732832933033121 unmodified lines35335435535635735835936036136236336436513 unmodified lines3793803813823833843853863873883893903913923933943953963973983994003 unmodified linestranscript-disjoint split, versioned cache invalidation, and real-time download progress."""import gcimport hashlibimport jsonimport mathimport multiprocessing as mpimport osimport warningsfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutor, as_completedfrom copy import copyfrom dataclasses import asdictfrom pathlib import Path287 unmodified lines}def _warm_shard_worker(task: Tuple[str, List[Dict[str, Any]], AudioConfig, str, str]) -> Tuple[str, int, int]:"""Decode and cache all uncached rows of ONE Parquet shard sequentially (1.0x disk read)."""os.environ.setdefault("OMP_NUM_THREADS", "1")os.environ.setdefault("MKL_NUM_THREADS", "1")import pyarrow as paimport pyarrow.parquet as pqtorch.set_num_threads(1)shard_path, entries, audio_cfg, cache_dir, feature_version = taskproc = AudioProcessor(audio_cfg)tokenizer = BilingualTextTokenizer(use_g2p_en=False)3 unmodified linesif not os.path.exists(cache_path):by_group[r["group"]].append(r)shard_name = os.path.basename(shard_path)if not by_group:return shard_name, 0, 0pf = pq.ParquetFile(shard_path)done = skipped = 021 unmodified linesskipped += 1del colpa.default_memory_pool().release_unused()del pfgc.collect()return shard_name, done, skippeddef warm_cache_by_shard(dataset: MurliV16Dataset, num_workers: int = 2) -> None:"""Pre-build Mel/F0/Energy cache sequentially per Parquet shard using spawn workers (no fork deadlock)."""if not dataset.cache_dir or not dataset.rows:returnos.makedirs(dataset.cache_dir, exist_ok=True)13 unmodified lines(shard_path, rows, dataset.audio_cfg, dataset.cache_dir, dataset.feature_version)for shard_path, rows in sorted(by_shard.items())]workers = min(2, max(1, num_workers))print(f"[Cache Warmup] Extracting {missing} clips across {len(tasks)} shards ({workers} spawn workers)...", flush=True)total_done = total_skip = 0if workers <= 1:for idx, t in enumerate(tasks, 1):name, d, s = _warm_shard_worker(t)total_done += dtotal_skip += sprint(f"[Cache {idx}/{len(tasks)}] {name}: +{d} (skip {s}) | Total {total_done}/{missing}", flush=True)else:ctx = mp.get_context("spawn")with ProcessPoolExecutor(max_workers=workers, mp_context=ctx) as ex:futures = [ex.submit(_warm_shard_worker, t) for t in tasks]for idx, fut in enumerate(as_completed(futures), 1):name, d, s = fut.result()total_done += dtotal_skip += sprint(f"[Cache {idx}/{len(tasks)}] {name}: +{d} (skip {s}) | Total {total_done}/{missing}", flush=True)
179 unmodified lines180181182183184185186179 unmodified linesprint("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")179 unmodified lines180181182183184185186179 unmodified linesprint("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=min(2, max(1, tc.num_workers)))gc.collect()device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
RULEBOOK_V1_6.md+1
data/dataset.py+25-15
train.py+1-1