Speed optimization: eliminate ConvNeXt GRN FP32 tensor copy + prefetch_factor=4 + float32_matmul_precision=high
Browse filesFiles changed (8)
44 unmodified lines45464744 unmodified lines- **2026-12-01 (G2P & Model):** Fixed medial schwa rule in `data/text_cleaner.py`, built `FrameProsodyRefiner` + `HybridDiTCFMVectorField` (`37.75M` acoustic params with 4 RoPE `AdaLNZeroDiTBlock` attention layers).- **2026-12-01 (Data & Exporter):** Added 3-speaker mapping (`0=syspin_male_01`, `1=kalita_rasa_male_01`, `2=iisc_f_hindi_female_spk001`), duration bucketing, multi-speaker test WAV uploader, and opset-17 Android ONNX exporter (`frontend=51.99 MiB`, `cfm_step=82.11 MiB`).- **2026-12-01 (Verify & Release):** `python -m unittest discover -s tests -p "test_*.py" -v` → `Ran 3 tests in 52.324s — OK`. Ready for `108.8+h` training on `ViuAI/Murli-V1.6-Code`.44 unmodified lines4546474844 unmodified lines- **2026-12-01 (G2P & Model):** Fixed medial schwa rule in `data/text_cleaner.py`, built `FrameProsodyRefiner` + `HybridDiTCFMVectorField` (`37.75M` acoustic params with 4 RoPE `AdaLNZeroDiTBlock` attention layers).- **2026-12-01 (Data & Exporter):** Added 3-speaker mapping (`0=syspin_male_01`, `1=kalita_rasa_male_01`, `2=iisc_f_hindi_female_spk001`), duration bucketing, multi-speaker test WAV uploader, and opset-17 Android ONNX exporter (`frontend=51.99 MiB`, `cfm_step=82.11 MiB`).- **2026-12-01 (Verify & Release):** `python -m unittest discover -s tests -p "test_*.py" -v` → `Ran 3 tests in 52.324s — OK`. Ready for `108.8+h` training on `ViuAI/Murli-V1.6-Code`.- **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`.
12345126 unmodified lines1321331341351361371388 unmodified lines147148149150151152"""Murli V2.0 Audio, Log-Mel Spectrogram, Pitch (F0), and Energy Extractor.Matches 24kHz / 100-bin HTK Mel specification cleanly with NaN guards and multi-container byte decoding."""126 unmodified linesmel = torch.matmul(self.mel_fb.to(wav.device), mag).clamp(min=self.cfg.mel_min_clip).log()t_frames = mel.shape[-1]energy = torch.log(mag.pow(2).mean(dim=0).sqrt().clamp(min=1e-5))# Lightweight frame-wise autocorrelation pitch (F0) estimatorframes = wav_padded.unfold(0, self.cfg.win_length, self.cfg.hop_length)[:t_frames]8 unmodified linesbest_val, best_idx = ac_norm.max(dim=-1)lags = best_idx.float() + min_laghz = torch.where(best_val > 0.35, self.cfg.sample_rate / lags, torch.zeros_like(lags))log_f0 = torch.where(hz > 0, torch.log(hz.clamp(min=1.0)) - math.log(150.0), torch.zeros_like(hz))return mel, log_f0, energy12345126 unmodified lines1321331341351361371381391408 unmodified lines149150151152153154155"""Murli V1.6 Audio, Log-Mel Spectrogram, Pitch (F0), and Energy Extractor.Matches 24kHz / 100-bin HTK Mel specification cleanly with NaN guards and multi-container byte decoding."""126 unmodified linesmel = torch.matmul(self.mel_fb.to(wav.device), mag).clamp(min=self.cfg.mel_min_clip).log()t_frames = mel.shape[-1]raw_energy = torch.log(mag.pow(2).mean(dim=0).sqrt().clamp(min=1e-5))# Center & scale log-RMS energy to match normalized mel/F0 scale (~[-2.5, +1.5])energy = (raw_energy + 5.0) / 2.5# Lightweight frame-wise autocorrelation pitch (F0) estimatorframes = wav_padded.unfold(0, self.cfg.win_length, self.cfg.hop_length)[:t_frames]8 unmodified linesbest_val, best_idx = ac_norm.max(dim=-1)lags = best_idx.float() + min_laghz = torch.where(best_val > 0.35, self.cfg.sample_rate / lags, torch.zeros_like(lags))# Reference at 40 Hz (< f0_min=50 Hz) so all voiced frames remain >= 0.223 and never collide with unvoiced 0.0log_f0 = torch.where(hz > 0, torch.log(hz.clamp(min=1.0)) - math.log(40.0), torch.zeros_like(hz))return mel, log_f0, energy
216 unmodified lines217218219220221222223216 unmodified linesdef _load_features(self, row: Dict[str, Any]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:uid = row["uid"]cache_path = os.path.join(self.cache_dir, f"{uid}-{self.feature_version}.pt") if self.cache_dir else Noneif cache_path and os.path.exists(cache_path):cached = torch.load(cache_path, map_location="cpu", weights_only=True)return cached["tokens"], cached["mel"], cached["f0"], cached["energy"]216 unmodified lines217218219220221222223216 unmodified linesdef _load_features(self, row: Dict[str, Any]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:uid = row["uid"]cache_path = os.path.join(self.cache_dir, uid[:2], f"{uid}-{self.feature_version}.pt") if self.cache_dir else Noneif cache_path and os.path.exists(cache_path):cached = torch.load(cache_path, map_location="cpu", weights_only=True)return cached["tokens"], cached["mel"], cached["f0"], cached["energy"]
33 unmodified lines34353637383940414243444533 unmodified linesvalue = value.replace(",", "").replace(" ", "").strip()percent = value.endswith("%")value = value.rstrip("%").strip()words = []if value[0] in "+-−":positive = value[0] == "+"words.append(("प्लस" if positive else "माइनस") if language == "hi" else ("plus" if positive else "minus"))value = value[1:]integer, dot, fraction = value.partition(".")if len(integer) > 15 or (len(integer) > 1 and integer.startswith("0")):words.extend(digits[int(c)] for c in integer)else:33 unmodified lines34353637383940414243444546474833 unmodified linesvalue = value.replace(",", "").replace(" ", "").strip()percent = value.endswith("%")value = value.rstrip("%").strip()if not value:return []words = []if value[0] in "+-−":positive = value[0] == "+"words.append(("प्लस" if positive else "माइनस") if language == "hi" else ("plus" if positive else "minus"))value = value[1:]integer, dot, fraction = value.partition(".")integer = integer or "0"if len(integer) > 15 or (len(integer) > 1 and integer.startswith("0")):words.extend(digits[int(c)] for c in integer)else:
12345111 unmodified lines11711811912012112272 unmodified lines19519619719819920020120220320420520648 unmodified lines25525625725825926026126226326426526626714 unmodified lines28228328428528628715 unmodified lines30330430530630730830931031131231331431531631731831932032132232332432522 unmodified lines348349350351352353354355356357358359360361362363364365366367368369370"""Murli V2.0 — 2026 Bilingual Hindi + English / Hinglish G2P & Unified IPA Tokenizer.Supports:- Pure Devanagari Hindi (`<hi>`): schwa rules, contextual Anusvara, Chandrabindu, ड़/ढ़ retroflexes111 unmodified lines"two": ["t", "uː"], "one": ["w", "ʌ", "n"], "three": ["θ", "r", "iː"],"four": ["f", "ɔː", "r"], "five": ["f", "aɪ", "v"], "six": ["s", "ɪ", "k", "s"],"seven": ["s", "ɛ", "v", "ə", "n"], "eight": ["eɪ", "t"], "nine": ["n", "aɪ", "n"], "zero": ["z", "ɪə", "r", "oʊ"],"don't": ["d", "oʊ", "n", "t"], "can't": ["k", "æ", "n", "t"], "won't": ["w", "oʊ", "n", "t"],"it's": ["ɪ", "t", "s"], "i'm": ["aɪ", "m"], "you're": ["j", "ʊ", "r"], "that's": ["ð", "æ", "t", "s"],"didn't": ["d", "ɪ", "d", "ə", "n", "t"], "isn't": ["ɪ", "z", "ə", "n", "t"],72 unmodified linesreturn "AH0" if arpabet_tok == "AH0" else re.sub(r"[012]$", "", arpabet_tok)def _split_devanagari_units(word: str) -> List[str]:chars = list(word)units: List[str] = []i = 0while i < len(chars):if i + 1 < len(chars) and chars[i + 1] == "\u093c":units.append(chars[i] + chars[i + 1])i += 2else:48 unmodified lineshas_more = any(units[k] in HI_CONSONANTS or units[k] in HI_INDEP_VOWELS for k in range(i + 1, n))has_nasal = nxt in ("ं", "ँ")prev_is_vowel = len(out) > len(cons) and out[-len(cons) - 1] in _IPA_VOWELSmedial_drop = (not has_nasaland prev_is_voweland nxt in HI_CONSONANTSand i + 2 < nand units[i + 2] in HI_MATRAS)if (has_more or has_nasal or len(out) <= len(cons)) and not medial_drop:out.append("ə")if has_nasal:14 unmodified linesreturn [tok for tok in out if tok in TOKEN_TO_ID]def roman_hindi_to_ipa(word: str) -> List[str]:"""Deterministic Romanized Hindi -> Unified IPA mapper."""w = ROMAN_HINDI_VARIANTS.get(word.lower(), word.lower())15 unmodified lines"p": ["p"], "q": ["q"], "r": ["ɾ"], "s": ["s"], "t": ["t̪"],"u": ["ʊ"], "v": ["ʋ"], "w": ["ʋ"], "x": ["k", "s"], "y": ["j"], "z": ["z"],}out: List[str] = []i = 0while i < len(w):matched = Falsefor pat, ipa in digraphs:if w.startswith(pat, i):out.extend(ipa)i += len(pat)matched = Truebreakif not matched:if i == len(w) - 1 and w[i] == "a":out.append("aː")else:out.extend(singles.get(w[i], []))i += 1return [tok for tok in out if tok in TOKEN_TO_ID]def _english_rules_to_ipa(word: str) -> List[str]:22 unmodified linesif len(w) > 3 and w.endswith("e") and not w.endswith(("ee", "le")):w = w[:-1]out: List[str] = []i = 0while i < len(w):matched = Falsefor pat, ipa in digraphs:if w.startswith(pat, i):out.extend(ipa)i += len(pat)matched = Truebreakif not matched:if i == len(w) - 1 and w[i] == "a":out.append("aː")else:out.extend(singles.get(w[i], []))i += 1return [tok for tok in out if tok in TOKEN_TO_ID]class BilingualTextTokenizer:12345111 unmodified lines11711811912012112212312412512612712812913013113213313413513613772 unmodified lines21021121221321421521621721821922022122222322422522622748 unmodified lines27627727827928028128228328428528628728828929029129229329429529614 unmodified lines31131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135215 unmodified lines36836937037137237337422 unmodified lines397398399400401402403"""Murli V1.6 — Bilingual Hindi + English / Hinglish G2P & Unified IPA Tokenizer.Supports:- Pure Devanagari Hindi (`<hi>`): schwa rules, contextual Anusvara, Chandrabindu, ड़/ढ़ retroflexes111 unmodified lines"two": ["t", "uː"], "one": ["w", "ʌ", "n"], "three": ["θ", "r", "iː"],"four": ["f", "ɔː", "r"], "five": ["f", "aɪ", "v"], "six": ["s", "ɪ", "k", "s"],"seven": ["s", "ɛ", "v", "ə", "n"], "eight": ["eɪ", "t"], "nine": ["n", "aɪ", "n"], "zero": ["z", "ɪə", "r", "oʊ"],"ten": ["t", "ɛ", "n"], "eleven": ["ɪ", "l", "ɛ", "v", "ə", "n"], "twelve": ["t", "w", "ɛ", "l", "v"],"thirteen": ["θ", "ɜː", "r", "t", "iː", "n"], "fourteen": ["f", "ɔː", "r", "t", "iː", "n"],"fifteen": ["f", "ɪ", "f", "t", "iː", "n"], "sixteen": ["s", "ɪ", "k", "s", "t", "iː", "n"],"seventeen": ["s", "ɛ", "v", "ə", "n", "t", "iː", "n"], "eighteen": ["eɪ", "t", "iː", "n"],"nineteen": ["n", "aɪ", "n", "t", "iː", "n"], "twenty": ["t", "w", "ɛ", "n", "t", "iː"],"thirty": ["θ", "ɜː", "r", "t", "iː"], "forty": ["f", "ɔː", "r", "t", "iː"],"fifty": ["f", "ɪ", "f", "t", "iː"], "sixty": ["s", "ɪ", "k", "s", "t", "iː"],"seventy": ["s", "ɛ", "v", "ə", "n", "t", "iː"], "eighty": ["eɪ", "t", "iː"],"ninety": ["n", "aɪ", "n", "t", "iː"], "hundred": ["h", "ʌ", "n", "d", "r", "ə", "d"],"thousand": ["θ", "aʊ", "z", "ə", "n", "d"], "million": ["m", "ɪ", "l", "j", "ə", "n"],"billion": ["b", "ɪ", "l", "j", "ə", "n"], "trillion": ["t", "r", "ɪ", "l", "j", "ə", "n"],"percent": ["p", "ə", "r", "s", "ɛ", "n", "t"], "point": ["p", "ɔɪ", "n", "t"],"minus": ["m", "aɪ", "n", "ə", "s"], "plus": ["p", "l", "ʌ", "s"],"hours": ["aʊ", "ə", "r", "z"], "days": ["d", "eɪ", "z"], "years": ["j", "ɪə", "r", "z"],"minutes": ["m", "ɪ", "n", "ɪ", "t", "s"], "seconds": ["s", "ɛ", "k", "ə", "n", "d", "s"],"don't": ["d", "oʊ", "n", "t"], "can't": ["k", "æ", "n", "t"], "won't": ["w", "oʊ", "n", "t"],"it's": ["ɪ", "t", "s"], "i'm": ["aɪ", "m"], "you're": ["j", "ʊ", "r"], "that's": ["ð", "æ", "t", "s"],"didn't": ["d", "ɪ", "d", "ə", "n", "t"], "isn't": ["ɪ", "z", "ə", "n", "t"],72 unmodified linesreturn "AH0" if arpabet_tok == "AH0" else re.sub(r"[012]$", "", arpabet_tok)_DEVANAGARI_CONJUNCTS = {"क्ष", "त्र", "ज्ञ", "श्र"}def _split_devanagari_units(word: str) -> List[str]:chars = list(word)units: List[str] = []i = 0while i < len(chars):if i + 2 < len(chars) and (chars[i] + chars[i + 1] + chars[i + 2]) in _DEVANAGARI_CONJUNCTS:units.append(chars[i] + chars[i + 1] + chars[i + 2])i += 3elif i + 1 < len(chars) and chars[i + 1] == "\u093c":units.append(chars[i] + chars[i + 1])i += 2else:48 unmodified lineshas_more = any(units[k] in HI_CONSONANTS or units[k] in HI_INDEP_VOWELS for k in range(i + 1, n))has_nasal = nxt in ("ं", "ँ")prev_is_vowel = len(out) > len(cons) and out[-len(cons) - 1] in _IPA_VOWELSafter_halant_cluster = i >= 2 and units[i - 2] == "्"cvcvc_4_drop = (n == 4and i == 1and not has_nasaland all(u in HI_CONSONANTS or u in HI_INDEP_VOWELS for u in units))medial_drop = (not has_nasaland not after_halant_clusterand prev_is_voweland nxt in HI_CONSONANTSand i + 2 < nand units[i + 2] in HI_MATRAS) or cvcvc_4_dropif (has_more or has_nasal or len(out) <= len(cons)) and not medial_drop:out.append("ə")if has_nasal:14 unmodified linesreturn [tok for tok in out if tok in TOKEN_TO_ID]def _scan_graphemes(w: str,digraphs: List[Tuple[str, List[str]]],singles: Dict[str, List[str]],english_rules: bool = False,) -> List[str]:out: List[str] = []i = 0while i < len(w):matched = Falsefor pat, ipa in digraphs:if w.startswith(pat, i):out.extend(ipa)i += len(pat)matched = Truebreakif not matched:if english_rules and i + 1 < len(w) and w[i] == w[i + 1] and w[i] in singles and w[i] not in "aeiou":# Collapse English geminate consonants (e.g., hello, million) to a single phonemeout.extend(singles[w[i]])i += 2elif english_rules and w[i] == "c" and i + 1 < len(w) and w[i + 1] in ("e", "i", "y"):out.append("s")i += 1elif english_rules and i == len(w) - 1 and w[i] == "y" and len(w) > 2:out.append("iː")i += 1elif i == len(w) - 1 and w[i] == "a":out.append("aː")i += 1else:out.extend(singles.get(w[i], []))i += 1return [tok for tok in out if tok in TOKEN_TO_ID]def roman_hindi_to_ipa(word: str) -> List[str]:"""Deterministic Romanized Hindi -> Unified IPA mapper."""w = ROMAN_HINDI_VARIANTS.get(word.lower(), word.lower())15 unmodified lines"p": ["p"], "q": ["q"], "r": ["ɾ"], "s": ["s"], "t": ["t̪"],"u": ["ʊ"], "v": ["ʋ"], "w": ["ʋ"], "x": ["k", "s"], "y": ["j"], "z": ["z"],}return _scan_graphemes(w, digraphs, singles, english_rules=False)def _english_rules_to_ipa(word: str) -> List[str]:22 unmodified linesif len(w) > 3 and w.endswith("e") and not w.endswith(("ee", "le")):w = w[:-1]return _scan_graphemes(w, digraphs, singles, english_rules=True)class BilingualTextTokenizer:
159 unmodified lines160161162163164165166159 unmodified linesh = F.gelu(self.pw1(h))if mask is not None:h = h * mask.unsqueeze(-1).to(h.dtype)gx = torch.norm(h.float(), p=2, dim=1, keepdim=True).to(h.dtype)nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)h = self.grn_gamma * (h * nx) + self.grn_beta + hout = residual + self.pw2(h)159 unmodified lines160161162163164165166159 unmodified linesh = F.gelu(self.pw1(h))if mask is not None:h = h * mask.unsqueeze(-1).to(h.dtype)gx = h.pow(2).sum(dim=1, keepdim=True, dtype=torch.float32).add(1e-12).sqrt().to(h.dtype)nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)h = self.grn_gamma * (h * nx) + self.grn_beta + hout = residual + self.pw2(h)
175 unmodified lines17617717817918018114 unmodified lines196197198199200201175 unmodified linesdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")if device.type == "cuda":torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Truetorch.backends.cudnn.benchmark = True14 unmodified linespersistent_workers=(tc.num_workers > 0),collate_fn=v16_collate_fn,)val_loader = DataLoader(val_ds, **loader_opts)signature = hashlib.sha256()175 unmodified lines17617717817918018118214 unmodified lines197198199200201202203204175 unmodified linesdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")if device.type == "cuda":torch.set_float32_matmul_precision("high")torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Truetorch.backends.cudnn.benchmark = True14 unmodified linespersistent_workers=(tc.num_workers > 0),collate_fn=v16_collate_fn,)if tc.num_workers > 0:loader_opts["prefetch_factor"] = 4val_loader = DataLoader(val_ds, **loader_opts)signature = hashlib.sha256()
7 unmodified lines89101112137 unmodified linesdef atomic_save(payload, destination):destination = Path(destination)with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as stream:temporary = stream.nametry:7 unmodified lines8910111213147 unmodified linesdef atomic_save(payload, destination):destination = Path(destination)destination.parent.mkdir(parents=True, exist_ok=True)with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as stream:temporary = stream.nametry:
RULEBOOK_V1_6.md+1
data/audio_processor.py+6-3
data/dataset.py+1-1
data/numbers_spoken.py+3
data/text_cleaner.py+70-37
models/layers.py+1-1
train.py+3
utils/checkpoint.py+1