sft-6k / thinker /encoder.py
VOLBEM's picture
Add files using upload-large-folder tool
ebcf321 verified
Raw
History Blame Contribute Delete
10.6 kB
"""
Whisper encoder with HGA-modulated self-attention.
================================================================================
V1 (2A): HGA now includes a Möbius bias term that breaks exp/log cancellation,
making the curvature c a real, gradient-bearing parameter.
Modulation formula (per Q/K/V projection, per layer):
W_HGA = log_0^c( ( diag(s) ⊗_c exp_0^c(W_ref) ) ⊕_c exp_0^c(b) )
Without b, the chain reduces to s ⊙ W_ref (DoRA-like, c does nothing — this
is the SER paper's formula). With b ≠ 0, the Möbius addition step entangles c
with the norms of q and b in a way that cannot be algebraically cancelled.
Key properties:
- b tiny-random-init (std=1e-4) → init is numerically ≈ s ⊙ W_ref but with
b ≠ 0, so c receives gradient signal from step 0. (Zero-init would freeze
c at a saddle ∂L/∂c = 0.)
- All layers use the same (c_min, c_init, c_max) bounds; layer-aware bucketing
removed because b makes c a real parameter that learns its own per-layer
optimum without artificial floors.
================================================================================
"""
import math
import logging
from typing import List, Dict, Any, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from .hyperbolic_ops import (
exp_map_zero, log_map_zero, mobius_add, clamp_norm,
LearnableCurvature,
)
logger = logging.getLogger(__name__)
class HGALinear(nn.Module):
"""Drop-in replacement for nn.Linear that applies HGA weight modulation
with a Möbius bias term.
Stores a frozen reference weight W_ref. At forward time:
p = exp_0^c(W_ref) # rows → ball
v = log_0^c(p) # = W_ref (id)
q = exp_0^c(diag(s) · v) = exp_0^c(s ⊙ W_ref)# Möbius scale
b_pt = exp_0^c(b) # bias → ball
r = q ⊕_c b_pt # Möbius add — c becomes essential
W_mod = log_0^c(r) # ball → tangent
output = x @ W_mod^T + bias_orig
Trainable: s (d_in,), b (d_in,), c (via curvature_module)
Frozen: W_ref, bias_orig (from pretrained Whisper)
"""
def __init__(self, original_linear: nn.Linear,
s: nn.Parameter, b: nn.Parameter,
curvature_module: nn.Module):
super().__init__()
# Frozen reference weight (rows are the d_out "row vectors" in R^{d_in})
self.register_buffer("W_ref", original_linear.weight.data.clone().float())
# Keep original bias (frozen but used in forward)
if original_linear.bias is not None:
self.register_buffer("bias", original_linear.bias.data.clone())
else:
self.bias = None
# Learnable HGA parameters (shared from the per-layer container)
self.s = s
self.b = b
self.curvature = curvature_module
def forward(self, x: torch.Tensor) -> torch.Tensor:
c = self.curvature().float()
# Step 1: rows of W_ref → Poincaré ball
p = exp_map_zero(self.W_ref, c) # (d_out, d_in)
# Step 2: Möbius diagonal scaling diag(s) ⊗_c p
# = exp_0^c( s ⊙ log_0^c(p) ) = exp_0^c( s ⊙ W_ref )
v = log_map_zero(p, c) # = W_ref (cancellation)
v_scaled = v * self.s.float().unsqueeze(0)
q = exp_map_zero(v_scaled, c) # (d_out, d_in) in ball
# Step 3: Möbius bias addition — broadcasts b across d_out rows
b_pt = exp_map_zero(self.b.float(), c) # (d_in,) in ball
b_pt_b = b_pt.unsqueeze(0).expand_as(q) # (d_out, d_in)
r = mobius_add(q, b_pt_b, c) # (d_out, d_in)
r = clamp_norm(r, c) # numerical safety
# Step 4: log_map back to tangent → modulated weight
W_mod = log_map_zero(r, c) # (d_out, d_in)
with torch.amp.autocast("cuda", enabled=False):
return F.linear(x.float(), W_mod.float(),
self.bias.float() if self.bias is not None else None).to(x.dtype)
class HGAWhisperEncoder(nn.Module):
"""Whisper encoder with HGA-modulated Q/K/V on all 32 layers.
Architecture:
1. Load Whisper encoder, freeze every original parameter.
2. For each layer, create one shared LearnableCurvature c^(l) plus three
pairs of (s, b) — for q_proj, k_proj, v_proj.
3. Replace q_proj/k_proj/v_proj with HGALinear wrappers that compute
the modulated weight on the fly.
4. Register forward hooks to capture multi-scale features for EMCA.
Trainable params per layer:
3 × d_model (s_Q, s_K, s_V) + 3 × d_model (b_Q, b_K, b_V) + 1 (c)
= 6 × d_model + 1
For d_model=1280 → 7,681 per layer × 32 layers ≈ 246K total (HGA only).
"""
output_dim = 1280
output_frame_rate_hz = 50.0
def __init__(self, model_path: str, extract_layers: List[int],
num_encoder_layers: int = 32,
hga_c_init: float = 1.0,
hga_c_min: float = 0.001,
hga_c_max: float = 8.0,
hga_b_init_std: float = 1.0e-4):
super().__init__()
self.extract_layers = sorted(extract_layers)
self.num_encoder_layers = num_encoder_layers
self.hga_c_init = hga_c_init
self.hga_c_min = hga_c_min
self.hga_c_max = hga_c_max
self.hga_b_init_std = hga_b_init_std
# --- Load Whisper encoder ---
from transformers import WhisperModel
whisper = WhisperModel.from_pretrained(model_path)
self.encoder = whisper.encoder
del whisper
# Freeze ALL original encoder parameters
for p in self.encoder.parameters():
p.requires_grad = False
# --- Create HGA params and inject into Whisper ---
self.hga_layers = nn.ModuleList()
d = self.output_dim
for i, layer in enumerate(self.encoder.layers):
attn = layer.self_attn
# Shared curvature for Q/K/V of this layer
curvature = LearnableCurvature(
init_value=hga_c_init, c_min=hga_c_min, c_max=hga_c_max
)
# Diagonal scaling: identity (s=1) at init → first-step output ≈ W_ref
s_q = nn.Parameter(torch.ones(d))
s_k = nn.Parameter(torch.ones(d))
s_v = nn.Parameter(torch.ones(d))
# Möbius bias: tiny random init so b ≠ 0 from step 0 and ∂L/∂c ≠ 0
b_q = nn.Parameter(torch.randn(d) * hga_b_init_std)
b_k = nn.Parameter(torch.randn(d) * hga_b_init_std)
b_v = nn.Parameter(torch.randn(d) * hga_b_init_std)
# Replace q/k/v_proj with HGA-modulated versions
attn.q_proj = HGALinear(attn.q_proj, s_q, b_q, curvature)
attn.k_proj = HGALinear(attn.k_proj, s_k, b_k, curvature)
attn.v_proj = HGALinear(attn.v_proj, s_v, b_v, curvature)
# Container so optimizer sees these params
cont = nn.Module()
cont.curvature = curvature
cont.s_q, cont.s_k, cont.s_v = s_q, s_k, s_v
cont.b_q, cont.b_k, cont.b_v = b_q, b_k, b_v
self.hga_layers.append(cont)
logger.info(
f"Whisper encoder: {num_encoder_layers} layers, "
f"all Q/K/V wrapped in HGALinear "
f"(c_init={hga_c_init}, c_min={hga_c_min}, c_max={hga_c_max}, "
f"b_std={hga_b_init_std})"
)
# --- Feature capture hooks ---
self._features: Dict[int, torch.Tensor] = {}
self._hooks = []
for idx, layer in enumerate(self.encoder.layers):
if idx in self.extract_layers:
self._hooks.append(
layer.register_forward_hook(self._make_hook(idx))
)
def _make_hook(self, layer_idx: int):
def hook_fn(module, input, output):
self._features[layer_idx] = (
output[0] if isinstance(output, tuple) else output
)
return hook_fn
def forward(self, mel_input: torch.Tensor) -> List[torch.Tensor]:
"""Run Whisper with HGA-modulated attention.
Args:
mel_input: (B, n_mels, T_mel)
Returns:
List of (B, T, 1280) tensors, one per extract_layer (sorted).
"""
encoder_dtype = self.encoder.layer_norm.weight.dtype
mel = mel_input.to(dtype=encoder_dtype)
self._features.clear()
_ = self.encoder(mel)
features = []
for ln in self.extract_layers:
if ln not in self._features:
raise RuntimeError(
f"Layer {ln} not captured. Got: {sorted(self._features.keys())}"
)
features.append(self._features[ln])
return features
def num_audio_frames(self, audio_samples_16khz: int) -> int:
return min(math.ceil(audio_samples_16khz / 320), 1500)
# ---- Diagnostics ----
def get_hga_diagnostics(self) -> Dict[str, float]:
"""Per-layer scalars logged to TensorBoard."""
diag = {}
for i, hga in enumerate(self.hga_layers):
diag[f"hga/c_L{i}"] = hga.curvature().item()
diag[f"hga/s_q_mean_L{i}"] = hga.s_q.data.mean().item()
diag[f"hga/s_v_mean_L{i}"] = hga.s_v.data.mean().item()
# b norms — key indicator: if these stay ~0, c won't learn
diag[f"hga/b_q_norm_L{i}"] = hga.b_q.data.norm().item()
diag[f"hga/b_k_norm_L{i}"] = hga.b_k.data.norm().item()
diag[f"hga/b_v_norm_L{i}"] = hga.b_v.data.norm().item()
return diag
def get_curvatures_summary(self) -> str:
"""Compact c-per-layer string for log lines (grouped 8 per row)."""
vals = [f"{hga.curvature().item():.4f}" for hga in self.hga_layers]
groups = []
for i in range(0, len(vals), 8):
groups.append("/".join(vals[i:i+8]))
return " | ".join(groups)
def get_b_norm_summary(self) -> str:
"""Compact b_q-per-layer norm string (grouped 8 per row).
Used to verify the 'b grows → c learns' training dynamic."""
vals = [f"{hga.b_q.data.norm().item():.4f}" for hga in self.hga_layers]
groups = []
for i in range(0, len(vals), 8):
groups.append("/".join(vals[i:i+8]))
return " | ".join(groups)