File size: 2,168 Bytes
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Murli V2.0 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)