File size: 14,484 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Muaalem mini, made to stream: the same weights and layers, but each frame
only sees its own chunk and `left` frames before it.

Two ways to run it, which must give the same numbers:

- `forward`: a whole batch of clips at once, every chunk in parallel. Used
  for training and evaluation.
- `step`: one chunk at a time, carrying a `State` from chunk to chunk. Used
  by the app (exported to ONNX).

What differs from the original model (docs: "What we change in the model"):

- Attention in the 24 layers and in the adapter: limited to the chunk and
  `left` frames before it.
- Position tags: this model rotates each frame's *input* to attention by its
  position before projecting it, so keys can't be cached with old
  positions. Each step recomputes keys over its window, with positions
  0 .. left-1 for the remembered frames and left .. left+chunk-1 for the
  chunk. Slots before the start of the audio are masked out.
- The rest (feed-forward steps, the causal convolutions, the adapter's two
  stride-2 convolutions, the head) is unchanged; the convolutions keep the
  frames they need from earlier chunks.
"""

from __future__ import annotations

import json
import math
from dataclasses import dataclass
from pathlib import Path

import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from huggingface_hub import snapshot_download
from safetensors.torch import load_file
from torch import nn
from transformers import Wav2Vec2BertConfig, Wav2Vec2BertModel

REPO = "sysofwan/hifzguide-muaalem-mini"
FILES = [
    "config.json",
    "model.safetensors",
    "phoneme_vocab.json",
    "preprocessor_config.json",
    "LICENSE",
    "NOTICE.md",
]


class MuaalemMini(nn.Module):
    """Wav2Vec2-BERT encoder + the `phonemes` CTC head (stock transformers
    classes; the repo's custom code is never run)."""

    def __init__(self, config: dict):
        super().__init__()
        self.encoder = Wav2Vec2BertModel(Wav2Vec2BertConfig(**config))
        self.head = nn.Linear(
            config["output_hidden_size"], config["level_to_vocab_size"]["phonemes"]
        )

    def forward(self, input_features: torch.Tensor) -> torch.Tensor:
        return self.head(self.encoder(input_features).last_hidden_state)


def download() -> Path:
    return Path(snapshot_download(REPO, allow_patterns=FILES))


def load_muaalem(snapshot: Path) -> MuaalemMini:
    config = json.loads((snapshot / "config.json").read_text())
    for key in ("architectures", "auto_map", "model_type"):
        config.pop(key, None)
    model = MuaalemMini(config).eval()
    renamed = {}
    for key, value in load_file(snapshot / "model.safetensors").items():
        if key.startswith("wav2vec2_bert."):
            renamed["encoder." + key.removeprefix("wav2vec2_bert.")] = value
        elif key.startswith("level_to_lm_head.phonemes."):
            renamed["head." + key.removeprefix("level_to_lm_head.phonemes.")] = value
        else:
            raise SystemExit(f"unexpected weight {key}")
    missing, unexpected = model.load_state_dict(renamed, strict=False)
    missing = [k for k in missing if not k.endswith("inv_freq")]
    if missing or unexpected:
        raise SystemExit(f"missing {missing}, unexpected {unexpected}")
    return model


def vocab(snapshot: Path) -> list[str]:
    return json.loads((snapshot / "phoneme_vocab.json").read_text())["id_to_char"]


@dataclass
class State:
    """What one streaming step hands to the next.

    attn:  (L, B, left, D)   each layer's attention input (before rotation)
    conv:  (L, B, K-1, D)    each layer's depthwise-conv input
    a_res, a_att: (B, 1, D)  the adapter's two conv inputs, last frame
    a_attn: (B, left/2, D)   the adapter's attention input
    seen:  ()                frames (50/s) processed so far
    """

    attn: torch.Tensor
    conv: torch.Tensor
    a_res: torch.Tensor
    a_att: torch.Tensor
    a_attn: torch.Tensor
    seen: torch.Tensor

    def tensors(self) -> tuple[torch.Tensor, ...]:
        return (self.attn, self.conv, self.a_res, self.a_att, self.a_attn, self.seen)


def _rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, heads: int) -> torch.Tensor:
    """Rotary position tags on (..., S, D) with cos/sin (S, d), per head,
    as Wav2Vec2BertSelfAttention._apply_rotary_embedding does."""
    shape = x.shape
    x = x.reshape(*shape[:-1], heads, shape[-1] // heads)
    half = x.shape[-1] // 2
    turned = torch.cat((-x[..., half:], x[..., :half]), dim=-1)
    x = x * cos[:, None, :] + turned * sin[:, None, :]
    return x.reshape(shape)


class StreamingMuaalem(nn.Module):
    def __init__(self, base: MuaalemMini, chunk: int = 32, left: int = 192):
        super().__init__()
        if chunk % 2 or left % 2:
            raise ValueError("chunk and left must be even (the adapter halves the rate)")
        model = base.encoder
        self.projection = model.feature_projection
        self.layers = model.encoder.layers
        self.adapter = model.adapter.layers[0]
        self.head = base.head
        self.chunk = chunk
        self.left = left
        config = model.config
        self.heads = config.num_attention_heads
        self.dim = config.hidden_size
        self.kernel = config.conv_depthwise_kernel_size
        self.register_buffer(
            "inv_freq", model.encoder.embed_positions.inv_freq.clone(), persistent=False
        )
        self.checkpointing = False

    # -- position tags ---------------------------------------------------

    def _cos_sin(self, length: int, device, dtype):
        t = torch.arange(length, device=device, dtype=torch.float32)
        freqs = t[:, None] * self.inv_freq[None, :]
        emb = torch.cat((freqs, freqs), dim=-1)
        return emb.cos().to(dtype), emb.sin().to(dtype)

    # -- attention over a chunk and the frames before it -------------------

    def _attend(self, attn, query_in, window_in, key_index, query_index, rotary, valid_len):
        """query_in: (..., C, D) chunk frames; window_in: (..., W, D) the
        remembered frames then the chunk. key_index (..., W) / query_index
        (..., C): absolute frame numbers (negative = before the audio).
        Returns (..., C, D) after the output projection."""
        C, W = query_in.shape[-2], window_in.shape[-2]
        if rotary:
            cos, sin = self._cos_sin(W, window_in.device, window_in.dtype)
            keys_in = _rotate(window_in, cos, sin, self.heads)
            query_in = _rotate(query_in, cos[W - C :], sin[W - C :], self.heads)
        else:
            keys_in = window_in
        lead = query_in.shape[:-2]
        d = self.dim // self.heads
        q = attn.linear_q(query_in).reshape(*lead, C, self.heads, d).transpose(-2, -3)
        k = attn.linear_k(keys_in).reshape(*lead, W, self.heads, d).transpose(-2, -3)
        v = attn.linear_v(window_in).reshape(*lead, W, self.heads, d).transpose(-2, -3)
        # Every frame of the window, except slots before the audio began.
        allowed = (key_index >= 0)[..., None, :].expand(*key_index.shape[:-1], C, W)
        if valid_len is not None:
            allowed = allowed & (key_index[..., None, :] < valid_len)
        # A frame may always see itself (keeps fully padded rows finite).
        allowed = allowed | (key_index[..., None, :] == query_index[..., :, None])
        out = F.scaled_dot_product_attention(
            q, k, v, attn_mask=allowed.unsqueeze(-3), scale=attn.scaling
        )
        out = out.transpose(-2, -3).reshape(*lead, C, self.dim)
        return attn.linear_out(out)

    def _windowed(self, attn, x, chunk, left, lengths, rotary):
        """All chunks of x (B, T, D) at once: chunk i sees frames
        [i*chunk - left, (i+1)*chunk)."""
        B, T, D = x.shape
        n = math.ceil(T / chunk)
        padded = F.pad(x, (0, 0, left, n * chunk - T))
        windows = padded.unfold(1, left + chunk, chunk).transpose(-1, -2)  # (B, n, W, D)
        queries = padded[:, left:].reshape(B, n, chunk, D)
        starts = torch.arange(n, device=x.device) * chunk
        key_index = (starts[:, None] - left + torch.arange(left + chunk, device=x.device)).expand(B, -1, -1)
        query_index = (starts[:, None] + torch.arange(chunk, device=x.device)).expand(B, -1, -1)
        valid = lengths.view(B, 1, 1, 1)
        out = self._attend(attn, queries, windows, key_index, query_index, rotary, valid)
        return out.reshape(B, n * chunk, D)[:, :T]

    # -- one conformer layer -----------------------------------------------

    def _layer(self, layer, h, attend):
        residual = h
        h = layer.ffn1(layer.ffn1_layer_norm(h)) * 0.5 + residual
        residual = h
        h = attend(layer.self_attn_layer_norm(h)) + residual
        residual = h
        h = residual + self._conv_full(layer.conv_module, h)
        residual = h
        h = layer.ffn2(layer.ffn2_layer_norm(h)) * 0.5 + residual
        return layer.final_layer_norm(h)

    @staticmethod
    def _conv_full(conv, h):
        return conv(h)

    # -- whole clips, all chunks in parallel (training) --------------------

    def forward(self, features: torch.Tensor, lengths: torch.Tensor, chunk: int | None = None, left: int | None = None):
        """features: (B, T, 160) rescaled frames at 50/s; lengths: (B,)
        valid frames. Returns logits (B, ceil(T/2), 43) at 25/s and their
        valid lengths."""
        chunk = chunk or self.chunk
        left = self.left if left is None else left
        h = self.projection(features)[0]
        for layer in self.layers:
            attend = lambda x, layer=layer: self._windowed(layer.self_attn, x, chunk, left, lengths, True)  # noqa: E731
            if self.checkpointing and self.training:
                h = torch.utils.checkpoint.checkpoint(self._layer, layer, h, attend, use_reentrant=False)
            else:
                h = self._layer(layer, h, attend)
        out_lengths = (lengths + 1) // 2
        h = self._adapter_full(h, lengths, out_lengths, chunk // 2, left // 2)
        return self.head(h), out_lengths

    def _adapter_full(self, h, lengths, out_lengths, chunk, left):
        a = self.adapter
        B, T, _ = h.shape
        mask = (torch.arange(T, device=h.device)[None, :] < lengths[:, None]).unsqueeze(-1)
        residual = a.activation(a.residual_conv((a.residual_layer_norm(h) * mask).transpose(1, 2))).transpose(1, 2)
        x = a.activation(a.self_attn_conv((a.self_attn_layer_norm(h) * mask).transpose(1, 2))).transpose(1, 2)
        x = self._windowed(a.self_attn, x, chunk, left, out_lengths, False) + residual
        return a.ffn(a.ffn_layer_norm(x)) + x

    # -- one chunk at a time (the app) -------------------------------------

    def initial_state(self, batch: int = 1, device=None, dtype=torch.float32) -> State:
        L, D = len(self.layers), self.dim
        z = lambda *s: torch.zeros(*s, device=device, dtype=dtype)  # noqa: E731
        return State(
            attn=z(L, batch, self.left, D),
            conv=z(L, batch, self.kernel - 1, D),
            a_res=z(batch, 1, D),
            a_att=z(batch, 1, D),
            a_attn=z(batch, self.left // 2, D),
            seen=torch.zeros((), dtype=torch.int64, device=device),
        )

    def step(self, features: torch.Tensor, state: State) -> tuple[torch.Tensor, State]:
        """features: (B, chunk, 160). Returns logits (B, chunk/2, 43)."""
        C = features.shape[1]
        left = self.left
        dev = features.device
        key_index = state.seen - left + torch.arange(left + C, device=dev)
        query_index = state.seen + torch.arange(C, device=dev)
        h = self.projection(features)[0]
        new_attn, new_conv = [], []
        for i, layer in enumerate(self.layers):
            residual = h
            h = layer.ffn1(layer.ffn1_layer_norm(h)) * 0.5 + residual
            residual = h
            x = layer.self_attn_layer_norm(h)
            window = torch.cat([state.attn[i], x], dim=1)
            h = self._attend(layer.self_attn, x, window, key_index, query_index, True, None) + residual
            new_attn.append(window[:, -left:])
            residual = h
            out, cache = self._conv_step(layer.conv_module, h, state.conv[i])
            new_conv.append(cache)
            h = residual + out
            residual = h
            h = layer.ffn2(layer.ffn2_layer_norm(h)) * 0.5 + residual
            h = layer.final_layer_norm(h)

        a = self.adapter
        r_in = torch.cat([state.a_res, a.residual_layer_norm(h)], dim=1)
        s_in = torch.cat([state.a_att, a.self_attn_layer_norm(h)], dim=1)
        residual = a.activation(F.conv1d(r_in.transpose(1, 2), a.residual_conv.weight, a.residual_conv.bias, stride=2)).transpose(1, 2)
        x = a.activation(F.conv1d(s_in.transpose(1, 2), a.self_attn_conv.weight, a.self_attn_conv.bias, stride=2)).transpose(1, 2)
        half, seen2 = C // 2, state.seen // 2
        window = torch.cat([state.a_attn, x], dim=1)
        k2 = seen2 - left // 2 + torch.arange(left // 2 + half, device=dev)
        q2 = seen2 + torch.arange(half, device=dev)
        x = self._attend(a.self_attn, x, window, k2, q2, False, None) + residual
        x = a.ffn(a.ffn_layer_norm(x)) + x

        state = State(
            attn=torch.stack(new_attn),
            conv=torch.stack(new_conv),
            a_res=r_in[:, -1:],
            a_att=s_in[:, -1:],
            a_attn=window[:, -(left // 2):],
            seen=state.seen + C,
        )
        return self.head(x), state

    @staticmethod
    def _conv_step(conv, h, cache):
        """The conformer convolution on one chunk, with the K-1 frames of
        depthwise input carried over from before."""
        x = conv.glu(conv.pointwise_conv1(conv.layer_norm(h).transpose(1, 2)))  # (B, D, C)
        x = torch.cat([cache.transpose(1, 2), x], dim=2)
        new_cache = x[:, :, -cache.shape[1]:].transpose(1, 2)
        x = conv.depthwise_conv(x)
        x = conv.depthwise_layer_norm(x.transpose(1, 2)).transpose(1, 2)
        x = conv.pointwise_conv2(conv.activation(x))
        return x.transpose(1, 2), new_cache


def greedy(ids, blank: int = 0, previous: int | None = None) -> tuple[list[int], int | None]:
    """Collapse repeats and drop blanks; `previous` carries the last id
    across chunks so a letter split over two chunks counts once."""
    out = []
    for i in ids:
        i = int(i)
        if i != previous and i != blank:
            out.append(i)
        previous = i
    return out, previous