| """ | |
| BilinearLatentDecoder for grn_att_only: Q@K^T bilinear decoder. | |
| Replaces LatentEmbedder/LatentDecoder from grn_ccfm. | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| class BilinearLatentDecoder(nn.Module): | |
| """Q@K^T bilinear decoder: (B, G, d_model) -> (B, G, G)""" | |
| def __init__(self, d_model: int = 128, head_dim: int = 128): | |
| super().__init__() | |
| self.q_proj = nn.Linear(d_model, head_dim) | |
| self.k_proj = nn.Linear(d_model, head_dim) | |
| self.scale = head_dim ** -0.5 | |
| self.out_gate = nn.Parameter(torch.tensor([0.1])) # small init: allow gradient flow | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| """x: (B, G, d_model) -> (B, G, G)""" | |
| Q = self.q_proj(x) # (B, G, head_dim) | |
| K = self.k_proj(x) # (B, G, head_dim) | |
| return torch.bmm(Q, K.transpose(1, 2)) * self.scale * self.out_gate | |