Download controller/encoder/student.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 3.72 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/controller/encoder/student.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/controller/encoder/student.py
-
curl -L -o student.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/controller/encoder/student.py
3.72 kB
| """Causal streaming student of the baseline audio encoder. | |
| Input: 16 kHz mono audio. Output: one 1280-d vector every 40 ms (25 Hz), the rate and | |
| width of the baseline AudioEncoder, so two vectors per 80 ms frame. | |
| Nothing here looks ahead: the mel frame for hop k uses samples up to the end of hop k | |
| (the baseline's STFT is centred and its log-mel is clamped by the whole clip's | |
| maximum, which a streaming front end cannot do), and attention is causal with a | |
| bounded window. `forward` (whole crop) and `step` (80 ms at a time) are the same | |
| function. | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| from duplex.spec import HOP, N_FFT, N_MELS, PATCH, SR, TEACHER_DIM | |
| from duplex.streaming import CausalTransformer | |
| TAIL = N_FFT - HOP # 240 samples of history each new mel frame needs | |
| def mel_filterbank(): | |
| """The baseline's filterbank (librosa, Slaney), built once at training time and then | |
| carried inside the checkpoint, so serving does not need librosa.""" | |
| import librosa | |
| return torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float() | |
| class StreamingMel(nn.Module): | |
| def __init__(self, fb=None): | |
| super().__init__() | |
| self.register_buffer("window", torch.hann_window(N_FFT)) | |
| self.register_buffer("fb", fb if fb is not None else torch.zeros(N_MELS, N_FFT // 2 + 1)) | |
| def forward(self, wav, tail=None): | |
| """wav [B, T], T a multiple of HOP -> log-mel [B, T/HOP, N_MELS], new tail [B, 240].""" | |
| assert wav.shape[1] % HOP == 0 | |
| with torch.autocast(wav.device.type, enabled=False): | |
| wav = wav.float() | |
| if tail is None: | |
| tail = wav.new_zeros(wav.shape[0], TAIL) | |
| x = torch.cat([tail, wav], dim=1) | |
| frames = x.unfold(1, N_FFT, HOP) # [B, T/HOP, 400] | |
| power = torch.fft.rfft(frames * self.window, dim=-1).abs() ** 2 | |
| mel = power @ self.fb.T | |
| logmel = (torch.clamp(mel, min=1e-6).log10() + 4.0) / 4.0 # fixed floor, no clip-level max | |
| return logmel, x[:, -TAIL:] | |
| class StudentEncoder(nn.Module): | |
| def __init__(self, dim=512, layers=12, heads=8, window=250, out_dim=TEACHER_DIM, fb=None): | |
| super().__init__() | |
| self.cfg = dict(dim=dim, layers=layers, heads=heads, window=window, out_dim=out_dim) | |
| self.mel = StreamingMel(fb) | |
| self.inp = nn.Linear(PATCH * N_MELS, dim) | |
| self.tf = CausalTransformer(dim, layers, heads, window) | |
| self.ln = nn.LayerNorm(dim) | |
| self.head = nn.Linear(dim, out_dim) | |
| def _tokens(self, logmel): | |
| B, N, M = logmel.shape | |
| return self.inp(logmel.reshape(B, N // PATCH, PATCH * M).to(self.inp.weight.dtype)) | |
| def forward(self, wav): | |
| """wav [B, T], T a multiple of 640 -> features [B, T/640, out_dim].""" | |
| logmel, _ = self.mel(wav) | |
| return self.head(self.ln(self.tf(self._tokens(logmel)))) | |
| def init_state(self, batch, device): | |
| return {"tail": torch.zeros(batch, TAIL, device=device), "tf": self.tf.init_state()} | |
| def step(self, wav, state): | |
| """wav [B, t], t a multiple of 640 (one 80 ms frame is 1280) -> [B, t/640, out_dim].""" | |
| logmel, tail = self.mel(wav, state["tail"]) | |
| x, tf = self.tf.step(self._tokens(logmel), state["tf"]) | |
| return self.head(self.ln(x)), {"tail": tail, "tf": tf} | |
| def save_student(path, model, extra=None): | |
| torch.save({"cfg": model.cfg, "model": model.state_dict(), "extra": extra or {}}, path) | |
| def load_student(path, device="cpu"): | |
| from duplex.streaming import read_checkpoint | |
| cfg, state = read_checkpoint(path) | |
| model = StudentEncoder(**cfg) | |
| model.load_state_dict(state) | |
| return model.to(device).eval() | |