changh95's picture
tt-model push raon-speech-9b (container)
4ffdd01 verified
Raw History Blame Contribute Delete
6.81 kB
# SPDX-License-Identifier: Apache-2.0
"""Clean-room fp32 reference of the Raon audio encoder path (ARCH section 4; official ``AuTWrapper`` /
``AuTEncoder`` non-causal path + ``get_audio_input_embeds``):
aut = AuT(ck)
rows = aut(wavs24) # list of 24 kHz waveforms -> [sum_c keep_c, 4096] thinker rows
enc, lens, feats = aut.encode(feats) # stage tensors (aut_encoder_out [C, R, 2048], output lens)
Per chunk (8 s of 24 kHz audio = 800 mel frames): mel split into windows of 100 frames, each window padded to the
longest window of the chunk, conv2d x3 (3x3, s2, p1, GELU) -> conv_out (7680 -> 1024, no bias) + sinusoid position
rows 0..12 (restart per window), the valid rows of every window concatenated; the chunks padded to a batch; 24
pre-LN layers with bidirectional attention inside each chunk (padded keys masked, padded rows zeroed after each
residual add); ln_post, proj1, GELU, proj2, padded rows zeroed. The wrapper truncates / zero-pads every chunk to
ceil(padded_len_24k / 1920) rows; rows with index < ceil(L_c / 1920) are valid; the input adaptor maps them to the
thinker width, valid rows of all chunks in order.
"""
from __future__ import annotations
import math
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from ..config import MAX_AUDIO_CHUNK, SAMPLES_PER_FRAME
from ..frontend.audio import chunk_audio
from ..frontend.mel import AuTFeatures, aut_features
from ..weights import stages as ST
from ..weights.source import Checkpoint
from .model import InputAdaptor
D, HEADS, LAYERS, WIN = 1024, 16, 24, 100
EPS = 1e-5
def sinusoids(length: int, channels: int = D, max_timescale: float = 10000.0) -> torch.Tensor:
inc = np.log(max_timescale) / (channels // 2 - 1)
inv = torch.exp(-inc * torch.arange(channels // 2).float())
t = torch.arange(length)[:, None] * inv[None, :]
return torch.cat([torch.sin(t), torch.cos(t)], dim=1)
def after_cnn(n: int) -> int:
for _ in range(3):
n = (n - 1) // 2 + 1
return n
class AuT:
def __init__(self, ck: Checkpoint):
self.w = {k: v.float() for k, v in ST.aut_encoder(ck).items()}
self.adaptor = InputAdaptor(ck)
self.pe = sinusoids(1500)
# ------------------------------------------------------------------ pieces
def _lin(self, x, n, bias=True):
y = x @ self.w[n + ".weight"].T
return y + self.w[n + ".bias"] if bias else y
def _ln(self, x, n):
return F.layer_norm(x, (x.shape[-1],), self.w[n + ".weight"], self.w[n + ".bias"], EPS)
def conv_rows(self, mel_c: torch.Tensor, n_frames: int) -> torch.Tensor:
"""One chunk: mel [128, >= n_frames] -> conv rows [R, 1024] (+ PE)."""
feat = mel_c[:, :n_frames]
n_win = math.ceil(n_frames / WIN)
lens = [WIN] * n_win
if n_frames % WIN:
lens[-1] = n_frames % WIN
wins = list(feat.T.split(lens, dim=0))
tmax = max(lens)
x = torch.zeros(n_win, tmax, feat.shape[0])
for i, wv in enumerate(wins):
x[i, : wv.shape[0]] = wv
x = x.transpose(1, 2).unsqueeze(1) # [n, 1, 128, tmax]
for i in (1, 2, 3):
x = F.gelu(F.conv2d(x, self.w[f"conv2d{i}.weight"], self.w[f"conv2d{i}.bias"], stride=2, padding=1))
n, c, fr, t = x.shape
x = x.permute(0, 3, 1, 2).contiguous().view(n, t, c * fr) @ self.w["conv_out.weight"].T
x = x + self.pe[:t][None]
return torch.cat([x[i, : after_cnn(L)] for i, L in enumerate(lens)])
def layer(self, l: int, x: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
"""x [C, R, D], valid [C, R] bool."""
p = f"layers.{l}."
C, R, _ = x.shape
hd = D // HEADS
h = self._ln(x, p + "self_attn_layer_norm")
q = self._lin(h, p + "self_attn.q_proj").view(C, R, HEADS, hd).transpose(1, 2)
k = self._lin(h, p + "self_attn.k_proj").view(C, R, HEADS, hd).transpose(1, 2)
v = self._lin(h, p + "self_attn.v_proj").view(C, R, HEADS, hd).transpose(1, 2)
mask = torch.zeros(C, 1, 1, R).masked_fill(~valid[:, None, None, :], torch.finfo(torch.float32).min)
o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=hd ** -0.5)
o = o.transpose(1, 2).reshape(C, R, D)
m = valid[..., None].float()
x = (x + self._lin(o, p + "self_attn.out_proj")) * m
h = self._ln(x, p + "final_layer_norm")
x = (x + self._lin(F.gelu(self._lin(h, p + "fc1")), p + "fc2")) * m
return x
@torch.inference_mode()
def encode(self, f: AuTFeatures, taps: Optional[dict] = None) -> Tuple[torch.Tensor, List[int]]:
"""-> (encoder output [C, R_max, 2048] with padded rows 0, rows per chunk)."""
rows = [self.conv_rows(f.mel[c], int(f.mel_lens[c])) for c in range(f.chunks)]
lens = [int(r.shape[0]) for r in rows]
R = max(lens)
x = torch.zeros(f.chunks, R, D)
valid = torch.zeros(f.chunks, R, dtype=torch.bool)
for c, r in enumerate(rows):
x[c, : r.shape[0]] = r
valid[c, : r.shape[0]] = True
if taps is not None:
taps["conv_rows"] = x.clone()
for l in range(LAYERS):
x = self.layer(l, x, valid)
x = self._ln(x, "ln_post")
x = self._lin(F.gelu(self._lin(x, "proj1")), "proj2")
return x * valid[..., None].float(), lens
def truncate(self, enc: torch.Tensor, f: AuTFeatures) -> torch.Tensor:
"""AuTWrapper: every chunk to ``expected_rows`` (truncate / zero-pad) -> [C, E, 2048] (= golden aut_out)."""
E = f.expected_rows
if enc.shape[1] >= E:
return enc[:, :E]
return F.pad(enc, (0, 0, 0, E - enc.shape[1]))
@torch.inference_mode()
def rows_from_features(self, f: AuTFeatures, taps: Optional[dict] = None) -> torch.Tensor:
enc, _ = self.encode(f, taps)
out = self.truncate(enc, f)
ad = self.adaptor(out) # [C, E, 4096] (official: adaptor on every row, then the mask selects)
if taps is not None:
taps.update(aut_encoder_out=enc, aut_out=out, in_adaptor_out=ad)
return torch.cat([ad[c, : min(k, ad.shape[1])] for c, k in enumerate(f.keep_rows)])
def __call__(self, wavs24: Sequence[torch.Tensor], max_chunk: int = MAX_AUDIO_CHUNK,
taps: Optional[dict] = None) -> torch.Tensor:
"""24 kHz waveforms (prompt order) -> thinker rows [sum_c keep_c, 4096] (the input placeholders' rows)."""
b, l = chunk_audio(wavs24, max_chunk)
return self.rows_from_features(aut_features(b, l), taps)
def placeholder_count(wavs24: Sequence[torch.Tensor]) -> int:
return sum(math.ceil(int(w.shape[-1]) / SAMPLES_PER_FRAME) for w in wavs24)