Download code/tinyear/model.py from sanjithrj/tiny-ear-asr: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/sanjithrj/tiny-ear-asr/resolve/main/code/tinyear/model.py
- Command line
-
hf download hf://sanjithrj/tiny-ear-asr/code/tinyear/model.py
-
curl -L -o model.py https://huggingface.co/sanjithrj/tiny-ear-asr/resolve/main/code/tinyear/model.py
30.5 kB
| """The whole speech-to-text model in one file: sound goes in, text comes out. About 19.3 million numbers (parameters). | |
| READ THIS FIRST: THE BIG PICTURE | |
| ================================ | |
| Think of a very fast stenographer who listens in tiny slices and writes down what was said. | |
| sound -> [Fbank] -> [Stem] -> [12 Blocks] -> [CTC head or TDT head] -> words | |
| waveform "how loud "squash "understand "write the words" | |
| is each 8 slices each moment | |
| pitch?" into 1" using context" | |
| 1. Fbank : turns the raw sound wave into a picture of "how much energy is at each pitch, 100 times a second". | |
| 2. Stem : shrinks that picture in time by 8, so the rest of the model has 8x less to think about. | |
| 3. Blocks : twelve layers (Conformer blocks). Each layer lets every moment look at the moments around it, | |
| so the model can tell "ice cream" from "I scream" by using the words that come before. | |
| 4. Heads : two different "writers" read the same understanding. CTC is simple and fast. TDT is smarter | |
| (it also remembers the last words it wrote). Either one can be used. | |
| STREAMING = LIVE | |
| ================ | |
| The same weights can run in two ways: | |
| * forward() : look at a whole recording at once (used for training and testing). | |
| * stream_step() : look at one short chunk at a time and remember a little of the past (used live). | |
| Both give the same answer, as long as they use the same "who can look at whom" rules. That is tested. | |
| WORDS USED BELOW (a mini dictionary) | |
| ==================================== | |
| frame one tiny slice of time. After the Stem, one frame = 80 milliseconds. | |
| token a piece of a word ("taught" might be "t" + "a" + "ugh" + "t"). Id 0 is special: "blank / nothing". | |
| tensor a box of numbers (like a spreadsheet, but possibly with more than 2 directions). | |
| batch (B) how many recordings we process at the same time. | |
| d the width of the model's "thought vector" for each frame (256 numbers). | |
| logits raw scores for each possible answer, before turning them into probabilities. | |
| residual "x = x + something": the layer only adds a correction, it never throws the old information away. | |
| cache a small notebook of the recent past, kept between chunks so live mode can still look backwards. | |
| loop running the same layers more than once (same weights, second look at the same thing). | |
| """ | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # --- Fixed numbers about the audio --------------------------------------------------------------------------------- | |
| # SR : samples per second. The microphone gives us 16,000 numbers every second. | |
| # N_FFT : each "look" at the sound uses a window of 400 samples = 25 milliseconds. | |
| # HOP : we slide that window forward by 160 samples = 10 milliseconds each time, so 100 looks per second. | |
| # N_MELS : for every look we measure 80 pitch bands ("mel bands", spaced the way human hearing works). | |
| SR, N_FFT, HOP, N_MELS = 16000, 400, 160, 80 | |
| HIST = N_FFT - HOP # audio samples carried between chunks so S samples -> exactly S // HOP frames | |
| # (Windows overlap: each 400-sample window starts 160 after the last one. Live mode keeps the last 240 samples | |
| # from the previous chunk so the first window of the new chunk has the sound it needs.) | |
| # DURATIONS: the TDT writer can say "after writing this, move forward by 0, 1, 2, 3 or 4 frames". | |
| DURATIONS = (0, 1, 2, 3, 4) | |
| # ===================================================================================================================== | |
| # PART 1: FRONT END. Raw sound wave -> a "picture" of the sound (log-mel spectrogram). | |
| # ===================================================================================================================== | |
| def mel_fbanks(n_freqs, n_mels): | |
| """Builds 80 triangle-shaped filters. Each one adds up the energy inside one pitch band. | |
| Human ears are better at telling low pitches apart than high ones, so the 'mel' scale spaces the bands | |
| closer together at low pitch and wider at high pitch. Returns a table of shape (n_mels, n_freqs).""" | |
| m = lambda f: 2595 * math.log10(1 + f / 700) # Hz -> mel (the ear-friendly pitch scale) | |
| hz = 700 * (10 ** (torch.linspace(0, m(SR / 2), n_mels + 2) / 2595) - 1) # band edges, equally spaced in mel | |
| f = torch.linspace(0, SR / 2, n_freqs) # the frequency (in Hz) of each row the DFT gives us | |
| lo, c, hi = hz[:-2, None], hz[1:-1, None], hz[2:, None] # each triangle: left foot, peak, right foot | |
| # The triangle rises from 'lo' up to 'c' and falls from 'c' down to 'hi'; clamp(min=0) cuts off below zero. | |
| return torch.clamp(torch.minimum((f - lo) / (c - lo), (hi - f) / (hi - c)), min=0) | |
| class Fbank(nn.Module): | |
| """Log-mel as a fixed DFT conv1d (no STFT op, exports anywhere). Global CMVN buffers are set from data. | |
| In plain words: for every 10 ms of sound, answer "how loud is each of 80 pitch bands?" and take the log | |
| (because we hear loudness on a log scale). The result is a grid: time going one way, 80 pitches the other. | |
| The DFT (the math that splits sound into pitches) is written as a convolution with fixed numbers, so this | |
| layer has NOTHING to learn (0 parameters) and works on any device without special 'FFT' support.""" | |
| def __init__(self): | |
| super().__init__() | |
| n, k = torch.arange(N_FFT), torch.arange(N_FFT // 2 + 1)[:, None] | |
| ang = 2 * math.pi * k * n / N_FFT # the angle of each sine/cosine wave we test the sound against | |
| # cos and -sin rows together give the real and imaginary parts of the DFT; the Hann window fades the edges | |
| # of every 25 ms window to zero so we do not get fake clicks at the borders. | |
| basis = torch.cat([torch.cos(ang), -torch.sin(ang)]) * torch.hann_window(N_FFT) | |
| # register_buffer = "saved with the model / moved to the GPU with it, but NOT something training changes". | |
| self.register_buffer("basis", basis[:, None], persistent=False) | |
| self.register_buffer("mel", mel_fbanks(N_FFT // 2 + 1, N_MELS), persistent=False) | |
| # mean / std: measured once from the training audio ("CMVN"). Subtracting the average and dividing by the | |
| # spread puts every recording on the same scale, so quiet and loud microphones look alike. | |
| self.register_buffer("mean", torch.zeros(N_MELS)) | |
| self.register_buffer("std", torch.ones(N_MELS)) | |
| def forward(self, wav): # (B, HIST + S) -> (B, S // HOP, 80) | |
| # Slide the fixed sine/cosine tests along the sound, jumping HOP=160 samples each time. | |
| re, im = F.conv1d(wav.float()[:, None], self.basis, stride=HOP).chunk(2, 1) | |
| # re**2 + im**2 = the energy at each frequency; self.mel adds those up into 80 bands; log squashes the range | |
| # (1e-6 stops us taking log of exactly zero); transpose puts time first. | |
| x = torch.log(self.mel @ (re ** 2 + im ** 2) + 1e-6).transpose(1, 2) | |
| return (x - self.mean) / self.std # put on a standard scale | |
| # ===================================================================================================================== | |
| # PART 2: STEM. Shrink time by 8 so the expensive layers have 8x less work. | |
| # ===================================================================================================================== | |
| class Stem(nn.Module): | |
| """FastConformer 8x subsampling, causal in time: each stride-2 conv sees the previous 2 rows (zeros or cache). | |
| In plain words: the Fbank gives 100 slices per second. That is more detail than we need to understand speech. | |
| The Stem looks at neighbouring slices and merges every 8 into one richer one (12.5 per second, 80 ms each). | |
| It does this with 3 convolutions that each halve the time (2 x 2 x 2 = 8) and also halve the 80 pitch bands | |
| (80 -> 40 -> 20 -> 10). | |
| 'Causal' = it never peeks at the FUTURE. That is what makes live use possible: to produce slice t it only needs | |
| slice t and the 2 slices before it. In live mode those 2 earlier rows are kept in a small cache.""" | |
| def __init__(self, d): | |
| super().__init__() | |
| # dw(): a "depthwise-separable" convolution = (1) a 3x3 filter run separately per channel, halving size, | |
| # then (2) a 1x1 mix across channels. It gives almost the same power as a normal conv for far fewer numbers. | |
| dw = lambda: nn.Sequential(nn.Conv2d(d, d, 3, 2, (0, 1), groups=d), nn.Conv2d(d, d, 1)) | |
| # First conv: 1 channel in (the picture) -> d=256 channels out. The padding is (0, 1): none in time (we | |
| # supply the past ourselves, see forward) and 1 in pitch. | |
| self.convs = nn.ModuleList([nn.Conv2d(1, d, 3, 2, (0, 1)), dw(), dw()]) | |
| # After 3 halvings of the 80 pitch bands we have 10 left, each with d channels: flatten d*10 -> d. | |
| self.out = nn.Linear(d * N_MELS // 8, d) | |
| def forward(self, x, caches=None): # x (B, T, 80) -> (B, ceil(T/8), d), new caches | |
| x, new = x[:, None], [] # add a "channel" direction so the picture looks like a 1-channel image | |
| for i, conv in enumerate(self.convs): | |
| # 'prev' = the 2 rows just before this chunk: from the cache in live mode, or zeros at the very start. | |
| prev = caches[i] if caches else x.new_zeros(x.shape[0], x.shape[1], 2, x.shape[3]) | |
| x = torch.cat([prev, x], 2) # glue the past on in front, so the conv can look 2 rows back | |
| new.append(x[:, :, -2:]) # remember the last 2 rows for NEXT time (the new cache) | |
| x = F.silu(conv(x)) # convolve, then a smooth on/off curve (SiLU) so the layer can be non-linear | |
| # Flatten the (channels x remaining pitch) numbers of each time step into one vector of size d. | |
| return self.out(x.permute(0, 2, 1, 3).flatten(2)), new | |
| # ===================================================================================================================== | |
| # PART 3: POSITION TRICK (RoPE). Lets attention know HOW FAR APART two moments are. | |
| # ===================================================================================================================== | |
| def rope(pos, dh): | |
| """For each position, makes the cos/sin numbers used to 'rotate' vectors (see rotate below). | |
| Idea: instead of adding a number that says "I am position 17", we turn each vector by an angle that depends | |
| on its position. When two vectors are compared, only the DIFFERENCE of their angles matters, so the model | |
| naturally learns "3 steps ago" rather than "absolute position 17". That works great for streaming, where the | |
| absolute position keeps growing forever.""" | |
| # Different pairs of numbers rotate at different speeds (some slowly, some quickly), like the hands on a clock. | |
| f = pos[:, None].float() * 10000 ** (-torch.arange(0, dh, 2, device=pos.device) / dh) | |
| return f.cos(), f.sin() | |
| def rotate(x, cs): | |
| """Applies the rotation: every pair of numbers (a, b) is turned by the angle for its position.""" | |
| c, s = cs | |
| a, b = x[..., ::2], x[..., 1::2] # split into pairs: even-numbered entries and odd-numbered entries | |
| # The standard 2-D rotation formula: (a, b) -> (a*cos - b*sin, a*sin + b*cos) | |
| return torch.stack([a * c - b * s, a * s + b * c], -1).flatten(-2).type_as(x) | |
| # ===================================================================================================================== | |
| # PART 4: THE BUILDING BLOCKS OF ONE LAYER | |
| # ===================================================================================================================== | |
| class SwiGLU(nn.Module): | |
| """A 'feed-forward' layer: thinks about each moment ON ITS OWN (no looking at neighbours). | |
| Steps: normalize -> expand to a wider space (2 x h numbers) -> use one half as a 'gate' that switches the other | |
| half on and off (SiLU(a) * b) -> shrink back to d numbers. The gate lets the layer decide which of its many | |
| features matter for this particular moment.""" | |
| def __init__(self, d, h, p): | |
| super().__init__() | |
| # norm: RMSNorm keeps numbers at a steady size. wi: widen (d -> 2h). wo: narrow (h -> d). No biases. | |
| self.norm, self.wi, self.wo = nn.RMSNorm(d), nn.Linear(d, 2 * h, bias=False), nn.Linear(h, d, bias=False) | |
| self.drop = nn.Dropout(p) # during training, randomly zero some numbers so the model cannot just memorize | |
| def forward(self, x): | |
| a, b = self.wi(self.norm(x)).chunk(2, -1) # cut the widened vector into two halves | |
| return self.drop(self.wo(self.drop(F.silu(a) * b))) # half 'a' gates half 'b', then shrink back | |
| class Block(nn.Module): | |
| """One Conformer block. The model stacks 12 of these. Four steps in a fixed order: | |
| 1. half a feed-forward : think about each moment alone | |
| 2. attention : look at other moments for context (long-range) | |
| 3. convolution : look at the last few moments for local rhythm (short-range) | |
| 4. half a feed-forward : think again with the new context | |
| then a final normalization. | |
| Every step ADDS its result to what was there before (x = x + ...), so nothing is ever erased: a layer can only | |
| refine. That is also why running a block a second time (looping) is safe.""" | |
| def __init__(self, d, heads, ff, kernel, p): | |
| super().__init__() | |
| self.ff1, self.ff2 = SwiGLU(d, ff, p), SwiGLU(d, ff, p) # the two half feed-forwards | |
| # Attention parts: n_att = normalize first; qkv = one layer that makes Query, Key and Value (3 x d numbers); | |
| # o = the output layer that mixes the heads back together. | |
| self.n_att, self.qkv, self.o = nn.RMSNorm(d), nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False) | |
| # Convolution parts: n_conv = normalize; pw1 = widen to 2d (so GLU can gate it back down to d). | |
| self.n_conv, self.pw1 = nn.RMSNorm(d), nn.Linear(d, 2 * d, bias=False) | |
| self.dw = nn.Conv1d(d, d, kernel, groups=d) # causal: left context comes from zeros / cache | |
| # dw = depthwise conv: each of the d channels is filtered separately over the last 'kernel' (=9) frames. | |
| # n_dw = normalize again; pw2 = pointwise (1-frame) mixing layer back to d numbers. | |
| self.n_dw, self.pw2 = nn.RMSNorm(d), nn.Linear(d, d, bias=False) | |
| self.n_out, self.drop, self.h, self.p, self.k = nn.RMSNorm(d), nn.Dropout(p), heads, p, kernel | |
| def forward(self, x, cs, mask, cache=None): | |
| """x: (B, T, d) the thoughts for T frames. cs: the rotation numbers from rope(). mask: who may look at whom. | |
| cache: the notebook of the recent past (live mode only). Returns the new x and the updated cache.""" | |
| B, T, d = x.shape | |
| # ---- Step 1: first half feed-forward (the 0.5 makes it a 'half step') ---- | |
| x = x + 0.5 * self.ff1(x) | |
| # ---- Step 2: attention ---- | |
| # Every frame makes a QUERY ("what am I looking for?"), a KEY ("what do I contain?") and a VALUE ("what do I | |
| # hand over if you pick me?"). A frame pays more attention to frames whose key matches its query. | |
| # The numbers are split into 'heads' (4 of them): 4 independent ways of looking at the same frames. | |
| q, k, v = self.qkv(self.n_att(x)).view(B, T, 3, self.h, -1).permute(2, 0, 3, 1, 4) | |
| q, k = rotate(q, cs), rotate(k, cs) # add the position information (only to queries and keys) | |
| if cache: | |
| # Live mode: put the remembered keys/values from earlier chunks in front of the new ones, so the new | |
| # frames can look backwards too. L = how many remembered frames there are (70). | |
| L = cache[0].shape[2] | |
| k, v = torch.cat([cache[0], k], 2), torch.cat([cache[1], v], 2) | |
| # The actual attention: score each query against each allowed key (mask hides the rest), turn scores into | |
| # percentages, and return the percentage-weighted mix of the values. PyTorch's fused function does it fast. | |
| a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=self.p if self.training else 0.0) | |
| x = x + self.drop(self.o(a.transpose(1, 2).reshape(B, T, d))) # glue the heads back together, add (residual) | |
| # ---- Step 3: convolution module (local context) ---- | |
| # normalize -> widen to 2d -> GLU (a gate halves it back to d) = pick the useful features. | |
| c = F.glu(self.pw1(self.n_conv(x)), -1) | |
| # Put the last (kernel-1)=8 frames of history in front, so the filter can look 8 frames back without peeking | |
| # ahead. At the start of a stream there is no history, so we use zeros. | |
| c = torch.cat([cache[2] if cache else c.new_zeros(B, self.k - 1, d), c], 1) | |
| # The new cache for next time: the latest L keys, L values, and the last 8 conv frames. | |
| new = (k[:, :, -L:], v[:, :, -L:], c[:, -(self.k - 1):]) if cache else None | |
| c = self.dw(c.transpose(1, 2)).transpose(1, 2) # filter each channel over its last 9 frames | |
| x = x + self.drop(self.pw2(F.silu(self.n_dw(c)))) # normalize, SiLU, mix, add (residual) | |
| # ---- Step 4: second half feed-forward, then the final normalization ---- | |
| return self.n_out(x + 0.5 * self.ff2(x)), new | |
| # ===================================================================================================================== | |
| # PART 5: THE FULL MODEL | |
| # ===================================================================================================================== | |
| class ASR(nn.Module): | |
| """The complete recognizer. ASR = Automatic Speech Recognition (speech to text).""" | |
| MAX_PASSES = 4 # the most times any loop may run; the per-pass notes below are sized for this many | |
| def __init__(self, vocab=1024, d=256, layers=12, heads=4, ff=640, kernel=9, p=0.1, inter_layer=None, left=70, | |
| loops=()): | |
| """loops: [[first_block, last_block, passes], ...] (1-based, inclusive): those blocks run `passes` times in a row, | |
| reusing their weights; a learned per-pass vector (zero-initialised: 1 pass == the plain model) marks each pass. | |
| Settings in plain words: | |
| vocab = how many word-pieces the model can write (1024). A "blank" is added on top, giving 1025. | |
| d = width of each frame's thought vector (256 numbers). | |
| layers = number of Conformer blocks (12). | |
| heads = attention heads (4): ways of looking in parallel. | |
| ff = hidden size inside each feed-forward layer (640). | |
| kernel = how many frames the convolution looks at (9). | |
| p = dropout chance during training (0.1). | |
| inter_layer = the block after which an early 'draft' guess is made (default: the middle, block 6). | |
| left = how many past frames live mode remembers (70 frames = 5.6 seconds). | |
| loops = which blocks to re-run, e.g. [[2, 3, 2], [7, 9, 2]] means 'blocks 2-3 twice, blocks 7-9 twice'.""" | |
| super().__init__() | |
| inter_layer = inter_layer or layers // 2 | |
| loops = [list(lp) for lp in loops] | |
| for a, b, n in loops: | |
| assert 1 <= a <= b <= layers and 1 <= n <= self.MAX_PASSES, (a, b, n) # sanity: valid block range and count | |
| assert not (a <= inter_layer <= b), "the intermediate-CTC block must run exactly once" | |
| # Save the settings so a checkpoint file can rebuild exactly the same model later. | |
| self.cfg = dict(vocab=vocab, d=d, layers=layers, heads=heads, ff=ff, kernel=kernel, p=p, | |
| inter_layer=inter_layer, left=left, loops=loops) | |
| if loops: | |
| # One learned vector of d numbers per (loop, pass). It starts at ZERO, so before any training it changes | |
| # nothing: one pass behaves exactly like the original model. It tells the shared blocks "this is pass 2". | |
| self.pass_emb = nn.Parameter(torch.zeros(len(loops), self.MAX_PASSES, d)) | |
| self.fbank, self.stem = Fbank(), Stem(d) # Parts 1 and 2 | |
| self.blocks = nn.ModuleList(Block(d, heads, ff, kernel, p) for _ in range(layers)) # the 12 blocks | |
| # ---- CTC head: the simple, fast writer. For each frame it gives a score for every word-piece (+ blank). | |
| self.ctc = nn.Linear(d, vocab + 1) # id 0 = blank; sentencepiece id i -> i + 1 | |
| # ---- Self-conditioning: the halfway 'draft' guess (from self.ctc at block 6) is turned back into a vector | |
| # and added in, so the later blocks can see the draft and fix it. cond: scores (vocab+1) -> d numbers. | |
| self.cond = nn.Linear(vocab + 1, d) # self-conditioning: intermediate CTC posteriors fed back | |
| # ---- TDT head: the smarter writer. It remembers the last 2 tokens it wrote (the 'predictor') and combines | |
| # that with the audio understanding (the 'joiner') to decide the next token AND how far to move on. | |
| self.pred_emb = nn.Embedding(vocab + 1, d) # TDT stateless predictor, blank doubles as <start> | |
| self.pred_conv = nn.Conv1d(d, d, 2, groups=d) # context = previous 2 tokens | |
| self.j_enc, self.j_pred = nn.Linear(d, d), nn.Linear(d, d) # bring audio and word-memory to a common form | |
| self.j_out = nn.Linear(d, vocab + 1 + len(DURATIONS)) # final scores: tokens first, then the 5 durations | |
| def schedule(self, passes=None): | |
| """Execution order as (block index, (loop, pass) | None). passes: int for every loop, a list, or None (cfg). | |
| In plain words: a recipe card that says which block to run next. Without loops it is just 0, 1, 2 ... 11. | |
| With loops, a group is repeated in place before moving on. Example with loops [[2,3,2],[7,9,2]]: | |
| blocks 1, (2 3), (2 3), 4, 5, 6, (7 8 9), (7 8 9), 10, 11, 12 -> 17 steps in total. | |
| The second item of each pair marks the first block of a loop group with (loop number, pass number), so | |
| encode() knows when to add the 'which pass am I on' vector.""" | |
| loops = self.cfg["loops"] | |
| # How many passes each loop gets: from the config, or one number for all, or a list. | |
| counts = [lp[2] for lp in loops] if passes is None else ( | |
| [passes] * len(loops) if isinstance(passes, int) else list(passes)) | |
| starts = {lp[0] - 1: k for k, lp in enumerate(loops)} # block index where each loop begins (0-based) | |
| out, i = [], 0 | |
| while i < self.cfg["layers"]: | |
| if i in starts: # a loop begins here: repeat the whole group 'counts[k]' times | |
| k = starts[i] | |
| a, b = loops[k][0] - 1, loops[k][1] - 1 | |
| for pi in range(counts[k]): | |
| out += [(j, (k, pi) if j == a else None) for j in range(a, b + 1)] | |
| i = b + 1 # jump past the group | |
| else: | |
| out.append((i, None)) # an ordinary block, run once | |
| i += 1 | |
| return out | |
| def encode(self, x, cs, mask, caches=None, passes=None): | |
| """Runs the stack of blocks in the order given by schedule(). Returns (final thoughts, draft scores, caches).""" | |
| inter, new = None, [] | |
| for pos, (i, tag) in enumerate(self.schedule(passes)): | |
| if tag is not None: | |
| # The first block of a loop pass: add the learned 'this is pass N' vector (zeros at the start). | |
| x = x + self.pass_emb[tag[0], tag[1]] | |
| x, c = self.blocks[i](x, cs, mask, caches[pos] if caches else None) | |
| new.append(c) # one cache per EXECUTED block (so a repeated block keeps separate notebooks per visit) | |
| if i + 1 == self.cfg["inter_layer"]: | |
| # Halfway point: make a draft guess of the words, then feed it back in (self-conditioning). | |
| inter = self.ctc(x) | |
| x = x + self.cond(inter.softmax(-1)) # softmax turns raw scores into percentages | |
| return x, inter, new | |
| def forward(self, wav, lens, chunk=None, specaug=False, tokens=None, passes=None): | |
| """wav (B, S), lens (B,) samples; chunk = frames per attention chunk (None = full context). | |
| Returns encoder out (B, T, d), CTC logits, intermediate CTC logits, frame lens | |
| (+ TDT joint logits when target tokens are given: keeps the whole training graph inside forward for DDP). | |
| In plain words: take a batch of recordings, run the whole pipeline, and return the understanding plus the | |
| CTC scores. If 'tokens' (the correct text) is given, also return the TDT scores, which training needs. | |
| 'chunk' decides how far ahead each frame may look: small chunk = low delay, None = may see everything.""" | |
| # Part 1: sound -> picture. We first add HIST=240 zeros in front so the first window has enough samples. | |
| x = self.fbank(F.pad(wav, (HIST, 0))) | |
| lens = lens // HOP # recording lengths, now counted in 10 ms frames instead of samples | |
| if specaug: # training only: hide random blocks of the picture so the model learns to cope with gaps | |
| from asr.augment import specaug as aug | |
| x = aug(x, lens) | |
| # Part 2: shrink time by 8. Each of the 3 halvings rounds the length up, so we do the same to 'lens'. | |
| x, _ = self.stem(x) | |
| for _ in range(3): | |
| lens = (lens + 1) // 2 | |
| T = x.shape[1] # number of 80 ms frames | |
| pos = torch.arange(T, device=x.device) # 0, 1, 2, ... T-1: the position of each frame | |
| # ---- The attention mask: a yes/no table of "may frame q look at frame k?" ---- | |
| # First rule: only real frames count (not the padding added to make recordings equal length). | |
| mask = (pos < lens[:, None])[:, None, :] # (B, q=1, k=T) valid keys | |
| if chunk: | |
| # Second rule (live-style): frames are grouped into chunks. A frame may look at its own chunk and at the | |
| # earlier chunks, but not further back than 'left' (70) frames, and NEVER at later chunks. | |
| qc = pos[:, None] // chunk # which chunk each querying frame belongs to | |
| mask = mask & (pos // chunk <= qc) & (pos >= qc * chunk - self.cfg["left"]) | |
| # Always let a frame look at itself, so no row is ever completely blocked (that would break the maths). | |
| mask = (mask | torch.eye(T, dtype=torch.bool, device=x.device))[:, None] | |
| # Part 3: the 12 blocks (with loops if configured). rope() makes the position-rotation numbers. | |
| enc, inter, _ = self.encode(x, rope(pos, self.cfg["d"] // self.cfg["heads"]), mask, passes=passes) | |
| out = (enc, self.ctc(enc), inter, lens) # CTC scores for every frame come straight from the CTC head | |
| # If the correct words were given (training), also compute the TDT scores for every (frame, word) pair. | |
| return out + (self.joint(enc, self.predict(tokens)),) if tokens is not None else out | |
| def stream_init(self, batch=1, device="cpu", passes=None): | |
| """Makes the EMPTY notebooks for starting a live stream: zeros everywhere, as if the past was silence.""" | |
| c, z = self.cfg, lambda *s: torch.zeros(*s, device=device) | |
| dh = c["d"] // c["heads"] # size of each attention head (64) | |
| return dict(wav=z(batch, HIST), t=0, passes=passes, | |
| # 'wav': the last 240 samples (so the next chunk's first window is complete); 't': frames so far | |
| # 'stem': the 2-row memories of the 3 Stem convolutions | |
| stem=[z(batch, 1, 2, N_MELS), z(batch, c["d"], 2, N_MELS // 2), z(batch, c["d"], 2, N_MELS // 4)], | |
| # 'layers': one notebook per executed block = (past keys, past values, past conv frames) | |
| layers=[(z(batch, c["heads"], c["left"], dh), z(batch, c["heads"], c["left"], dh), | |
| z(batch, c["kernel"] - 1, c["d"])) for _ in self.schedule(passes)]) # one per executed block | |
| def stream_step(self, wav, state): | |
| """wav (B, chunk * 8 * HOP) new samples -> encoder frames for this chunk (B, chunk, d), CTC logits, new state. | |
| In plain words: feed in the NEXT short piece of audio plus the notebooks from last time; get back the | |
| understanding of just this piece and the updated notebooks. Call it again and again for a live stream.""" | |
| w = torch.cat([state["wav"], wav], 1) # the 240 leftover samples + the new audio | |
| x, stem = self.stem(self.fbank(w), state["stem"]) # Parts 1 and 2, using and updating the Stem memory | |
| t0, T, L = state["t"], x.shape[1], self.cfg["left"] # t0: frames already done; T: frames in this chunk | |
| # At the very start of a stream the notebooks hold zeros, not real frames. Hide those empty slots | |
| # (cache_ok is False for positions before the stream began), so the model does not attend to fake past. | |
| cache_ok = torch.arange(t0 - L, t0, device=x.device) >= 0 # cache slots before the stream started | |
| mask = torch.cat([cache_ok, cache_ok.new_ones(T)])[None, None, None] # all new frames are visible to each other | |
| pos = torch.arange(t0, t0 + T, device=x.device) # absolute positions continue where the last chunk ended | |
| enc, _, layers = self.encode(x, rope(pos, self.cfg["d"] // self.cfg["heads"]), mask, state["layers"], | |
| state.get("passes")) | |
| # Return this chunk's understanding, its CTC scores, and the updated notebooks. | |
| return enc, self.ctc(enc), dict(wav=w[:, -HIST:], t=t0 + T, passes=state.get("passes"), stem=stem, layers=layers) | |
| def predict(self, y): | |
| """y (B, U) previous tokens (ids >= 1) -> predictor states (B, U + 1, d); state u conditions on y[u-2], y[u-1]. | |
| In plain words: the TDT writer's 'memory of what I just wrote'. It only remembers the last 2 words-pieces | |
| (a short memory is enough and keeps it small and fast). The padding adds two 'start' tokens in front.""" | |
| e = self.pred_emb(F.pad(y, (2, 0))).transpose(1, 2) # look up a vector for each token | |
| return F.relu(self.pred_conv(e)).transpose(1, 2) # combine each token's previous 2 with a tiny conv | |
| def joint(self, enc, pred): | |
| """(B, T, d), (B, U+1, d) -> (B, T, U+1, vocab + 1 + len(DURATIONS)): token logits then duration logits. | |
| In plain words: for every combination of 'audio frame t' and 'words written so far u', combine what the | |
| ears heard (enc) with what the writer remembers (pred) and score: which token comes next, and how many | |
| frames to advance. The first 1025 scores are for tokens, the last 5 for the durations 0..4.""" | |
| return self.j_out(F.relu(self.j_enc(enc)[:, :, None] + self.j_pred(pred)[:, None])) | |