duplex-v0 / controller /encoder /teacher.py
Jr23xd23's picture
RightNow Duplex v0
f730521 verified
Raw History Blame Contribute Delete
5.92 kB
"""The baseline's audio encoder, loaded alone (about 0.6B of the 33B), as the frozen teacher.
`AudioEncoder`, `log_mel` and the length arithmetic follow
modeling_step_audio_2.py / utils.py of stepfun-ai/Step-Audio-R1.1
(Copyright StepFun, Apache-2.0). Parameter names are kept identical so the released
weights load with strict=True. Only the `encoder.*` tensors are read from the
checkpoint shards; the LLM is never loaded.
"""
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from duplex.spec import N_FFT, N_MELS, SR
class MultiHeadAttention(nn.Module):
def __init__(self, n_state, n_head):
super().__init__()
self.n_head = n_head
self.query = nn.Linear(n_state, n_state)
self.key = nn.Linear(n_state, n_state, bias=False)
self.value = nn.Linear(n_state, n_state)
self.out = nn.Linear(n_state, n_state)
def forward(self, x, bias):
# Same attention as the released code (q and k each scaled by d_head ** -0.25, i.e. the usual
# 1 / sqrt(d_head)), computed with PyTorch's fused routine: the released explicit float32
# softmax over batch x heads x T x T made a distillation step several times slower.
B, T, _ = x.shape
q, k, v = (m(x).view(B, T, self.n_head, -1).transpose(1, 2) for m in (self.query, self.key, self.value))
a = F.scaled_dot_product_attention(q, k, v, attn_mask=bias.to(q.dtype))
return self.out(a.transpose(1, 2).flatten(start_dim=2))
class ResidualAttentionBlock(nn.Module):
def __init__(self, n_state, n_head):
super().__init__()
self.attn = MultiHeadAttention(n_state, n_head)
self.attn_ln = nn.LayerNorm(n_state)
self.mlp = nn.Sequential(nn.Linear(n_state, n_state * 4), nn.GELU(), nn.Linear(n_state * 4, n_state))
self.mlp_ln = nn.LayerNorm(n_state)
def forward(self, x, bias):
x = x + self.attn(self.attn_ln(x), bias)
return x + self.mlp(self.mlp_ln(x))
class AudioEncoder(nn.Module):
"""Every clip in a batch has the same length here (fixed crops). The released code
still hides the two mel frames that come from its 479-sample padding
(feats_lengths = frames - 2); the same key mask is applied here."""
def __init__(self, n_mels=128, n_ctx=1500, n_state=1280, n_head=20, n_layer=32):
super().__init__()
self.conv1 = nn.Conv1d(n_mels, n_state, kernel_size=3, padding=1)
self.conv2 = nn.Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1)
self.positional_embedding = nn.Embedding(n_ctx, n_state)
self.blocks = nn.ModuleList([ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)])
self.avg_pooler = nn.AvgPool1d(2, stride=2)
self.after_norm = nn.LayerNorm(n_state)
def forward(self, mel):
T = mel.size(-1)
x = F.gelu(self.conv1(mel))
x = F.gelu(self.conv2(x)).permute(0, 2, 1)
assert x.shape[1] <= self.positional_embedding.num_embeddings, "clip longer than the encoder context (about 29.9 s)"
valid = (torch.arange(T, device=mel.device) < T - 2)[(T + 1) % 2::2] # released make_non_pad_mask + subsampling
bias = ((~valid).to(x.dtype) * -1.0e10)[None, None, None, :]
x = x + self.positional_embedding.weight[: x.shape[1]]
for block in self.blocks:
x = block(x, bias)
x = self.avg_pooler(x.permute(0, 2, 1)).permute(0, 2, 1)
return self.after_norm(x)
def log_mel(audio, filters):
"""Released log_mel_spectrogram (padding=479), batched over equal-length clips [B, T]."""
audio = F.pad(audio, (0, 479))
window = torch.hann_window(N_FFT, device=audio.device)
stft = torch.stft(audio, N_FFT, 160, window=window, return_complex=True)
mel = filters @ (stft[..., :-1].abs() ** 2)
log_spec = torch.clamp(mel, min=1e-10).log10()
log_spec = torch.maximum(log_spec, log_spec.amax(dim=(1, 2), keepdim=True) - 8.0) # per clip, as released
return (log_spec + 4.0) / 4.0
class Teacher(nn.Module):
def __init__(self, model_dir):
super().__init__()
import librosa
self.register_buffer("filters", torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float())
model_dir = Path(model_dir)
cfg = json.loads((model_dir / "config.json").read_text())["audio_encoder_config"]
self.encoder = AudioEncoder(cfg["n_mels"], cfg["n_audio_ctx"], cfg["n_audio_state"], cfg["n_audio_head"], cfg["n_audio_layer"])
self.encoder.load_state_dict(_encoder_weights(model_dir), strict=True)
self.requires_grad_(False).eval()
@torch.no_grad()
def forward(self, wav):
"""wav [B, T] at 16 kHz, T a multiple of 640 -> [B, T/640, 1280] (25 Hz)."""
with torch.autocast(wav.device.type, enabled=False):
mel = log_mel(wav.float(), self.filters)
with torch.autocast(wav.device.type, dtype=torch.bfloat16, enabled=wav.is_cuda):
out = self.encoder(mel)
n = wav.shape[1] // 640
assert out.shape[1] == n, f"teacher gave {out.shape[1]} frames for {n} expected"
return out.float()
def _encoder_weights(model_dir):
from safetensors import safe_open
weight_map = json.loads((model_dir / "model.safetensors.index.json").read_text())["weight_map"]
keys = [k for k in weight_map if k.startswith("encoder.")]
if not keys:
prefixes = sorted({k.split(".")[0] for k in weight_map})
raise RuntimeError(f"no 'encoder.*' tensors in the checkpoint index; top-level names are {prefixes}")
sd = {}
for shard in sorted({weight_map[k] for k in keys}):
with safe_open(str(model_dir / shard), framework="pt") as f:
for k in f.keys():
if k.startswith("encoder."):
sd[k[len("encoder."):]] = f.get_tensor(k).float()
return sd