""" Text Encoder with Rotary Positional Embeddings (RoPE) and Transformer Blocks. Total parameter budget: ~2.7M params. """ import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional class RotaryEmbedding(nn.Module): """Rotary Position Embedding (RoPE) for stable long-sequence prosody.""" def __init__(self, dim: int, max_seq_len: int = 4096): super().__init__() inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) self.max_seq_len = max_seq_len def forward(self, seq_len: int, device: torch.device): t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) freqs = torch.outer(t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1) return emb.cos(), emb.sin() def rotate_half(x: torch.Tensor) -> torch.Tensor: x1, x2 = x.chunk(2, dim=-1) return torch.cat((-x2, x1), dim=-1) def apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor): # q, k: (B, H, T, D) cos = cos.unsqueeze(0).unsqueeze(0).to(q.dtype) # (1, 1, T, D) sin = sin.unsqueeze(0).unsqueeze(0).to(q.dtype) # (1, 1, T, D) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed class MultiHeadAttentionRoPE(nn.Module): def __init__(self, dim: int, heads: int = 4, dropout: float = 0.1): super().__init__() if dim % heads != 0: raise ValueError(f"dim ({dim}) must be divisible by heads ({heads})") self.dim = dim self.heads = heads self.head_dim = dim // heads self.scale = self.head_dim ** -0.5 self.q_proj = nn.Linear(dim, dim) self.k_proj = nn.Linear(dim, dim) self.v_proj = nn.Linear(dim, dim) self.out_proj = nn.Linear(dim, dim) self.dropout = nn.Dropout(dropout) self.rope = RotaryEmbedding(self.head_dim) def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: # x: (B, T, C) B, T, C = x.shape q = self.q_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2) k = self.k_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2) v = self.v_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2) cos, sin = self.rope(T, x.device) q, k = apply_rope(q, k, cos, sin) scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale if mask is not None: # mask: (B, 1, 1, T) or (B, 1, T, T) scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min) attn = F.softmax(scores, dim=-1) attn = torch.nan_to_num(attn, nan=0.0) attn = self.dropout(attn) out = torch.matmul(attn, v) # (B, H, T, D) out = out.transpose(1, 2).contiguous().view(B, T, C) return self.out_proj(out) class TransformerBlock(nn.Module): def __init__(self, dim: int, heads: int = 4, ffn_dim: int = 768, dropout: float = 0.1): super().__init__() self.norm1 = nn.LayerNorm(dim) self.attn = MultiHeadAttentionRoPE(dim, heads=heads, dropout=dropout) self.norm2 = nn.LayerNorm(dim) self.ffn = nn.Sequential( nn.Linear(dim, ffn_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(ffn_dim, dim), nn.Dropout(dropout), ) def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: x = x + self.attn(self.norm1(x), mask=mask) x = x + self.ffn(self.norm2(x)) return x class TextEncoder(nn.Module): """ Transformer Text Encoder with RoPE. Encodes text token IDs into contextual hidden representations. """ def __init__( self, vocab_size: int = 512, dim: int = 256, layers: int = 4, heads: int = 4, ffn_dim: int = 768, dropout: float = 0.1, pad_token_id: int = 0, ): super().__init__() self.pad_token_id = pad_token_id self.embedding = nn.Embedding(vocab_size, dim, padding_idx=pad_token_id) self.blocks = nn.ModuleList([ TransformerBlock(dim=dim, heads=heads, ffn_dim=ffn_dim, dropout=dropout) for _ in range(layers) ]) self.final_norm = nn.LayerNorm(dim) def forward(self, text_ids: torch.Tensor, text_lengths: Optional[torch.Tensor] = None) -> torch.Tensor: # text_ids: (B, T_text) B, T = text_ids.shape x = self.embedding(text_ids) token_mask = None attn_mask = None if text_lengths is not None: token_mask = torch.arange(T, device=text_ids.device).unsqueeze(0) < text_lengths.unsqueeze(1) attn_mask = token_mask.unsqueeze(1).unsqueeze(2) # (B, 1, 1, T) for block in self.blocks: x = block(x, mask=attn_mask) x = self.final_norm(x) if token_mask is not None: x = x.masked_fill(~token_mask.unsqueeze(-1), 0.0) return x # (B, T_text, dim)