File size: 6,573 Bytes
21f5301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""Features for streaming Muaalem: the same log-mel frames as the
SeamlessM4T feature extractor the model was trained with, computed in torch
(so training can run them on the GPU), but rescaled with running statistics
instead of the whole clip's.

Frames: 25 ms windows every 10 ms (100 a second), 80 mel bins, Kaldi style
(DC offset removed, preemphasis 0.97, Povey window, 512-point FFT, natural
log). The model then takes pairs of frames: 160 values, 50 a second.

Rescaling: each bin is shifted and scaled by the mean and variance of the
last `window` frames up to the end of the current chunk, blended with fixed
global statistics worth `prior` frames, so the first chunk is not rescaled by
a handful of frames. The app does exactly the same, chunk by chunk.
"""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F
from transformers import SeamlessM4TFeatureExtractor

RATE = 16000
FRAME = 400  # samples per fbank frame (25 ms)
HOP = 160  # samples between frames (10 ms)
FFT = 512
BINS = 80
EPS = 1e-7


@dataclass(frozen=True)
class NormStats:
    """Global per-bin mean and variance of raw log-mel frames."""

    mean: torch.Tensor  # (80,)
    var: torch.Tensor  # (80,)

    @staticmethod
    def load(path: Path) -> "NormStats":
        data = json.loads(path.read_text())
        return NormStats(torch.tensor(data["mean"]), torch.tensor(data["var"]))

    def save(self, path: Path, frames: int) -> None:
        path.write_text(
            json.dumps(
                {
                    "frames": frames,
                    "mean": [round(float(x), 6) for x in self.mean],
                    "var": [round(float(x), 6) for x in self.var],
                }
            )
        )

    def to(self, device) -> "NormStats":
        return NormStats(self.mean.to(device), self.var.to(device))


class Fbank(torch.nn.Module):
    """Raw (not yet rescaled) log-mel frames, matching
    SeamlessM4TFeatureExtractor._extract_fbank_features."""

    def __init__(self):
        super().__init__()
        extractor = SeamlessM4TFeatureExtractor(
            feature_size=BINS, num_mel_bins=BINS, sampling_rate=RATE, stride=2, padding_value=1
        )
        self.register_buffer("window", torch.tensor(extractor.window, dtype=torch.float32))
        # (257, 80): FFT bins -> mel bins.
        self.register_buffer("mel", torch.tensor(extractor.mel_filters, dtype=torch.float32))

    @staticmethod
    def frames(samples: int) -> int:
        return 0 if samples < FRAME else 1 + (samples - FRAME) // HOP

    def forward(self, audio: torch.Tensor) -> torch.Tensor:
        """audio: (B, S) floats in [-1, 1] -> (B, frames(S), 80)."""
        x = audio.float() * 32768  # Kaldi works on 16-bit sample values
        frames = x.unfold(-1, FRAME, HOP)  # (B, T, 400)
        frames = frames - frames.mean(-1, keepdim=True)
        frames = torch.cat(
            [frames[..., :1] * (1 - 0.97), frames[..., 1:] - 0.97 * frames[..., :-1]], dim=-1
        )
        spectrum = torch.fft.rfft(frames * self.window, n=FFT).abs() ** 2  # (B, T, 257)
        return torch.clamp(spectrum @ self.mel, min=1.192092955078125e-07).log()


def running_normalize(
    fbank: torch.Tensor,
    lengths: torch.Tensor,
    chunk: int,
    stats: NormStats,
    window: int = 1000,
    prior: int = 100,
) -> torch.Tensor:
    """Rescales raw frames chunk by chunk, as the app does while streaming.

    fbank: (B, T, 80) raw log-mel frames; lengths: (B,) valid frames each.
    chunk: frames per chunk at 100 a second (twice the model's chunk).
    Each frame uses the statistics of frames [max(0, end - window), end),
    where end is the end of its chunk (clipped to the valid length).
    """
    B, T, _ = fbank.shape
    device = fbank.device
    valid = (torch.arange(T, device=device)[None, :] < lengths[:, None]).unsqueeze(-1)
    x = fbank.double() * valid
    zero = torch.zeros(B, 1, BINS, dtype=x.dtype, device=device)
    sums = torch.cat([zero, x.cumsum(1)], 1)  # (B, T+1, 80)
    squares = torch.cat([zero, (x * x).cumsum(1)], 1)

    t = torch.arange(T, device=device)
    end = torch.minimum(((t // chunk) + 1) * chunk, lengths[:, None])  # (B, T)
    end = torch.maximum(end, torch.ones_like(end))
    start = torch.clamp(end - window, min=0)
    n = (end - start).unsqueeze(-1).double()

    def window_sum(c: torch.Tensor) -> torch.Tensor:
        take = lambda i: c.gather(1, i.unsqueeze(-1).expand(-1, -1, BINS))  # noqa: E731
        return take(end) - take(start)

    mean_g = stats.mean.to(device).double()
    var_g = stats.var.to(device).double()
    mean = (window_sum(sums) + prior * mean_g) / (n + prior)
    second = (window_sum(squares) + prior * (var_g + mean_g**2)) / (n + prior)
    var = torch.clamp(second - mean**2, min=0)
    out = (fbank.double() - mean) / torch.sqrt(var + EPS)
    return (out * valid).float()


def whole_clip_normalize(fbank: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
    """What the original extractor does: each clip rescaled by its own
    statistics (variance with ddof=1), padding left out."""
    T = fbank.shape[1]
    valid = (torch.arange(T, device=fbank.device)[None, :] < lengths[:, None]).unsqueeze(-1)
    x = fbank.double() * valid
    n = lengths.view(-1, 1, 1).double()
    mean = x.sum(1, keepdim=True) / n
    var = ((x - mean) ** 2 * valid).sum(1, keepdim=True) / (n - 1).clamp(min=1)
    return ((fbank.double() - mean) / torch.sqrt(var + EPS) * valid).float()


def stack_pairs(x: torch.Tensor) -> torch.Tensor:
    """(B, T, 80) at 100/s -> (B, T // 2, 160) at 50/s, as the extractor does."""
    B, T, D = x.shape
    T -= T % 2
    return x[:, :T].reshape(B, T // 2, D * 2)


def global_stats(fbanks: list[torch.Tensor]) -> tuple[NormStats, int]:
    """Per-bin mean and variance over many clips' raw frames."""
    total = sum(f.shape[0] for f in fbanks)
    s = sum(f.double().sum(0) for f in fbanks)
    ss = sum((f.double() ** 2).sum(0) for f in fbanks)
    mean = s / total
    var = ss / total - mean**2
    return NormStats(mean.float(), var.float()), total


def pad_batch(clips: list[np.ndarray]) -> tuple[torch.Tensor, torch.Tensor]:
    """int16 clips -> (B, S) float audio and (B,) sample counts."""
    lengths = torch.tensor([len(c) for c in clips])
    audio = torch.zeros(len(clips), int(lengths.max()))
    for i, c in enumerate(clips):
        audio[i, : len(c)] = torch.from_numpy(c.astype(np.float32) / 32768)
    return audio, lengths