File size: 6,994 Bytes
a1cd84e | 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """
Shared 2026 Transformer & ConvNeXt-V2 Building Blocks for Murli V2.0.
Includes RMSNorm, SwiGLU MLP, Rotary Positional Embeddings (RoPE), SDPA Attention,
and Mask-Aware ConvNeXt-V2 1D blocks.
"""
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization (FP32-safe)."""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
orig_dtype = x.dtype
x_fp32 = x.float()
norm = torch.rsqrt(x_fp32.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return (x_fp32 * norm).to(orig_dtype) * self.weight
class SwiGLU(nn.Module):
"""SwiGLU Feed-Forward Network."""
def __init__(self, dim: int, ff_mult: float = 2.667, dropout: float = 0.0):
super().__init__()
hidden = int(round(dim * ff_mult / 64.0) * 64)
self.w_gate_up = nn.Linear(dim, hidden * 2, bias=False)
self.w_down = nn.Linear(hidden, dim, bias=False)
self.drop = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
gate, up = self.w_gate_up(x).chunk(2, dim=-1)
return self.w_down(self.drop(F.silu(gate) * up))
class RotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE) computed dynamically up to any sequence length."""
def __init__(self, head_dim: int, base: float = 10000.0):
super().__init__()
if head_dim % 2 != 0:
raise ValueError(f"RoPE head_dim must be even, got {head_dim}")
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype):
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().to(dtype), emb.sin().to(dtype)
def apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
"""Apply rotary position embeddings to query and key tensors [B, H, T, D]."""
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
cos_b = cos.unsqueeze(0).unsqueeze(0)
sin_b = sin.unsqueeze(0).unsqueeze(0)
return (q * cos_b) + (_rotate_half(q) * sin_b), (k * cos_b) + (_rotate_half(k) * sin_b)
class MultiHeadSDPA(nn.Module):
"""Self-Attention or Cross-Attention backed by PyTorch SDPA (FlashAttention-2 ready)."""
def __init__(self, dim: int, num_heads: int, kv_dim: Optional[int] = None, dropout: float = 0.0, use_rope: bool = True):
super().__init__()
if dim % num_heads != 0:
raise ValueError(f"dim {dim} must be divisible by num_heads {num_heads}")
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.dropout = dropout
self.use_rope = use_rope and (kv_dim is None)
src_dim = kv_dim if kv_dim is not None else dim
self.q_proj = nn.Linear(dim, dim, bias=False)
self.k_proj = nn.Linear(src_dim, dim, bias=False)
self.v_proj = nn.Linear(src_dim, dim, bias=False)
self.out_proj = nn.Linear(dim, dim, bias=False)
self.rope = RotaryEmbedding(self.head_dim) if self.use_rope else None
def forward(
self,
x: torch.Tensor,
kv: Optional[torch.Tensor] = None,
key_padding_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
bsz, q_len, _ = x.shape
src = kv if kv is not None else x
k_len = src.shape[1]
q = self.q_proj(x).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(src).view(bsz, k_len, self.num_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(src).view(bsz, k_len, self.num_heads, self.head_dim).transpose(1, 2)
if self.rope is not None:
cos, sin = self.rope(q_len, x.device, q.dtype)
q, k = apply_rope(q, k, cos, sin)
attn_mask = None
if key_padding_mask is not None:
# key_padding_mask: [B, K_len] True = valid token
attn_mask = key_padding_mask[:, None, None, :].to(torch.bool)
drop_p = self.dropout if self.training else 0.0
out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=drop_p, is_causal=False)
out = out.transpose(1, 2).contiguous().view(bsz, q_len, -1)
return self.out_proj(out)
class SinusoidalTimestepEmbed(nn.Module):
"""Continuous diffusion flow timestep embedding t in [0, 1]."""
def __init__(self, dim: int):
super().__init__()
self.half_dim = dim // 2
self.mlp = nn.Sequential(
nn.Linear(dim, dim * 2),
nn.SiLU(),
nn.Linear(dim * 2, dim),
)
def forward(self, t: torch.Tensor) -> torch.Tensor:
if t.dim() == 0:
t = t.unsqueeze(0)
freqs = math.log(10000.0) / max(self.half_dim - 1, 1)
angles = t.float().unsqueeze(-1) * torch.exp(torch.arange(self.half_dim, device=t.device).float() * -freqs)
emb = torch.cat((angles.sin(), angles.cos()), dim=-1)
return self.mlp(emb.to(self.mlp[0].weight.dtype))
class ConvNeXt1DBlock(nn.Module):
"""Mask-aware 1D ConvNeXt-V2 block with Global Response Normalization."""
def __init__(self, dim: int, kernel_size: int = 7, mult: int = 3):
super().__init__()
self.dwconv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)
self.norm = RMSNorm(dim)
self.pw1 = nn.Linear(dim, dim * mult)
self.pw2 = nn.Linear(dim * mult, dim)
self.grn_gamma = nn.Parameter(torch.zeros(1, 1, dim * mult))
self.grn_beta = nn.Parameter(torch.zeros(1, 1, dim * mult))
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
# x: [B, T, D], mask: [B, T] bool
residual = x
if mask is not None:
x = x * mask.unsqueeze(-1).to(x.dtype)
h = self.dwconv(x.transpose(1, 2)).transpose(1, 2)
h = self.norm(h)
h = 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 + h
out = residual + self.pw2(h)
if mask is not None:
out = out * mask.unsqueeze(-1).to(out.dtype)
return out
|