Download models/text_encoder.py from ViuAI/Murli-V1.6-Code: direct link, hf CLI and curl.
- Browser
- Download file 2.17 kB
-
https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/models/text_encoder.py
- Command line
-
hf download hf://ViuAI/Murli-V1.6-Code/models/text_encoder.py
-
curl -L -o text_encoder.py https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/models/text_encoder.py
2.17 kB
| """ | |
| Murli V1.6 Bilingual Text & Phoneme Encoder. | |
| Combines local ConvNeXt-V2 phonetic boundary blocks with a deep RoPE SwiGLU Transformer. | |
| """ | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| from models.layers import ConvNeXt1DBlock, MultiHeadSDPA, RMSNorm, SwiGLU | |
| class TransformerEncoderBlock(nn.Module): | |
| def __init__(self, dim: int, num_heads: int, ff_mult: float = 2.667, dropout: float = 0.05): | |
| super().__init__() | |
| self.norm1 = RMSNorm(dim) | |
| self.attn = MultiHeadSDPA(dim, num_heads, dropout=dropout, use_rope=True) | |
| self.norm2 = RMSNorm(dim) | |
| self.mlp = SwiGLU(dim, ff_mult=ff_mult, dropout=dropout) | |
| def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: | |
| x = x + self.attn(self.norm1(x), key_padding_mask=mask) | |
| x = x + self.mlp(self.norm2(x)) | |
| if mask is not None: | |
| x = x * mask.unsqueeze(-1).to(x.dtype) | |
| return x | |
| class BilingualTextEncoder(nn.Module): | |
| """Encodes unified Hindi/English IPA token IDs into contextual phonetic hidden states [B, T, D].""" | |
| def __init__( | |
| self, | |
| vocab_size: int = 256, | |
| dim: int = 384, | |
| num_layers: int = 6, | |
| num_heads: int = 6, | |
| ff_mult: float = 2.667, | |
| dropout: float = 0.05, | |
| ): | |
| super().__init__() | |
| self.embed = nn.Embedding(vocab_size, dim, padding_idx=0) | |
| self.local_convs = nn.ModuleList([ConvNeXt1DBlock(dim, kernel_size=5) for _ in range(2)]) | |
| self.blocks = nn.ModuleList([ | |
| TransformerEncoderBlock(dim, num_heads, ff_mult=ff_mult, dropout=dropout) | |
| for _ in range(num_layers) | |
| ]) | |
| self.final_norm = RMSNorm(dim) | |
| def forward(self, token_ids: torch.Tensor, text_mask: Optional[torch.Tensor] = None) -> torch.Tensor: | |
| if text_mask is None: | |
| text_mask = token_ids != 0 | |
| x = self.embed(token_ids) | |
| for conv in self.local_convs: | |
| x = conv(x, mask=text_mask) | |
| for blk in self.blocks: | |
| x = blk(x, mask=text_mask) | |
| x = self.final_norm(x) | |
| return x * text_mask.unsqueeze(-1).to(x.dtype) | |