sft-6k / thinker /emca.py
VOLBEM's picture
Add files using upload-large-folder tool
ebcf321 verified
Raw
History Blame Contribute Delete
7.5 kB
"""
Enhanced Multi-scale Cross-Attention (EMCA) in the Poincaré ball.
================================================================================
V1 (2B): radii_per_scale and p_fuse are no longer .detach()'d. Crucially, the
radii used for L_radius are computed from `attended` (post Einstein-midpoint
cross-attention), NOT from `ball_features` (the bare exp_map output).
WHY:
poincare_radius(exp_0^c(h), c) = (2/√c) · artanh(√c · tanh(√c‖h‖)/√c)
= 2‖h‖ — c CANCELS OUT.
poincare_radius(attended, c) has no such cancellation because `attended`
is the output of einstein_midpoint, whose Lorentz factor γ = (1-c‖k‖²)^(-1/2)
is genuinely c-dependent and not invertible by the outer artanh.
So under V1:
- L_radius has real gradient flow (no .detach())
- L_radius's gradient w.r.t. c_work is non-zero (radii truly depend on c)
- L_radius's gradient also reaches HGA's (s, b, c^(l)) via the
multi_scale_features → attended path
================================================================================
"""
import logging
from typing import Dict, List, Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from .hyperbolic_ops import (
exp_map_zero, log_map_zero, clamp_norm,
hyperbolic_distance, einstein_midpoint,
poincare_radius, LearnableCurvature,
)
logger = logging.getLogger(__name__)
class RMSNorm(nn.Module):
"""Root Mean Square Normalization (preserves direction, controls magnitude)."""
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):
x_f = x.float()
rms = torch.sqrt(x_f.pow(2).mean(-1, keepdim=True) + self.eps)
return ((x_f / rms) * self.weight.float()).to(x.dtype)
class EMCA(nn.Module):
"""Enhanced Multi-scale Cross-Attention.
Forward pipeline:
1. Per-scale exp_map into working Poincaré ball (c_work).
2. Pairwise hyperbolic distance → softmax → cross-scale attention scores.
3. Einstein midpoint per query scale → `attended` (B, T, S, d) in ball.
↑ This is where c truly affects values (via Lorentz factor γ).
4. Final aggregation across scales (Einstein midpoint, scale_weights) → p_fuse.
5. log_map → projector → RMSNorm → audio_tokens (Euclidean).
Outputs:
audio_tokens: (B, T, llm_dim) Euclidean — feeds LLM.
p_fuse: (B, T, d) in ball — available for future hyperbolic losses.
radii_per_scale: (S,) — mean poincare_radius(attended[..., i, :], c_work).
Gradient flows through this; L_radius uses it.
"""
def __init__(self,
encoder_dim: int = 1280,
llm_dim: int = 3584,
num_scales: int = 8,
c_work_init: float = 0.5,
c_work_min: float = 0.01,
c_work_max: float = 4.0,
projector_hidden: int = 4096):
super().__init__()
self.encoder_dim = encoder_dim
self.num_scales = num_scales
# Working curvature for the EMCA ball (separate from HGA's per-layer c^(l))
self.c_work = LearnableCurvature(
init_value=c_work_init, c_min=c_work_min, c_max=c_work_max
)
# Learnable temperature for attention
self.log_temperature = nn.Parameter(torch.tensor(1.0).log())
# Learnable scale weights for final aggregation
self.scale_logits = nn.Parameter(torch.zeros(num_scales))
# Output projection: encoder_dim → llm_dim
self.projector = nn.Sequential(
nn.Linear(encoder_dim, projector_hidden),
nn.GELU(),
nn.Linear(projector_hidden, llm_dim),
)
self.output_norm = RMSNorm(llm_dim)
@property
def temperature(self):
return self.log_temperature.float().exp()
def forward(self, multi_scale_features: List[torch.Tensor]
) -> Dict[str, Any]:
"""
Args:
multi_scale_features: list of S tensors, each (B, T, d).
S = num_scales, features from different Whisper layers
(already pooled to target frame rate by ThinkerModel).
Returns:
dict containing audio_tokens (for LLM), p_fuse (for future use),
radii_per_scale (for L_radius, WITH gradient), and diagnostics.
"""
S = len(multi_scale_features)
assert S == self.num_scales, f"Expected {self.num_scales} scales, got {S}"
B, T, d = multi_scale_features[0].shape
c = self.c_work().float()
# 1. Map each scale into the working Poincaré ball
ball_features = []
for i in range(S):
h = multi_scale_features[i].float()
p = exp_map_zero(h, c) # (B, T, d) in ball
ball_features.append(p)
# Stack: (B, T, S, d)
ball_stack = torch.stack(ball_features, dim=2)
# 2. Pairwise hyperbolic distances for cross-attention
q = ball_stack.unsqueeze(3).expand(B, T, S, S, d).reshape(-1, d)
k = ball_stack.unsqueeze(2).expand(B, T, S, S, d).reshape(-1, d)
dists = hyperbolic_distance(q, k, c).reshape(B, T, S, S)
# Attention scores: -distance / temperature, mask diagonal
scores = -dists / self.temperature
diag_mask = torch.eye(S, device=scores.device, dtype=torch.bool)
scores = scores.masked_fill(
diag_mask.unsqueeze(0).unsqueeze(0), float('-inf')
)
attn_weights = F.softmax(scores, dim=-1) # (B, T, S, S)
# 3. Einstein midpoint cross-attention per query scale
points_exp = ball_stack.unsqueeze(2).expand(B, T, S, S, d)
attended = einstein_midpoint(points_exp, attn_weights, c) # (B, T, S, d)
# 3b. Radii from `attended` — c truly affects values here (no cancellation)
# Note: NO .detach() — radii carry gradient back to c_work, scale weights,
# and through multi_scale_features to HGA parameters.
radii_per_scale = []
for i in range(S):
radii_per_scale.append(
poincare_radius(attended[:, :, i, :], c).mean()
)
radii_per_scale = torch.stack(radii_per_scale) # (S,)
# 4. Final aggregation across scales
scale_w = F.softmax(self.scale_logits.float(), dim=0) # (S,)
scale_w_exp = scale_w.unsqueeze(0).unsqueeze(0).expand(B, T, -1)
p_fuse = einstein_midpoint(attended, scale_w_exp, c) # (B, T, d)
# 5. Log map back to Euclidean, project to LLM dim
z = log_map_zero(p_fuse, c) # (B, T, d)
proj_dtype = next(self.projector.parameters()).dtype
audio_tokens = self.projector(z.to(proj_dtype))
audio_tokens = self.output_norm(audio_tokens)
return {
"audio_tokens": audio_tokens,
# p_fuse kept in graph (no detach) — available for future losses.
"p_fuse": p_fuse,
# radii_per_scale carries gradient → real L_radius signal.
"radii_per_scale": radii_per_scale,
# Below are diagnostics only; .detach() is fine here.
"c_work": c.detach(),
"scale_weights": scale_w.detach(),
"scale_entropy": -(scale_w * (scale_w + 1e-8).log()).sum().detach(),
"attention_temp": self.temperature.detach(),
}