File size: 3,716 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""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()