cartesinus commited on
Commit
3d4d3bc
·
verified ·
1 Parent(s): ed8faff

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language: en
4
+ tags:
5
+ - audio
6
+ - audio-classification
7
+ - voice-assistant
8
+ - wake-word
9
+ - device-directed-speech
10
+ - zipformer
11
+ datasets:
12
+ - TCLResearchEurope/intelligent_wakeup
13
+ metrics:
14
+ - f1
15
+ pipeline_tag: audio-classification
16
+ ---
17
+
18
+ # int_wakeup-zipformer_small-ctx20-ft4
19
+
20
+ Decides, turn by turn, whether a voice assistant should respond — **without
21
+ requiring a wake word**. It reads the current utterance together with up to 20
22
+ preceding turns, so it can accept a follow-up like *"and the one after that?"*
23
+ and reject a question two people are asking each other.
24
+
25
+ Same recipe as
26
+ [`int_wakeup-whisper_base-ctx20-ft4`](https://huggingface.co/TCLResearchEurope/int_wakeup-whisper_base-ctx20-ft4),
27
+ with a **Zipformer** encoder in place of Whisper. Trained and evaluated on
28
+ [`TCLResearchEurope/intelligent_wakeup`](https://huggingface.co/datasets/TCLResearchEurope/intelligent_wakeup)
29
+ v1.0.1.
30
+
31
+ ## Results
32
+
33
+ Test split: 243 conversations, 3,647 scored turns, 6.72 h of recording of which
34
+ 5.28 h is speech not addressed to the assistant. Threshold **0.35**, swept on
35
+ validation and applied unchanged to test.
36
+
37
+ | | precision | recall | F1 | FA/hour |
38
+ |---|---|---|---|---|
39
+ | **this model** | **0.924** | 0.856 | **0.889** | **3.98** |
40
+ | whisper-base sibling | 0.931 | 0.853 | 0.890 | 3.60 |
41
+ | GPT Realtime prompted baseline | 0.098 | 0.997 | 0.179 | 516.6 |
42
+
43
+ False accepts per hour are over the 5.28 h of not-addressed speech; over the
44
+ whole 6.72 h recording this model gives 3.12/hour.
45
+
46
+ By turn type:
47
+
48
+ | type | n | recall |
49
+ |---|---|---|
50
+ | `direct` — contains the wake word | 158 | **0.981** |
51
+ | `contextual` — follow-up, no wake word | 141 | 0.716 |
52
+ | `non-assistance` — human-to-human | 3,348 | 21 false accepts |
53
+
54
+ **It reaches the same F1 as the Whisper model by a different trade**: better at
55
+ spotting the wake word (0.981 vs 0.943), worse at follow-ups without one
56
+ (0.716 vs 0.794). If your traffic is mostly explicit invocations, this is the
57
+ better of the two; if it is mostly conversational follow-up, take the Whisper
58
+ one.
59
+
60
+ Averaging this run's three kept checkpoints gives F1 0.895 at 5.31 FA/hour —
61
+ better F1, worse false accepts.
62
+
63
+ ## Architecture
64
+
65
+ 25.3M parameters; the encoder is 22.0M of them.
66
+
67
+ 1. **Per-turn encoder** — Zipformer-small (6 stacks, 12 layers, 256-d output)
68
+ over Kaldi filterbank features, then learned attention pooling to one 256-d
69
+ vector per turn.
70
+ 2. **Context transformer** — 4 causal layers, 256-d, over the last 20 turn
71
+ vectors plus a speaker-role embedding each. Turn *t* attends to 0..*t* and
72
+ never to the future.
73
+ 3. **Heads** — a trigger logit, plus an auxiliary turn-type head used only as a
74
+ training signal.
75
+
76
+ Initialised from icefall's LibriSpeech CR-CTC
77
+ [`zipformer-small`](https://huggingface.co/Zengwei/icefall-asr-librispeech-zipformer-small-cr-ctc-20241018),
78
+ then trained in two phases: encoder frozen with turn embeddings cached, then the
79
+ **top 4 encoder layers unfrozen** (10.9M trainable).
80
+
81
+ Unlike Whisper, Zipformer runs on the utterance's real length rather than a
82
+ padded 30 s window. Utterances are still capped at 30 s to match what Whisper
83
+ saw, and floored at 0.3 s — below about 0.09 s the convolutional frontend
84
+ returns zero frames.
85
+
86
+ ### Two encoders at inference — please read
87
+
88
+ Phase 2 fine-tuned the encoder for the **current** turn while the **context**
89
+ turns kept being read from a cache built with the **frozen** encoder. The model
90
+ expects that asymmetry, and inference has to reproduce it:
91
+
92
+ | | encoder |
93
+ |---|---|
94
+ | current turn | the fine-tuned one, in `model.safetensors` |
95
+ | context turns | the pristine pretrained Zipformer + `context_pooling_head.safetensors` |
96
+
97
+ Encoding everything with the fine-tuned encoder raises no error and costs about
98
+ 0.18 F1 (measured on the Whisper sibling). `inference.py` does it correctly;
99
+ start from that rather than reimplementing. The context encoder's weights are
100
+ downloaded from the Hub on first run.
101
+
102
+ This asymmetry is a training artefact rather than a design choice, and it is the
103
+ first thing to fix in a retrain.
104
+
105
+ ## Usage
106
+
107
+ ```bash
108
+ pip install -r requirements.txt
109
+ python inference.py session.wav turns.json
110
+ ```
111
+
112
+ `turns.json` is the turn segmentation — this model classifies turns, it does not
113
+ find them, so bring your own VAD and diarisation:
114
+
115
+ ```json
116
+ [{"start": 0.0, "end": 4.2, "speaker": "Tariq"},
117
+ {"start": 4.2, "end": 9.8, "speaker": "Sigma"},
118
+ {"start": 9.8, "end": 13.1, "speaker": "Priya"}]
119
+ ```
120
+
121
+ Audio is 16 kHz mono. Use the literal name `"Sigma"` for the assistant's own
122
+ turns — they form context but are never scored. Speaker ids are **roles, not
123
+ identities**: the assistant is 1, humans are 2, 3, 4… by order of first
124
+ appearance within the conversation. `inference.py` handles that mapping.
125
+
126
+ It is a causal model, so the same code shape works for streaming: encode each
127
+ turn as it ends, keep the last 20 context vectors, classify.
128
+
129
+ The encoder code under `wakeup_model/zipformer/` is vendored from
130
+ [k2-fsa/icefall](https://github.com/k2-fsa/icefall) (Apache-2.0) and torchaudio
131
+ (BSD-2), unmodified. `k2` and `torchaudio` are **not** dependencies: the only
132
+ things needed from them are the Swoosh activations and the Kaldi filterbank,
133
+ both of which are pure PyTorch and included.
134
+
135
+ ## Training
136
+
137
+ Needs the training repo, which carries the data pipeline:
138
+
139
+ ```bash
140
+ python precompute_embeddings.py 'splits=[train,validation,test]' \
141
+ dataset.embedding_cache_dir=.cache/embeddings-zf
142
+ python train.py +experiment=int_wakeup-zipformer_small-ctx20-ft4 \
143
+ dataset.embedding_cache_dir=.cache/embeddings-zf
144
+ ```
145
+
146
+ `training_config.yaml` is that experiment file; `resolved_config.yaml` is the
147
+ exact config this checkpoint was produced with.
148
+
149
+ **The embedding cache must be one your own run built.** It stores the output of
150
+ a randomly-initialised pooling layer, so a cache from a different run is a
151
+ different vector space — the training repo pins the pooling head to the cache
152
+ directory and refuses to mix them.
153
+
154
+ ## Limitations
155
+
156
+ - **`contextual` recall is 0.716**, the weakest of the encoders tried. Follow-ups
157
+ with no wake word are the remaining recall problem.
158
+ - **3.98 false accepts/hour is not low enough for always-on use** — roughly 30
159
+ spurious activations a day in a living room.
160
+ - **Turn segmentation is assumed.** This model sits downstream of VAD and
161
+ diarisation, and their errors land directly on its input. It also cannot
162
+ decide until a turn has ended, so latency is bounded by endpointing.
163
+ - **The corpus is synthetic** — TTS voices over mixed room tone, one generation
164
+ pipeline, English only. Splits are grouped so scenario variants never straddle
165
+ them, but test is still *unseen conversations, same distribution*. Expect
166
+ materially worse numbers on real recordings; treat these as a ceiling.
167
+ - The wake word is the fixed string *"Sigma"*, baked into the training data.
168
+
169
+ ## Citation
170
+
171
+ Dataset and model from TCL Research Europe.
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "encoder_type": "zipformer",
3
+ "zipformer_size": "small",
4
+ "zipformer_pretrained": true,
5
+ "encoder_output_dim": 256,
6
+ "freeze_encoder": true,
7
+ "unfreeze_top_layers": 4,
8
+ "pooling": "attention",
9
+ "max_utterance_seconds": 30.0,
10
+ "min_utterance_seconds": 0.3,
11
+ "num_speakers": 16,
12
+ "speaker_embed_dim": 64,
13
+ "wake_embed_dim": 0,
14
+ "context_dim": 256,
15
+ "context_layers": 4,
16
+ "context_heads": 4,
17
+ "context_ffn_multiplier": 4,
18
+ "context_dropout": 0.1,
19
+ "max_context_turns": 20,
20
+ "num_trigger_types": 3,
21
+ "aux_loss_weight": 0.3,
22
+ "pos_weight": 2.0,
23
+ "label_smoothing": 0.0
24
+ }
context_pooling_head.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a95ec640f007800e67702359c2077c2691e6085ac4d2712bde5d23dc6b96f3da
3
+ size 1172
inference.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Run int_wakeup-zipformer_small-ctx20-ft4 on a conversation.
3
+
4
+ python inference.py session.wav turns.json
5
+
6
+ ``turns.json`` is a list of turns in order, each ``{"start", "end", "speaker"}``
7
+ with the times in seconds and ``speaker`` a **name**. Use the literal name
8
+ ``"Sigma"`` for the assistant's own turns; any stable string will do for the
9
+ humans. Example:
10
+
11
+ [{"start": 0.0, "end": 4.2, "speaker": "Tariq"},
12
+ {"start": 4.2, "end": 9.8, "speaker": "Sigma"},
13
+ {"start": 9.8, "end": 13.1, "speaker": "Priya"}]
14
+
15
+ The script prints, for every human turn, the probability that the assistant
16
+ should respond to it. Assistant turns are not scored — they are part of the
17
+ context, never a thing to trigger on — which is exactly how the model was
18
+ trained.
19
+
20
+ Speaker ids are **roles, not identities**: the assistant is always 1 and humans
21
+ get 2, 3, 4… in order of first appearance, per conversation. Getting this wrong
22
+ does not raise anything, it just quietly degrades the model, so the mapping is
23
+ built here rather than left to the caller.
24
+
25
+ The model is causal — turn *t* sees turns 0..t-1 and never the future — so this
26
+ is also the shape a streaming caller would use: encode each turn as it ends,
27
+ keep the last 20 embeddings, classify.
28
+
29
+ **Two encoders, and they are not interchangeable.** Training fine-tuned the top
30
+ four Zipformer layers for the *current* turn while the *context* turns kept
31
+ coming from a cache built with the frozen encoder, so the model expects that
32
+ asymmetry and this script reproduces it:
33
+
34
+ * current turn → the fine-tuned encoder in ``model.safetensors``
35
+ * context turns → the pristine LibriSpeech Zipformer (downloaded from the Hub on
36
+ first run) plus ``context_pooling_head.safetensors``
37
+
38
+ Encoding everything with the fine-tuned encoder instead — the obvious thing to
39
+ write — does not fail, it just quietly drops validation F1 from 0.896 to 0.718
40
+ and contextual recall from 0.759 to 0.290 on the Whisper model this recipe came
41
+ from. The context embeddings land in a different space than the one the context
42
+ transformer was trained to read.
43
+
44
+ The first run downloads the pretrained Zipformer weights from the Hub, so it
45
+ needs network access; later runs use the local cache.
46
+ """
47
+
48
+ import json
49
+ import sys
50
+
51
+ import soundfile as sf
52
+ import torch
53
+
54
+ from wakeup_model import OfflineWakeupDetector, WakeupModelConfig
55
+
56
+ SAMPLE_RATE = 16_000
57
+ #: Chosen on the validation split; see the model card.
58
+ THRESHOLD = 0.35
59
+ #: Must match dataset_lib/labels.py in the training repo.
60
+ ASSISTANT_NAME = "Sigma"
61
+ SPEAKER_PAD, SPEAKER_ASSISTANT, SPEAKER_FIRST_HUMAN = 0, 1, 2
62
+
63
+
64
+ def speaker_ids(turns: list[dict]) -> list[int]:
65
+ """Map speaker names to the role ids the model was trained with.
66
+
67
+ Args:
68
+ turns: Turns in order, each with a ``speaker`` name.
69
+
70
+ Returns:
71
+ One role id per turn: the assistant is 1, humans are 2, 3, 4… by order
72
+ of first appearance.
73
+ """
74
+ mapping = {ASSISTANT_NAME: SPEAKER_ASSISTANT}
75
+ next_id = SPEAKER_FIRST_HUMAN
76
+ for turn in turns:
77
+ if turn["speaker"] not in mapping:
78
+ mapping[turn["speaker"]] = next_id
79
+ next_id += 1
80
+ return [mapping[t["speaker"]] for t in turns]
81
+
82
+
83
+ def load_models(path: str = ".", device: str = "cpu") -> tuple:
84
+ """Load both encoders — see the module docstring for why there are two.
85
+
86
+ Args:
87
+ path: Directory holding ``config.json``, ``model.safetensors`` and
88
+ ``context_pooling_head.safetensors``.
89
+ device: Torch device.
90
+
91
+ Returns:
92
+ ``(model, context_encoder)``, both in eval mode. ``model`` scores the
93
+ current turn; ``context_encoder`` embeds the history.
94
+ """
95
+ from safetensors.torch import load_file # pylint: disable=import-outside-toplevel
96
+
97
+ with open(f"{path}/config.json", encoding="utf-8") as handle:
98
+ raw = json.load(handle)
99
+
100
+ model = OfflineWakeupDetector(WakeupModelConfig(**raw))
101
+ model.load_state_dict(load_file(f"{path}/model.safetensors"))
102
+
103
+ # The untouched pretrained encoder, plus the pooling head that produced the
104
+ # context embeddings during training. zipformer_pretrained pulls the
105
+ # published icefall weights; unfreeze_top_layers=0 is not a training switch
106
+ # here, it just says this copy is the one training never modified.
107
+ context = OfflineWakeupDetector(
108
+ WakeupModelConfig(**{**raw, "unfreeze_top_layers": 0})
109
+ )
110
+ context.utterance_encoder.pooling.load_state_dict(
111
+ load_file(f"{path}/context_pooling_head.safetensors")
112
+ )
113
+ return model.to(device).eval(), context.utterance_encoder.to(device).eval()
114
+
115
+
116
+ @torch.no_grad()
117
+ def score_conversation( # pylint: disable=too-many-locals
118
+ model, context_encoder, audio, turns, device: str = "cpu"
119
+ ) -> list[float | None]:
120
+ """Score every human turn of one conversation.
121
+
122
+ Every turn is encoded twice, once by each encoder, because a turn is a
123
+ context turn for everything that follows it and the current turn exactly
124
+ once. See the module docstring.
125
+
126
+ Args:
127
+ model: The fine-tuned detector, used for the current turn.
128
+ context_encoder: The frozen encoder, used for the history.
129
+ audio: 1-D float32 waveform at 16 kHz.
130
+ turns: Turns in order, each with ``start``, ``end`` and ``speaker``.
131
+ device: Torch device.
132
+
133
+ Returns:
134
+ One trigger probability per turn, or None for the assistant's own turns.
135
+ """
136
+ config = model.config
137
+ roles = speaker_ids(turns)
138
+
139
+ current_embs, context_embs = [], []
140
+ for turn in turns:
141
+ chunk = audio[int(turn["start"] * SAMPLE_RATE) : int(turn["end"] * SAMPLE_RATE)]
142
+ wav = torch.as_tensor(chunk, dtype=torch.float32, device=device).unsqueeze(0)
143
+ current_embs.append(model.encode_utterance(wav)[0])
144
+ context_embs.append(context_encoder(wav)[0])
145
+
146
+ n_ctx = config.max_context_turns
147
+ scores: list[float | None] = []
148
+ for i, emb in enumerate(current_embs):
149
+ if roles[i] == SPEAKER_ASSISTANT:
150
+ scores.append(None)
151
+ continue
152
+
153
+ # The most recent n_ctx turns before this one, right-aligned so the
154
+ # newest sits last; earlier slots are padding.
155
+ history = context_embs[max(0, i - n_ctx) : i]
156
+ hist_roles = roles[max(0, i - n_ctx) : i]
157
+ start = n_ctx - len(history)
158
+
159
+ ctx = torch.zeros(1, n_ctx, emb.shape[-1], device=device)
160
+ ctx_roles = torch.full((1, n_ctx), SPEAKER_PAD, dtype=torch.long, device=device)
161
+ ctx_mask = torch.ones(1, n_ctx, dtype=torch.bool, device=device) # True = pad
162
+ if history:
163
+ ctx[0, start:] = torch.stack(history)
164
+ ctx_roles[0, start:] = torch.tensor(hist_roles, device=device)
165
+ ctx_mask[0, start:] = False
166
+
167
+ out = model.forward_from_embeddings(
168
+ emb.unsqueeze(0),
169
+ ctx,
170
+ torch.tensor([roles[i]], device=device),
171
+ ctx_roles,
172
+ ctx_mask,
173
+ )
174
+ scores.append(out["trigger_logit"].sigmoid().item())
175
+ return scores
176
+
177
+
178
+ def main() -> None:
179
+ """Score the conversation named on the command line."""
180
+ if len(sys.argv) != 3:
181
+ print(__doc__)
182
+ raise SystemExit(1)
183
+
184
+ audio, rate = sf.read(sys.argv[1], dtype="float32")
185
+ if rate != SAMPLE_RATE:
186
+ raise SystemExit(f"expected {SAMPLE_RATE} Hz audio, got {rate}")
187
+ if audio.ndim > 1:
188
+ audio = audio.mean(axis=1)
189
+
190
+ with open(sys.argv[2], encoding="utf-8") as handle:
191
+ turns = json.load(handle)
192
+
193
+ model, context_encoder = load_models()
194
+ scores = score_conversation(model, context_encoder, audio, turns)
195
+ for turn, score in zip(turns, scores):
196
+ if score is None:
197
+ print(
198
+ f"{turn['start']:7.2f}-{turn['end']:6.2f} {turn['speaker']:<10} "
199
+ f"(assistant, not scored)"
200
+ )
201
+ continue
202
+ flag = "RESPOND" if score > THRESHOLD else ""
203
+ print(
204
+ f"{turn['start']:7.2f}-{turn['end']:6.2f} {turn['speaker']:<10} "
205
+ f"p={score:.4f} {flag}"
206
+ )
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d0cec464cfc414bbf56c8a0e96f5fe1331722095b45c143da9c5e1806d5b319
3
+ size 101304432
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch>=2.1
2
+ transformers>=4.40
3
+ safetensors>=0.4
4
+ huggingface_hub
5
+ soundfile>=0.12
6
+ numpy
resolved_config.yaml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ encoder_type: zipformer
3
+ zipformer_size: small
4
+ zipformer_pretrained: true
5
+ max_utterance_seconds: 30.0
6
+ whisper_model: openai/whisper-base
7
+ encoder_output_dim: 256
8
+ freeze_encoder: true
9
+ unfreeze_top_layers: 4
10
+ pooling: attention
11
+ num_speakers: 16
12
+ speaker_embed_dim: 64
13
+ wake_embed_dim: 0
14
+ context_dim: 256
15
+ context_layers: 4
16
+ context_heads: 4
17
+ context_ffn_multiplier: 4
18
+ context_dropout: 0.1
19
+ max_context_turns: 20
20
+ num_trigger_types: 3
21
+ aux_loss_weight: 0.3
22
+ pos_weight: 2.0
23
+ label_smoothing: 0.0
24
+ dataset:
25
+ repo_id: TCLResearchEurope/intelligent_wakeup
26
+ revision: v1.0.1
27
+ train_split: train
28
+ val_split: validation
29
+ wake_word_source: none
30
+ sample_rate: 16000
31
+ max_context_turns: 20
32
+ session_cache_size: 24
33
+ embedding_cache_dir: /nas/people/marcin.sowanski/intelligent_wakeup/embeddings-zf-small
34
+ training:
35
+ lr: 0.0002
36
+ weight_decay: 0.0001
37
+ grad_clip: 1.0
38
+ num_epochs: 50
39
+ warmup_epochs: 3
40
+ batch_size: 64
41
+ precompute_batch_size: 16
42
+ phase2_batch_size: 8
43
+ num_workers: 4
44
+ phase2_start_epoch: 35
45
+ phase2_lr: 1.0e-05
46
+ checkpoint_dir: /nas/people/marcin.sowanski/intelligent_wakeup/checkpoints/20260914-152410
47
+ log_every_steps: 10
48
+ eval_every_epochs: 1
49
+ keep_best_k: 3
50
+ seed: 42
51
+ device: cuda
52
+ splits: null
53
+ resume_from: null
54
+ checkpoints: null
55
+ checkpoint: null
56
+ from_audio: null
57
+ report_threshold: null
58
+ eval_on: val
training_config.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ #
3
+ # The ctx20-ft4 recipe with a Zipformer encoder in place of Whisper.
4
+ #
5
+ # python train.py +experiment=int_wakeup-zipformer_small-ctx20-ft4
6
+ #
7
+ # Zipformer-small is 22M parameters against whisper-base's 20.6M, so this is a
8
+ # like-for-like swap of the encoder family rather than a capacity change —
9
+ # which is the comparison worth making first. `zipformer_size: medium` (65M) is
10
+ # one line away if small looks promising.
11
+ #
12
+ # Weights are the published icefall LibriSpeech CR-CTC model, pulled from the
13
+ # Hub on first construction. The encoder code is vendored under
14
+ # wakeup_model/zipformer/ — see that package for why k2 is not a dependency.
15
+ #
16
+ # Needs its own embedding cache: the features and the width both differ from
17
+ # every Whisper run.
18
+
19
+ model:
20
+ encoder_type: zipformer
21
+ zipformer_size: small
22
+ # Zipformer2 emits max(encoder_dim); for the small stack that is 256.
23
+ encoder_output_dim: 256
24
+ # Same as the Whisper recipe: the last four encoder layers. Zipformer has 12
25
+ # in six stacks, so this is the last four counting from the output.
26
+ unfreeze_top_layers: 4
27
+ pos_weight: 2.0
28
+
29
+ training:
30
+ num_epochs: 50
31
+ phase2_start_epoch: 35
32
+ phase2_batch_size: 8
33
+
34
+ dataset:
35
+ session_cache_size: 24
wakeup_model/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+ """
5
+
6
+ from .config import WakeupModelConfig
7
+ from .model import OfflineWakeupDetector, forward_batch
8
+
9
+ __all__ = ["OfflineWakeupDetector", "WakeupModelConfig", "forward_batch"]
wakeup_model/config.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass
10
+ class WakeupModelConfig: # pylint: disable=too-many-instance-attributes
11
+ """Hyperparameters for :class:`OfflineWakeupDetector`.
12
+
13
+ Mirrors ``configs/model/default.yaml``; Hydra builds it from that file.
14
+ """
15
+
16
+ # --- Encoder ---
17
+ #: "whisper", "zipformer" or "hubert" — which per-turn encoder to use. Changes the
18
+ #: embedding width and the feature frontend, so a cache and a checkpoint
19
+ #: belong to one setting.
20
+ encoder_type: str = "whisper"
21
+ #: HuBERT checkpoint, when encoder_type is "hubert". Base is 768-d.
22
+ hubert_model: str = "facebook/hubert-base-ls960"
23
+ #: Zipformer stack size, when encoder_type is "zipformer".
24
+ zipformer_size: str = "small"
25
+ #: Start from the published icefall ASR weights rather than random ones.
26
+ zipformer_pretrained: bool = True
27
+ #: Longest utterance the Zipformer encoder looks at, in seconds.
28
+ #:
29
+ #: WhisperFeatureExtractor pads *and truncates* to a fixed 30 s window, so
30
+ #: every Whisper run in this repo only ever saw the first 30 s of a turn.
31
+ #: Zipformer has no such window, so without this it would see more of a long
32
+ #: turn than Whisper did and the comparison would not be like-for-like.
33
+ #:
34
+ #: It is also what keeps memory bounded: cost scales with the longest turn
35
+ #: in the batch, and this corpus has turns up to 97 s against a median of
36
+ #: 5.6 s, so one of them padded a batch of 64 to 9,680 frames and OOM'd a
37
+ #: 24 GB card. Only 0.12% of turns are affected by the cap.
38
+ max_utterance_seconds: float = 30.0
39
+ #: Shortest utterance the Zipformer encoder will encode, in seconds;
40
+ #: anything briefer is zero-padded up to it.
41
+ #:
42
+ #: Conv2dSubsampling needs a minimum number of frames: feed it a 0.006 s
43
+ #: turn and it returns *zero* output frames, so the pooling softmax runs
44
+ #: over an entirely masked row and yields NaN — which then propagates
45
+ #: through every batch that turn appears in as context. The v1.0.1 corpus
46
+ #: has exactly two such turns (one of them zero-length), and they were
47
+ #: enough to make the whole run NaN from epoch 1. Whisper never hit this
48
+ #: because it pads everything to a fixed 30 s window.
49
+ min_utterance_seconds: float = 0.3
50
+
51
+ whisper_model: str = "openai/whisper-base"
52
+ encoder_output_dim: int = 512 # whisper-base hidden dim
53
+ freeze_encoder: bool = True
54
+ # Phase 2: unfreeze top N Whisper encoder layers for fine-tuning
55
+ # whisper-base has 6 layers; whisper-small has 12
56
+ unfreeze_top_layers: int = 0 # 0 = fully frozen; 2-4 = fine-tune top layers
57
+
58
+ # --- Speaker embedding ---
59
+ num_speakers: int = 16 # max distinct speakers + 1 for unknown
60
+ speaker_embed_dim: int = 64
61
+
62
+ # Width of the wake-word presence embedding added to each turn token.
63
+ # 0 disables the feature entirely and restores the original input width.
64
+ wake_embed_dim: int = 0
65
+
66
+ # How frame sequences collapse to one utterance vector:
67
+ # attention - learned softmax over frames (original)
68
+ # mean_max - attention pooling concatenated with max over frames,
69
+ # doubling the output width. Attention averages, so a ~0.5 s
70
+ # keyword inside a 30 s window is diluted; max keeps peaks.
71
+ # Changing this changes the cached embeddings -- use a separate cache dir.
72
+ pooling: str = "attention"
73
+
74
+ @property
75
+ def pooled_dim(self) -> int:
76
+ """Width of one pooled utterance embedding.
77
+
78
+ Not the same as ``encoder_output_dim``: mean_max pooling concatenates
79
+ two vectors, so everything sized by the embedding -- the cache, the
80
+ context transformer's input -- must use this instead.
81
+
82
+ Returns:
83
+ Embedding width after pooling.
84
+ """
85
+ return self.encoder_output_dim * (2 if self.pooling == "mean_max" else 1)
86
+
87
+ # --- Causal context transformer ---
88
+ context_dim: int = 256
89
+ context_layers: int = 4
90
+ context_heads: int = 4
91
+ context_ffn_multiplier: int = 4
92
+ context_dropout: float = 0.1
93
+ max_context_turns: int = 20 # max conversation history kept
94
+
95
+ # --- Classification ---
96
+ # Trigger types: 0=none, 1=direct, 2=contextual
97
+ num_trigger_types: int = 3
98
+
99
+ # --- Training ---
100
+ # Weight for the auxiliary type-classification loss
101
+ aux_loss_weight: float = 0.3
102
+ # Upweight positive (trigger) samples to counter class imbalance (~1:4 ratio)
103
+ pos_weight: float = 4.0
104
+ # Label smoothing for BCE loss (0 = off; e.g. 0.1 prevents overconfident predictions)
105
+ label_smoothing: float = 0.0
wakeup_model/context_transformer.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+ """
5
+
6
+ import torch
7
+ from torch import nn
8
+
9
+ from .config import WakeupModelConfig
10
+
11
+
12
+ class CausalContextTransformer(nn.Module):
13
+ """
14
+ Small transformer that reasons over a sequence of turn tokens (one per utterance).
15
+ Causal masking ensures turn t only attends to turns 0..t — no future leakage.
16
+
17
+ NaN-safety: when a position can only attend to padding positions (e.g. the first
18
+ turn in a conversation has no context history), softmax(-inf, ..., -inf) = NaN.
19
+ We run layers manually and zero-out padding positions after each layer so NaN
20
+ values never propagate as keys into the next layer.
21
+ """
22
+
23
+ def __init__(self, config: WakeupModelConfig):
24
+ super().__init__()
25
+ # pooled_dim, not encoder_output_dim: mean_max pooling concatenates
26
+ # two vectors and doubles the embedding width.
27
+ in_dim = config.pooled_dim + config.speaker_embed_dim + config.wake_embed_dim
28
+
29
+ self.input_proj = nn.Linear(in_dim, config.context_dim)
30
+ self.pos_embedding = nn.Embedding(
31
+ config.max_context_turns + 1, config.context_dim
32
+ )
33
+
34
+ self.layers = nn.ModuleList(
35
+ [
36
+ nn.TransformerEncoderLayer(
37
+ d_model=config.context_dim,
38
+ nhead=config.context_heads,
39
+ dim_feedforward=config.context_dim * config.context_ffn_multiplier,
40
+ dropout=config.context_dropout,
41
+ activation="gelu",
42
+ batch_first=True,
43
+ norm_first=True,
44
+ )
45
+ for _ in range(config.context_layers)
46
+ ]
47
+ )
48
+
49
+ def forward(
50
+ self,
51
+ turn_tokens: torch.Tensor, # (B, T, encoder_dim + speaker_dim)
52
+ padding_mask: torch.Tensor = None, # (B, T) bool, True = pad
53
+ ) -> torch.Tensor: # (B, T, context_dim)
54
+ """Contextualise a sequence of turn tokens.
55
+
56
+ Args:
57
+ turn_tokens: (B, T, encoder_dim + speaker_dim) per-turn features.
58
+ padding_mask: (B, T) bool, True where a slot is padding.
59
+
60
+ Returns:
61
+ (B, T, context_dim) contextualised turns.
62
+ """
63
+ _, n_turns, _ = turn_tokens.shape
64
+
65
+ x = self.input_proj(turn_tokens)
66
+ positions = torch.arange(n_turns, device=x.device).unsqueeze(0)
67
+ x = x + self.pos_embedding(positions)
68
+
69
+ # Zero-out padded inputs so their keys start as 0 not garbage
70
+ if padding_mask is not None:
71
+ x = x.masked_fill(padding_mask.unsqueeze(-1), 0.0)
72
+
73
+ # Bool, not the float mask generate_square_subsequent_mask returns:
74
+ # padding_mask is bool, and torch deprecates mixing the two types on
75
+ # the same call ("Support for mismatched src_key_padding_mask and
76
+ # src_mask is deprecated").
77
+ causal_mask = torch.triu(
78
+ torch.ones(n_turns, n_turns, dtype=torch.bool, device=x.device),
79
+ diagonal=1,
80
+ )
81
+
82
+ for layer in self.layers:
83
+ x = layer(
84
+ x,
85
+ src_mask=causal_mask,
86
+ src_key_padding_mask=padding_mask,
87
+ is_causal=True,
88
+ )
89
+ # Zero-out padded positions after every layer.
90
+ # Padding positions whose entire causal window is masked produce NaN via
91
+ # softmax(-inf,...,-inf). Zeroing here prevents those NaNs becoming keys
92
+ # in the next layer and corrupting non-padded positions.
93
+ if padding_mask is not None:
94
+ x = x.masked_fill(padding_mask.unsqueeze(-1), 0.0)
95
+
96
+ return x
wakeup_model/encoder.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+ """
5
+
6
+ import torch
7
+ from torch import nn
8
+ from transformers import WhisperFeatureExtractor, WhisperModel
9
+
10
+ from .config import WakeupModelConfig
11
+
12
+
13
+ class AttentionPooling(nn.Module):
14
+ """Learnable attention pooling: collapses frame sequence → single utterance vector."""
15
+
16
+ def __init__(self, dim: int, mode: str = "attention"):
17
+ super().__init__()
18
+ self.score = nn.Linear(dim, 1)
19
+ self.mode = mode
20
+
21
+ def forward(
22
+ self,
23
+ hidden_states: torch.Tensor, # (B, T_frames, D)
24
+ padding_mask: torch.Tensor = None, # (B, T_frames) bool, True = pad
25
+ ) -> torch.Tensor: # (B, D)
26
+ """Collapse a frame sequence to one vector by learned attention.
27
+
28
+ Args:
29
+ hidden_states: (B, T_frames, D) encoder output.
30
+ padding_mask: (B, T_frames) bool, True where a frame is padding.
31
+
32
+ Returns:
33
+ (B, D) pooled utterance embedding.
34
+ """
35
+ logits = self.score(hidden_states).squeeze(-1) # (B, T_frames)
36
+ if padding_mask is not None:
37
+ # A row that is entirely padding would be softmax(-inf, ..., -inf),
38
+ # which is NaN, and one NaN embedding poisons every batch the turn
39
+ # appears in as context. Leave such a row unmasked instead: its
40
+ # frames are all padding anyway, so the result is unused, but it
41
+ # stays finite. Reached when an encoder returns zero frames for a
42
+ # degenerately short utterance.
43
+ all_pad = padding_mask.all(dim=-1, keepdim=True)
44
+ logits = logits.masked_fill(padding_mask & ~all_pad, float("-inf"))
45
+ weights = logits.softmax(dim=-1) # (B, T_frames)
46
+ pooled = (weights.unsqueeze(-1) * hidden_states).sum(dim=1) # (B, D)
47
+
48
+ if self.mode != "mean_max":
49
+ return pooled
50
+
51
+ # Attention pooling is a weighted average, so a brief event -- a wake
52
+ # word inside a 30 s window -- is diluted by everything around it. A max
53
+ # over frames keeps the peak instead; the two are complementary.
54
+ masked = hidden_states
55
+ if padding_mask is not None:
56
+ masked = hidden_states.masked_fill(
57
+ (padding_mask & ~all_pad).unsqueeze(-1), float("-inf")
58
+ )
59
+ return torch.cat([pooled, masked.amax(dim=1)], dim=-1) # (B, 2D)
60
+
61
+
62
+ class UtteranceEncoder(nn.Module):
63
+ """
64
+ Whisper encoder + attention pooling → fixed-dim utterance embedding.
65
+
66
+ Whisper is trained with ASR supervision so its encoder representations encode
67
+ both acoustic (phonetics, prosody) and semantic (what was said) content,
68
+ making it more suitable for wakeword + contextual trigger detection than
69
+ self-supervised acoustic-only models.
70
+
71
+ Phase 1 (freeze_encoder=True, unfreeze_top_layers=0):
72
+ All Whisper encoder weights frozen. Used to pre-cache embeddings offline.
73
+ Only the attention pooling layer has gradients.
74
+
75
+ Phase 2 (unfreeze_top_layers > 0):
76
+ Top N Whisper encoder layers unfrozen. Fine-tune with lower LR.
77
+ """
78
+
79
+ def __init__(self, config: WakeupModelConfig):
80
+ super().__init__()
81
+ self.feature_extractor = WhisperFeatureExtractor.from_pretrained(
82
+ config.whisper_model
83
+ )
84
+ whisper = WhisperModel.from_pretrained(config.whisper_model)
85
+ self.encoder = whisper.encoder
86
+ self.num_encoder_layers = len(self.encoder.layers)
87
+ self.pooling = AttentionPooling(config.encoder_output_dim, config.pooling)
88
+ self._apply_freeze(config.freeze_encoder, config.unfreeze_top_layers)
89
+
90
+ def _apply_freeze(self, freeze: bool, unfreeze_top: int) -> None:
91
+ if not freeze:
92
+ return
93
+ for param in self.encoder.parameters():
94
+ param.requires_grad = False
95
+ if unfreeze_top > 0:
96
+ self.unfreeze_top_layers(unfreeze_top)
97
+
98
+ def unfreeze_top_layers(self, n: int) -> None:
99
+ """Call this when transitioning from phase 1 → phase 2."""
100
+ for i in range(self.num_encoder_layers - n, self.num_encoder_layers):
101
+ for param in self.encoder.layers[i].parameters():
102
+ param.requires_grad = True
103
+
104
+ def forward(
105
+ self,
106
+ input_values: torch.Tensor, # (B, T_samples) 16kHz audio
107
+ attention_mask: torch.Tensor = None, # pylint: disable=unused-argument
108
+ ) -> torch.Tensor: # (B, encoder_output_dim)
109
+ """Encode raw waveforms into one embedding each.
110
+
111
+ Args:
112
+ input_values: (B, T_samples) 16 kHz audio.
113
+ attention_mask: Accepted for API compatibility and ignored — the
114
+ feature extractor pads every utterance to a fixed 30 s window.
115
+
116
+ Returns:
117
+ (B, encoder_output_dim) utterance embeddings.
118
+ """
119
+ # Convert raw waveforms → log-mel spectrograms (B, 80, 3000).
120
+ # WhisperFeatureExtractor pads / truncates each utterance to 30 s.
121
+ # Silence frames will produce distinct encoder outputs that the
122
+ # attention pooling learns to downweight automatically.
123
+ features = self.feature_extractor(
124
+ list(input_values.cpu().numpy()),
125
+ sampling_rate=self.feature_extractor.sampling_rate,
126
+ return_tensors="pt",
127
+ )
128
+ input_features = features.input_features.to(
129
+ input_values.device
130
+ ) # (B, 80, 3000)
131
+ outputs = self.encoder(input_features=input_features)
132
+ return self.pooling(outputs.last_hidden_state) # (B, D)
wakeup_model/hubert_encoder.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+
5
+ HuBERT utterance encoder — a self-supervised alternative to the Whisper and
6
+ Zipformer ones.
7
+
8
+ Same contract as the others: waveforms in, one pooled vector per utterance out,
9
+ attention pooling on top, so nothing downstream changes.
10
+
11
+ What makes it a different point in the comparison is the pre-training objective,
12
+ not the size or the shape:
13
+
14
+ * **Whisper** — weakly supervised ASR over web-scale audio. Optimised for *what
15
+ words were said*.
16
+ * **Zipformer** — supervised ASR on LibriSpeech, or audio tagging on AudioSet.
17
+ * **HuBERT** — self-supervised masked prediction over LibriSpeech-960 with no
18
+ transcripts at all. Optimised for *predictable structure in speech*, which
19
+ keeps prosody and speaker/turn-taking cues that an ASR objective has no reason
20
+ to preserve.
21
+
22
+ That last point is the reason to try it here. `direct` turns are a word-spotting
23
+ problem and ASR pre-training already solves them (recall 0.985). `contextual`
24
+ turns — follow-ups with no wake word — have been stuck near 0.76 across every
25
+ encoder tried, and they plausibly depend on exactly the prosodic "is this aimed
26
+ at me" signal a masked-prediction objective is more likely to keep.
27
+
28
+ Like Zipformer and unlike Whisper, it runs on the utterance's real length, so it
29
+ inherits the same window bounds — see ``config.max_utterance_seconds``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import logging
35
+
36
+ import torch
37
+ from torch import nn
38
+ from transformers import AutoFeatureExtractor, HubertModel
39
+
40
+ from .config import WakeupModelConfig
41
+ from .encoder import AttentionPooling
42
+
43
+ log = logging.getLogger(__name__)
44
+
45
+ SAMPLE_RATE = 16_000
46
+
47
+
48
+ class HubertUtteranceEncoder(nn.Module):
49
+ """HuBERT → attention pooling → one vector per utterance.
50
+
51
+ Args:
52
+ config: Model config; ``hubert_model`` names the checkpoint and
53
+ ``encoder_output_dim`` must match its hidden size.
54
+
55
+ Raises:
56
+ ValueError: If the configured output dim does not match the checkpoint.
57
+ """
58
+
59
+ def __init__(self, config: WakeupModelConfig):
60
+ super().__init__()
61
+ self.feature_extractor = AutoFeatureExtractor.from_pretrained(
62
+ config.hubert_model
63
+ )
64
+ self.hubert = HubertModel.from_pretrained(config.hubert_model)
65
+
66
+ hidden = self.hubert.config.hidden_size
67
+ if config.encoder_output_dim != hidden:
68
+ raise ValueError(
69
+ f"{config.hubert_model} is {hidden}-d, but "
70
+ f"model.encoder_output_dim is {config.encoder_output_dim}."
71
+ )
72
+
73
+ self.pooling = AttentionPooling(config.encoder_output_dim, config.pooling)
74
+ self.max_samples = int(config.max_utterance_seconds * SAMPLE_RATE)
75
+ self.min_samples = int(config.min_utterance_seconds * SAMPLE_RATE)
76
+
77
+ # The convolutional front end is always frozen when fine-tuning a
78
+ # wav2vec2-family model: it is a fixed feature extractor and updating it
79
+ # is the documented way to destabilise training.
80
+ self.hubert.feature_extractor._freeze_parameters() # pylint: disable=protected-access
81
+ self._apply_freeze(config.freeze_encoder, config.unfreeze_top_layers)
82
+
83
+ def _apply_freeze(self, freeze: bool, unfreeze_top: int) -> None:
84
+ """Freeze the transformer, optionally leaving the top layers trainable.
85
+
86
+ Args:
87
+ freeze: Whether to freeze at all.
88
+ unfreeze_top: How many of the last layers to leave trainable.
89
+
90
+ Returns:
91
+ None.
92
+ """
93
+ if not freeze:
94
+ return
95
+ for param in self.hubert.parameters():
96
+ param.requires_grad = False
97
+ if unfreeze_top > 0:
98
+ self.unfreeze_top_layers(unfreeze_top)
99
+
100
+ def unfreeze_top_layers(self, n: int) -> None:
101
+ """Unfreeze the last ``n`` transformer layers.
102
+
103
+ Args:
104
+ n: How many layers to unfreeze.
105
+
106
+ Returns:
107
+ None.
108
+ """
109
+ for layer in self.hubert.encoder.layers[-n:]:
110
+ for param in layer.parameters():
111
+ param.requires_grad = True
112
+
113
+ def forward(
114
+ self,
115
+ input_values: torch.Tensor, # (B, T_samples) 16 kHz
116
+ attention_mask: torch.Tensor = None, # (B, T_samples) bool, True = real
117
+ ) -> torch.Tensor: # (B, encoder_output_dim)
118
+ """Encode raw waveforms into one embedding each.
119
+
120
+ Args:
121
+ input_values: (B, T_samples) 16 kHz audio.
122
+ attention_mask: (B, T_samples) bool, True where a sample is real.
123
+
124
+ Returns:
125
+ (B, encoder_output_dim) utterance embeddings.
126
+ """
127
+ device = input_values.device
128
+ lengths = (
129
+ attention_mask.sum(dim=1)
130
+ if attention_mask is not None
131
+ else torch.full(
132
+ (input_values.shape[0],), input_values.shape[1], device=device
133
+ )
134
+ )
135
+
136
+ trimmed = []
137
+ for wav, length in zip(input_values, lengths.tolist()):
138
+ usable = wav[: min(int(length), self.max_samples)]
139
+ if usable.numel() < self.min_samples:
140
+ usable = torch.nn.functional.pad(
141
+ usable, (0, self.min_samples - usable.numel())
142
+ )
143
+ trimmed.append(usable.detach().cpu().numpy())
144
+
145
+ # Ask for the mask explicitly. This checkpoint's extractor defaults to
146
+ # return_attention_mask=False, which is right for the uniform-length
147
+ # batches it was pre-trained on; here the batch is ragged, and without
148
+ # the mask the per-utterance normalisation would take its statistics
149
+ # over the padding too.
150
+ batch = self.feature_extractor(
151
+ trimmed,
152
+ sampling_rate=SAMPLE_RATE,
153
+ return_tensors="pt",
154
+ padding=True,
155
+ return_attention_mask=True,
156
+ )
157
+ values = batch.input_values.to(device)
158
+ mask = batch.attention_mask.to(device)
159
+
160
+ hidden = self.hubert(values, attention_mask=mask).last_hidden_state
161
+
162
+ frame_lens = self.hubert._get_feat_extract_output_lengths( # pylint: disable=protected-access
163
+ mask.sum(dim=-1)
164
+ ).to(
165
+ device
166
+ )
167
+ frames = torch.arange(hidden.shape[1], device=device).unsqueeze(0)
168
+ # AttentionPooling takes True == padding.
169
+ return self.pooling(hidden, frames >= frame_lens.unsqueeze(1))
wakeup_model/model.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+ """
5
+
6
+ import torch
7
+ from torch import nn
8
+ import torch.nn.functional as F
9
+
10
+ from .config import WakeupModelConfig
11
+ from .context_transformer import CausalContextTransformer
12
+ from .encoder import UtteranceEncoder
13
+ from .hubert_encoder import HubertUtteranceEncoder
14
+ from .zipformer_encoder import ZipformerUtteranceEncoder
15
+
16
+
17
+ class OfflineWakeupDetector(nn.Module):
18
+ """
19
+ Offline, turn-level contextual wakeup detector.
20
+
21
+ Decides whether the current utterance should trigger the assistant,
22
+ using both its own acoustic content and the conversational history.
23
+
24
+ Two forward modes:
25
+
26
+ 1. encode_utterance(audio) → embedding
27
+ Pre-compute and cache embeddings for all turns (phase 1 training / inference prep).
28
+
29
+ 2. forward_from_embeddings(context_embs, current_emb, ...) → logits
30
+ Run only the context transformer + heads. Fast inner loop for phase 1 training
31
+ when encoder is fully frozen.
32
+
33
+ 3. forward(current_audio, context_embs, ...) → logits
34
+ Full forward pass. Used for phase 2 (encoder fine-tuning) and inference.
35
+ """
36
+
37
+ # Trigger type indices — keep in sync with dataset labelling
38
+ TYPE_NONE = 0
39
+ TYPE_DIRECT = 1
40
+ TYPE_CONTEXTUAL = 2
41
+
42
+ def __init__(self, config: WakeupModelConfig):
43
+ super().__init__()
44
+ self.config = config
45
+
46
+ encoders = {
47
+ "zipformer": ZipformerUtteranceEncoder,
48
+ "hubert": HubertUtteranceEncoder,
49
+ }
50
+ self.utterance_encoder = encoders.get(config.encoder_type, UtteranceEncoder)(
51
+ config
52
+ )
53
+ self.speaker_embedding = nn.Embedding(
54
+ config.num_speakers,
55
+ config.speaker_embed_dim,
56
+ padding_idx=0, # 0 = unknown/padding speaker
57
+ )
58
+ # Wake-word presence per turn: absent / present. See the note in
59
+ # configs/model/default.yaml -- the frozen encoder loses the keyword,
60
+ # so this hands it to the context transformer directly.
61
+ self.wake_embedding = (
62
+ nn.Embedding(2, config.wake_embed_dim) if config.wake_embed_dim else None
63
+ )
64
+ self.context_transformer = CausalContextTransformer(config)
65
+
66
+ self.trigger_head = nn.Sequential(
67
+ nn.Linear(config.context_dim, config.context_dim // 2),
68
+ nn.GELU(),
69
+ nn.Dropout(config.context_dropout),
70
+ nn.Linear(config.context_dim // 2, 1),
71
+ )
72
+ # Auxiliary head: predicts trigger type (direct / contextual / none)
73
+ # Used as extra training signal; not needed at inference.
74
+ self.type_head = nn.Sequential(
75
+ nn.Linear(config.context_dim, config.context_dim // 2),
76
+ nn.GELU(),
77
+ nn.Dropout(config.context_dropout),
78
+ nn.Linear(config.context_dim // 2, config.num_trigger_types),
79
+ )
80
+
81
+ # ------------------------------------------------------------------
82
+ # Encoding
83
+ # ------------------------------------------------------------------
84
+
85
+ def encode_utterance(
86
+ self,
87
+ audio: torch.Tensor, # (B, T_samples)
88
+ audio_mask: torch.Tensor = None, # (B, T_samples) bool, True = valid
89
+ ) -> torch.Tensor: # (B, encoder_output_dim)
90
+ """Encode one batch of utterances.
91
+
92
+ Args:
93
+ audio: (B, T_samples) 16 kHz waveforms.
94
+ audio_mask: (B, T_samples) bool, True where a sample is real.
95
+
96
+ Returns:
97
+ (B, encoder_output_dim) utterance embeddings.
98
+ """
99
+ return self.utterance_encoder(audio, audio_mask)
100
+
101
+ # ------------------------------------------------------------------
102
+ # Classification (context transformer + heads)
103
+ # ------------------------------------------------------------------
104
+
105
+ def forward_from_embeddings( # pylint: disable=too-many-arguments
106
+ # pylint: disable=too-many-positional-arguments
107
+ self,
108
+ current_emb: torch.Tensor, # (B, encoder_output_dim)
109
+ context_embs: torch.Tensor, # (B, C, encoder_output_dim)
110
+ current_speaker: torch.Tensor, # (B,) int speaker id
111
+ context_speakers: torch.Tensor, # (B, C) int speaker ids
112
+ context_mask: torch.Tensor = None, # (B, C) bool, True = pad (ignore)
113
+ current_wake: torch.Tensor = None, # (B,) int {0, 1}
114
+ context_wakes: torch.Tensor = None, # (B, C) int {0, 1}
115
+ ) -> dict:
116
+ """Classify the current turn from embeddings, skipping the encoder.
117
+
118
+ Args:
119
+ current_emb: (B, encoder_output_dim) current turn.
120
+ context_embs: (B, C, encoder_output_dim) preceding turns.
121
+ current_speaker: (B,) speaker role id of the current turn.
122
+ context_speakers: (B, C) speaker role ids of the context.
123
+ context_mask: (B, C) bool, True where a context slot is padding.
124
+
125
+ Returns:
126
+ Dict with ``trigger_logit`` and ``type_logits``.
127
+ """
128
+ # pylint: disable=too-many-locals
129
+ batch_size = context_embs.shape[0]
130
+
131
+ current_spk = self.speaker_embedding(current_speaker) # (B, spk_dim)
132
+ context_spk = self.speaker_embedding(context_speakers) # (B, C, spk_dim)
133
+
134
+ ctx_parts = [context_embs, context_spk]
135
+ cur_parts = [current_emb, current_spk]
136
+ if self.wake_embedding is not None:
137
+ # Absent when the caller supplies nothing, so a model trained with
138
+ # the feature still runs on batches that lack it.
139
+ zeros_c = context_speakers.new_zeros(context_speakers.shape)
140
+ zeros_b = current_speaker.new_zeros(current_speaker.shape)
141
+ ctx_parts.append(
142
+ self.wake_embedding(zeros_c if context_wakes is None else context_wakes)
143
+ )
144
+ cur_parts.append(
145
+ self.wake_embedding(zeros_b if current_wake is None else current_wake)
146
+ )
147
+
148
+ # Build turn sequence: [context turns ... | current turn]
149
+ ctx_tokens = torch.cat(ctx_parts, dim=-1) # (B, C, D+spk+wake)
150
+ cur_token = torch.cat(cur_parts, dim=-1).unsqueeze(1) # (B, 1, D+spk+wake)
151
+ turn_seq = torch.cat([ctx_tokens, cur_token], dim=1) # (B, C+1, D+spk)
152
+
153
+ # Padding mask: extend context mask with False (current turn is always valid)
154
+ if context_mask is not None:
155
+ cur_valid = context_mask.new_zeros(batch_size, 1)
156
+ full_mask = torch.cat([context_mask, cur_valid], dim=1) # (B, C+1)
157
+ else:
158
+ full_mask = None
159
+
160
+ ctx_out = self.context_transformer(
161
+ turn_seq, padding_mask=full_mask
162
+ ) # (B, C+1, ctx_dim)
163
+
164
+ # Use the last position = current turn's contextualized representation
165
+ current_ctx = ctx_out[:, -1, :] # (B, ctx_dim)
166
+
167
+ return {
168
+ "trigger_logit": self.trigger_head(current_ctx).squeeze(-1), # (B,)
169
+ "type_logits": self.type_head(current_ctx), # (B, num_types)
170
+ }
171
+
172
+ # ------------------------------------------------------------------
173
+ # Full forward (encode + classify)
174
+ # ------------------------------------------------------------------
175
+
176
+ def forward(
177
+ self,
178
+ current_audio: torch.Tensor, # (B, T_samples)
179
+ context_embs: torch.Tensor, # (B, C, encoder_output_dim)
180
+ current_speaker: torch.Tensor, # (B,)
181
+ context_speakers: torch.Tensor, # (B, C)
182
+ context_mask: torch.Tensor = None, # (B, C) bool, True = pad
183
+ audio_mask: torch.Tensor = None, # (B, T_samples) bool, True = valid
184
+ ) -> dict:
185
+ """Encode the current turn and classify it against its context.
186
+
187
+ Args:
188
+ current_audio: (B, T_samples) waveform of the current turn.
189
+ context_embs: (B, C, encoder_output_dim) preceding turns.
190
+ current_speaker: (B,) speaker role id of the current turn.
191
+ context_speakers: (B, C) speaker role ids of the context.
192
+ context_mask: (B, C) bool, True where a context slot is padding.
193
+ audio_mask: (B, T_samples) bool, True where a sample is real.
194
+
195
+ Returns:
196
+ Dict with ``trigger_logit``, ``type_logits`` and the computed
197
+ ``current_embedding``, so callers can cache it without re-encoding.
198
+ """
199
+ # pylint: disable=too-many-arguments,too-many-positional-arguments
200
+ current_emb = self.encode_utterance(current_audio, audio_mask)
201
+ out = self.forward_from_embeddings(
202
+ current_emb, context_embs, current_speaker, context_speakers, context_mask
203
+ )
204
+ # Expose the embedding so callers can cache it without a second encode pass
205
+ out["current_embedding"] = current_emb
206
+ return out
207
+
208
+ # ------------------------------------------------------------------
209
+ # Loss
210
+ # ------------------------------------------------------------------
211
+
212
+ def compute_loss(
213
+ self,
214
+ outputs: dict,
215
+ trigger_labels: torch.Tensor, # (B,) float {0, 1}
216
+ type_labels: torch.Tensor, # (B,) int {0, 1, 2}
217
+ ) -> dict:
218
+ """Binary trigger loss plus the auxiliary trigger-type loss.
219
+
220
+ Args:
221
+ outputs: Model output dict.
222
+ trigger_labels: (B,) float {0, 1} — should the VA respond.
223
+ type_labels: (B,) int {0, 1, 2} — trigger type.
224
+
225
+ Returns:
226
+ Dict with ``loss``, ``trigger_loss`` and ``type_loss``.
227
+ """
228
+ pos_weight = trigger_labels.new_tensor([self.config.pos_weight])
229
+ if self.config.label_smoothing > 0.0:
230
+ s = self.config.label_smoothing
231
+ smooth_labels = trigger_labels * (1.0 - s) + 0.5 * s
232
+ else:
233
+ smooth_labels = trigger_labels
234
+ trigger_loss = F.binary_cross_entropy_with_logits(
235
+ outputs["trigger_logit"], smooth_labels, pos_weight=pos_weight
236
+ )
237
+ type_loss = F.cross_entropy(outputs["type_logits"], type_labels)
238
+
239
+ total = trigger_loss + self.config.aux_loss_weight * type_loss
240
+ return {"loss": total, "trigger_loss": trigger_loss, "type_loss": type_loss}
241
+
242
+ # ------------------------------------------------------------------
243
+ # Utilities
244
+ # ------------------------------------------------------------------
245
+
246
+ def predict(self, outputs: dict, threshold: float = 0.5) -> torch.Tensor:
247
+ """Binary prediction from logits."""
248
+ return (outputs["trigger_logit"].sigmoid() > threshold).long()
249
+
250
+ def parameter_count(self) -> dict:
251
+ """Count parameters.
252
+
253
+ Returns:
254
+ Dict with total and trainable counts, in millions.
255
+ """
256
+ total = sum(p.numel() for p in self.parameters())
257
+ trainable = sum(p.numel() for p in self.parameters() if p.requires_grad)
258
+ return {"total_M": total / 1e6, "trainable_M": trainable / 1e6}
259
+
260
+
261
+ def forward_batch(model: OfflineWakeupDetector, batch: dict, device: torch.device):
262
+ """Run one batch through the model, whichever phase it belongs to.
263
+
264
+ The phase is read off the batch itself: ``current_embedding`` means the
265
+ encoder is frozen and the current turn came from the cache (Phase 1),
266
+ ``current_audio`` means it runs with gradient (Phase 2).
267
+
268
+ Args:
269
+ model: The detector.
270
+ batch: A collated batch.
271
+ device: Device to move tensors to.
272
+
273
+ Returns:
274
+ The model's output dict.
275
+ """
276
+ context_embs = batch["context_embeddings"].to(device)
277
+ context_spks = batch["context_speakers"].to(device)
278
+ context_mask = batch["context_mask"].to(device)
279
+ current_spk = batch["current_speaker_id"].to(device)
280
+
281
+ wake = batch.get("current_wake")
282
+ wakes = batch.get("context_wakes")
283
+ if wake is not None:
284
+ wake, wakes = wake.to(device), wakes.to(device)
285
+
286
+ if "current_embedding" in batch:
287
+ return model.forward_from_embeddings(
288
+ batch["current_embedding"].to(device),
289
+ context_embs,
290
+ current_spk,
291
+ context_spks,
292
+ context_mask,
293
+ wake,
294
+ wakes,
295
+ )
296
+
297
+ audio_mask = batch.get("audio_mask")
298
+ if audio_mask is not None:
299
+ audio_mask = audio_mask.to(device)
300
+ return model.forward(
301
+ batch["current_audio"].to(device),
302
+ context_embs,
303
+ current_spk,
304
+ context_spks,
305
+ context_mask,
306
+ audio_mask,
307
+ )
wakeup_model/zipformer/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zipformer encoder, vendored from k2-fsa/icefall (Apache-2.0).
3
+
4
+ ``zipformer.py``, ``scaling.py``, ``subsampling.py`` and
5
+ ``encoder_interface.py`` are copied verbatim from
6
+ ``egs/librispeech/ASR/zipformer/`` so they can be refreshed by re-copying; the
7
+ only local code is ``_shims.py``, which stands in for the ``k2`` and
8
+ ``icefall`` imports. See that module for why.
9
+
10
+ Those files import each other by bare module name (``from scaling import ...``),
11
+ which only resolves when their directory is on ``sys.path`` — so this package
12
+ puts it there rather than rewriting the vendored source.
13
+ """
14
+
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from . import _shims
19
+
20
+ _shims.install()
21
+ sys.path.insert(0, str(Path(__file__).parent))
22
+
23
+ from zipformer import Zipformer2 # noqa: E402 pylint: disable=wrong-import-position
24
+ from subsampling import (
25
+ Conv2dSubsampling,
26
+ ) # noqa: E402 pylint: disable=wrong-import-position
27
+
28
+ from .kaldi import fbank # noqa: E402 pylint: disable=wrong-import-position
29
+
30
+ __all__ = ["Zipformer2", "Conv2dSubsampling", "fbank"]
wakeup_model/zipformer/_shims.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The two things icefall's Zipformer imports that we do not want to depend on.
3
+
4
+ ``zipformer.py``, ``scaling.py`` and ``subsampling.py`` are vendored verbatim
5
+ from k2-fsa/icefall (Apache-2.0) so they can be updated by re-copying. They
6
+ import two things this repo has no use for:
7
+
8
+ * **k2** — used only for the Swoosh activations, and only as a speed
9
+ optimisation. The pure-PyTorch formulas are in those same files, in the
10
+ ``torch.jit.is_scripting()`` branch right above each k2 call, so they are
11
+ reproduced here rather than taking on a dependency that needs building from
12
+ source against a matching CUDA.
13
+ * **icefall.utils.torch_autocast** — a thin wrapper over ``torch.amp.autocast``.
14
+
15
+ ``kaldi.py`` is vendored the same way, from torchaudio (BSD-2), for the
16
+ Kaldi-compatible filterbank features the pretrained weights expect. torchaudio
17
+ itself is not a dependency: its wheel carries a C++ extension pinned to one
18
+ torch build, which fails to load against both the torch here and the newer one
19
+ on the cluster, while the ``compliance.kaldi`` module it contains is pure
20
+ PyTorch. Its single use of ``torchaudio.functional.create_dct`` is on the MFCC
21
+ path, not the filterbank one, and is stubbed below so the file stays a verbatim
22
+ copy.
23
+
24
+ Installed into ``sys.modules`` by this package's ``__init__``, before the
25
+ vendored files are imported.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ import sys
32
+ import types
33
+ from contextlib import contextmanager
34
+
35
+ import torch
36
+ from torch import Tensor
37
+
38
+
39
+ def swoosh_l(x: Tensor) -> Tensor:
40
+ """Swoosh-L activation.
41
+
42
+ Args:
43
+ x: Input tensor.
44
+
45
+ Returns:
46
+ ``log(1 + exp(x - 4)) - 0.08 x - 0.035``.
47
+ """
48
+ zero = torch.zeros((), dtype=x.dtype, device=x.device)
49
+ return torch.logaddexp(zero, x - 4.0) - 0.08 * x - 0.035
50
+
51
+
52
+ def swoosh_r(x: Tensor) -> Tensor:
53
+ """Swoosh-R activation.
54
+
55
+ Args:
56
+ x: Input tensor.
57
+
58
+ Returns:
59
+ ``log(1 + exp(x - 1)) - 0.08 x - 0.313261687``.
60
+ """
61
+ zero = torch.zeros((), dtype=x.dtype, device=x.device)
62
+ return torch.logaddexp(zero, x - 1.0) - 0.08 * x - 0.313261687
63
+
64
+
65
+ def swoosh_l_forward_and_deriv(x: Tensor) -> tuple[Tensor, Tensor]:
66
+ """Swoosh-L and its derivative.
67
+
68
+ Args:
69
+ x: Input tensor.
70
+
71
+ Returns:
72
+ ``(value, d value / d x)``.
73
+ """
74
+ return swoosh_l(x), torch.sigmoid(x - 4.0) - 0.08
75
+
76
+
77
+ def swoosh_r_forward_and_deriv(x: Tensor) -> tuple[Tensor, Tensor]:
78
+ """Swoosh-R and its derivative.
79
+
80
+ Args:
81
+ x: Input tensor.
82
+
83
+ Returns:
84
+ ``(value, d value / d x)``.
85
+ """
86
+ return swoosh_r(x), torch.sigmoid(x - 1.0) - 0.08
87
+
88
+
89
+ def create_dct(n_mfcc: int, n_mels: int, norm: str | None) -> Tensor:
90
+ """Orthonormal DCT-II matrix — stands in for ``torchaudio.functional``.
91
+
92
+ Only the MFCC path in the vendored ``kaldi.py`` calls this; filterbank
93
+ features do not. Implemented rather than stubbed so the vendored file stays
94
+ usable as written.
95
+
96
+ Args:
97
+ n_mfcc: Number of output coefficients.
98
+ n_mels: Number of mel bins.
99
+ norm: ``"ortho"`` for the orthonormal scaling, else None.
100
+
101
+ Returns:
102
+ (n_mels, n_mfcc) transform matrix.
103
+ """
104
+ n = torch.arange(float(n_mels))
105
+ k = torch.arange(float(n_mfcc)).unsqueeze(1)
106
+ dct = torch.cos(torch.pi / float(n_mels) * (n + 0.5) * k)
107
+ if norm is None:
108
+ dct *= 2.0
109
+ else:
110
+ dct[0] *= 1.0 / math.sqrt(2.0)
111
+ dct *= math.sqrt(2.0 / float(n_mels))
112
+ return dct.t()
113
+
114
+
115
+ @contextmanager
116
+ def torch_autocast(*args, **kwargs):
117
+ """Stand-in for ``icefall.utils.torch_autocast``.
118
+
119
+ Args:
120
+ *args: Passed through to ``torch.amp.autocast``.
121
+ **kwargs: Passed through; ``device_type`` defaults to cuda.
122
+
123
+ Yields:
124
+ None, inside the autocast context.
125
+ """
126
+ kwargs.setdefault("device_type", "cuda")
127
+ with torch.amp.autocast(*args, **kwargs):
128
+ yield
129
+
130
+
131
+ def install() -> None:
132
+ """Put the fake ``k2`` and ``icefall`` modules into ``sys.modules``.
133
+
134
+ Returns:
135
+ None.
136
+ """
137
+ if "k2" not in sys.modules:
138
+ k2 = types.ModuleType("k2")
139
+ k2.swoosh_l = swoosh_l
140
+ k2.swoosh_r = swoosh_r
141
+ # The no-grad variants differ only in that k2 skips saving state.
142
+ k2.swoosh_l_forward = swoosh_l
143
+ k2.swoosh_r_forward = swoosh_r
144
+ k2.swoosh_l_forward_and_deriv = swoosh_l_forward_and_deriv
145
+ k2.swoosh_r_forward_and_deriv = swoosh_r_forward_and_deriv
146
+ sys.modules["k2"] = k2
147
+
148
+ if "torchaudio" not in sys.modules:
149
+ torchaudio = types.ModuleType("torchaudio")
150
+ functional = types.ModuleType("torchaudio.functional")
151
+ functional.create_dct = create_dct
152
+ torchaudio.functional = functional
153
+ sys.modules["torchaudio"] = torchaudio
154
+ sys.modules["torchaudio.functional"] = functional
155
+
156
+ if "icefall" not in sys.modules:
157
+ icefall = types.ModuleType("icefall")
158
+ utils = types.ModuleType("icefall.utils")
159
+ utils.torch_autocast = torch_autocast
160
+ icefall.utils = utils
161
+ sys.modules["icefall"] = icefall
162
+ sys.modules["icefall.utils"] = utils
wakeup_model/zipformer/encoder_interface.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
2
+ #
3
+ # See ../../../../LICENSE for clarification regarding multiple authors
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from typing import Tuple
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+
23
+ class EncoderInterface(nn.Module):
24
+ def forward(
25
+ self, x: torch.Tensor, x_lens: torch.Tensor
26
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
27
+ """
28
+ Args:
29
+ x:
30
+ A tensor of shape (batch_size, input_seq_len, num_features)
31
+ containing the input features.
32
+ x_lens:
33
+ A tensor of shape (batch_size,) containing the number of frames
34
+ in `x` before padding.
35
+ Returns:
36
+ Return a tuple containing two tensors:
37
+ - encoder_out, a tensor of (batch_size, out_seq_len, output_dim)
38
+ containing unnormalized probabilities, i.e., the output of a
39
+ linear layer.
40
+ - encoder_out_lens, a tensor of shape (batch_size,) containing
41
+ the number of frames in `encoder_out` before padding.
42
+ """
43
+ raise NotImplementedError("Please implement it in a subclass")
wakeup_model/zipformer/kaldi.py ADDED
@@ -0,0 +1,907 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ import torchaudio
6
+ from torch import Tensor
7
+
8
+ __all__ = [
9
+ "get_mel_banks",
10
+ "inverse_mel_scale",
11
+ "inverse_mel_scale_scalar",
12
+ "mel_scale",
13
+ "mel_scale_scalar",
14
+ "spectrogram",
15
+ "fbank",
16
+ "mfcc",
17
+ "vtln_warp_freq",
18
+ "vtln_warp_mel_freq",
19
+ ]
20
+
21
+ # numeric_limits<float>::epsilon() 1.1920928955078125e-07
22
+ EPSILON = torch.tensor(torch.finfo(torch.float).eps)
23
+ # 1 milliseconds = 0.001 seconds
24
+ MILLISECONDS_TO_SECONDS = 0.001
25
+
26
+ # window types
27
+ HAMMING = "hamming"
28
+ HANNING = "hanning"
29
+ POVEY = "povey"
30
+ RECTANGULAR = "rectangular"
31
+ BLACKMAN = "blackman"
32
+ WINDOWS = [HAMMING, HANNING, POVEY, RECTANGULAR, BLACKMAN]
33
+
34
+
35
+ def _get_epsilon(device, dtype):
36
+ return EPSILON.to(device=device, dtype=dtype)
37
+
38
+
39
+ def _next_power_of_2(x: int) -> int:
40
+ r"""Returns the smallest power of 2 that is greater than x"""
41
+ return 1 if x == 0 else 2 ** (x - 1).bit_length()
42
+
43
+
44
+ def _get_strided(
45
+ waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool
46
+ ) -> Tensor:
47
+ r"""Given a waveform (1D tensor of size ``num_samples``), it returns a 2D tensor (m, ``window_size``)
48
+ representing how the window is shifted along the waveform. Each row is a frame.
49
+
50
+ Args:
51
+ waveform (Tensor): Tensor of size ``num_samples``
52
+ window_size (int): Frame length
53
+ window_shift (int): Frame shift
54
+ snip_edges (bool): If True, end effects will be handled by outputting only frames that completely fit
55
+ in the file, and the number of frames depends on the frame_length. If False, the number of frames
56
+ depends only on the frame_shift, and we reflect the data at the ends.
57
+
58
+ Returns:
59
+ Tensor: 2D tensor of size (m, ``window_size``) where each row is a frame
60
+ """
61
+ assert waveform.dim() == 1
62
+ num_samples = waveform.size(0)
63
+ strides = (window_shift * waveform.stride(0), waveform.stride(0))
64
+
65
+ if snip_edges:
66
+ if num_samples < window_size:
67
+ return torch.empty((0, 0), dtype=waveform.dtype, device=waveform.device)
68
+ else:
69
+ m = 1 + (num_samples - window_size) // window_shift
70
+ else:
71
+ reversed_waveform = torch.flip(waveform, [0])
72
+ m = (num_samples + (window_shift // 2)) // window_shift
73
+ pad = window_size // 2 - window_shift // 2
74
+ pad_right = reversed_waveform
75
+ if pad > 0:
76
+ # torch.nn.functional.pad returns [2,1,0,1,2] for 'reflect'
77
+ # but we want [2, 1, 0, 0, 1, 2]
78
+ pad_left = reversed_waveform[-pad:]
79
+ waveform = torch.cat((pad_left, waveform, pad_right), dim=0)
80
+ else:
81
+ # pad is negative so we want to trim the waveform at the front
82
+ waveform = torch.cat((waveform[-pad:], pad_right), dim=0)
83
+
84
+ sizes = (m, window_size)
85
+ return waveform.as_strided(sizes, strides)
86
+
87
+
88
+ def _feature_window_function(
89
+ window_type: str,
90
+ window_size: int,
91
+ blackman_coeff: float,
92
+ device: torch.device,
93
+ dtype: int,
94
+ ) -> Tensor:
95
+ r"""Returns a window function with the given type and size"""
96
+ if window_type == HANNING:
97
+ return torch.hann_window(
98
+ window_size, periodic=False, device=device, dtype=dtype
99
+ )
100
+ elif window_type == HAMMING:
101
+ return torch.hamming_window(
102
+ window_size,
103
+ periodic=False,
104
+ alpha=0.54,
105
+ beta=0.46,
106
+ device=device,
107
+ dtype=dtype,
108
+ )
109
+ elif window_type == POVEY:
110
+ # like hanning but goes to zero at edges
111
+ return torch.hann_window(
112
+ window_size, periodic=False, device=device, dtype=dtype
113
+ ).pow(0.85)
114
+ elif window_type == RECTANGULAR:
115
+ return torch.ones(window_size, device=device, dtype=dtype)
116
+ elif window_type == BLACKMAN:
117
+ a = 2 * math.pi / (window_size - 1)
118
+ window_function = torch.arange(window_size, device=device, dtype=dtype)
119
+ # can't use torch.blackman_window as they use different coefficients
120
+ return (
121
+ blackman_coeff
122
+ - 0.5 * torch.cos(a * window_function)
123
+ + (0.5 - blackman_coeff) * torch.cos(2 * a * window_function)
124
+ ).to(device=device, dtype=dtype)
125
+ else:
126
+ raise Exception("Invalid window type " + window_type)
127
+
128
+
129
+ def _get_log_energy(
130
+ strided_input: Tensor, epsilon: Tensor, energy_floor: float
131
+ ) -> Tensor:
132
+ r"""Returns the log energy of size (m) for a strided_input (m,*)"""
133
+ device, dtype = strided_input.device, strided_input.dtype
134
+ log_energy = torch.max(strided_input.pow(2).sum(1), epsilon).log() # size (m)
135
+ if energy_floor == 0.0:
136
+ return log_energy
137
+ return torch.max(
138
+ log_energy, torch.tensor(math.log(energy_floor), device=device, dtype=dtype)
139
+ )
140
+
141
+
142
+ def _get_waveform_and_window_properties(
143
+ waveform: Tensor,
144
+ channel: int,
145
+ sample_frequency: float,
146
+ frame_shift: float,
147
+ frame_length: float,
148
+ round_to_power_of_two: bool,
149
+ preemphasis_coefficient: float,
150
+ ) -> Tuple[Tensor, int, int, int]:
151
+ r"""Gets the waveform and window properties"""
152
+ channel = max(channel, 0)
153
+ assert channel < waveform.size(0), "Invalid channel {} for size {}".format(
154
+ channel, waveform.size(0)
155
+ )
156
+ waveform = waveform[channel, :] # size (n)
157
+ window_shift = int(sample_frequency * frame_shift * MILLISECONDS_TO_SECONDS)
158
+ window_size = int(sample_frequency * frame_length * MILLISECONDS_TO_SECONDS)
159
+ padded_window_size = (
160
+ _next_power_of_2(window_size) if round_to_power_of_two else window_size
161
+ )
162
+
163
+ assert (
164
+ 2 <= window_size <= len(waveform)
165
+ ), "choose a window size {} that is [2, {}]".format(window_size, len(waveform))
166
+ assert 0 < window_shift, "`window_shift` must be greater than 0"
167
+ assert padded_window_size % 2 == 0, (
168
+ "the padded `window_size` must be divisible by two."
169
+ " use `round_to_power_of_two` or change `frame_length`"
170
+ )
171
+ assert (
172
+ 0.0 <= preemphasis_coefficient <= 1.0
173
+ ), "`preemphasis_coefficient` must be between [0,1]"
174
+ assert sample_frequency > 0, "`sample_frequency` must be greater than zero"
175
+ return waveform, window_shift, window_size, padded_window_size
176
+
177
+
178
+ def _get_window(
179
+ waveform: Tensor,
180
+ padded_window_size: int,
181
+ window_size: int,
182
+ window_shift: int,
183
+ window_type: str,
184
+ blackman_coeff: float,
185
+ snip_edges: bool,
186
+ raw_energy: bool,
187
+ energy_floor: float,
188
+ dither: float,
189
+ remove_dc_offset: bool,
190
+ preemphasis_coefficient: float,
191
+ ) -> Tuple[Tensor, Tensor]:
192
+ r"""Gets a window and its log energy
193
+
194
+ Returns:
195
+ (Tensor, Tensor): strided_input of size (m, ``padded_window_size``) and signal_log_energy of size (m)
196
+ """
197
+ device, dtype = waveform.device, waveform.dtype
198
+ epsilon = _get_epsilon(device, dtype)
199
+
200
+ # size (m, window_size)
201
+ strided_input = _get_strided(waveform, window_size, window_shift, snip_edges)
202
+
203
+ if dither != 0.0:
204
+ rand_gauss = torch.randn(strided_input.shape, device=device, dtype=dtype)
205
+ strided_input = strided_input + rand_gauss * dither
206
+
207
+ if remove_dc_offset:
208
+ # Subtract each row/frame by its mean
209
+ row_means = torch.mean(strided_input, dim=1).unsqueeze(1) # size (m, 1)
210
+ strided_input = strided_input - row_means
211
+
212
+ if raw_energy:
213
+ # Compute the log energy of each row/frame before applying preemphasis and
214
+ # window function
215
+ signal_log_energy = _get_log_energy(
216
+ strided_input, epsilon, energy_floor
217
+ ) # size (m)
218
+
219
+ if preemphasis_coefficient != 0.0:
220
+ # strided_input[i,j] -= preemphasis_coefficient * strided_input[i, max(0, j-1)] for all i,j
221
+ offset_strided_input = torch.nn.functional.pad(
222
+ strided_input.unsqueeze(0), (1, 0), mode="replicate"
223
+ ).squeeze(
224
+ 0
225
+ ) # size (m, window_size + 1)
226
+ strided_input = (
227
+ strided_input - preemphasis_coefficient * offset_strided_input[:, :-1]
228
+ )
229
+
230
+ # Apply window_function to each row/frame
231
+ window_function = _feature_window_function(
232
+ window_type, window_size, blackman_coeff, device, dtype
233
+ ).unsqueeze(
234
+ 0
235
+ ) # size (1, window_size)
236
+ strided_input = strided_input * window_function # size (m, window_size)
237
+
238
+ # Pad columns with zero until we reach size (m, padded_window_size)
239
+ if padded_window_size != window_size:
240
+ padding_right = padded_window_size - window_size
241
+ strided_input = torch.nn.functional.pad(
242
+ strided_input.unsqueeze(0), (0, padding_right), mode="constant", value=0
243
+ ).squeeze(0)
244
+
245
+ # Compute energy after window function (not the raw one)
246
+ if not raw_energy:
247
+ signal_log_energy = _get_log_energy(
248
+ strided_input, epsilon, energy_floor
249
+ ) # size (m)
250
+
251
+ return strided_input, signal_log_energy
252
+
253
+
254
+ def _subtract_column_mean(tensor: Tensor, subtract_mean: bool) -> Tensor:
255
+ # subtracts the column mean of the tensor size (m, n) if subtract_mean=True
256
+ # it returns size (m, n)
257
+ if subtract_mean:
258
+ col_means = torch.mean(tensor, dim=0).unsqueeze(0)
259
+ tensor = tensor - col_means
260
+ return tensor
261
+
262
+
263
+ def spectrogram(
264
+ waveform: Tensor,
265
+ blackman_coeff: float = 0.42,
266
+ channel: int = -1,
267
+ dither: float = 0.0,
268
+ energy_floor: float = 1.0,
269
+ frame_length: float = 25.0,
270
+ frame_shift: float = 10.0,
271
+ min_duration: float = 0.0,
272
+ preemphasis_coefficient: float = 0.97,
273
+ raw_energy: bool = True,
274
+ remove_dc_offset: bool = True,
275
+ round_to_power_of_two: bool = True,
276
+ sample_frequency: float = 16000.0,
277
+ snip_edges: bool = True,
278
+ subtract_mean: bool = False,
279
+ window_type: str = POVEY,
280
+ ) -> Tensor:
281
+ r"""Create a spectrogram from a raw audio signal. This matches the input/output of Kaldi's
282
+ compute-spectrogram-feats.
283
+
284
+ Args:
285
+ waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
286
+ blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
287
+ channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
288
+ dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
289
+ the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
290
+ energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
291
+ this floor is applied to the zeroth component, representing the total signal energy. The floor on the
292
+ individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
293
+ frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
294
+ frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
295
+ min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
296
+ preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
297
+ raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
298
+ remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
299
+ round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
300
+ to FFT. (Default: ``True``)
301
+ sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
302
+ specified there) (Default: ``16000.0``)
303
+ snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
304
+ in the file, and the number of frames depends on the frame_length. If False, the number of frames
305
+ depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
306
+ subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
307
+ it this way. (Default: ``False``)
308
+ window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
309
+ (Default: ``'povey'``)
310
+
311
+ Returns:
312
+ Tensor: A spectrogram identical to what Kaldi would output. The shape is
313
+ (m, ``padded_window_size // 2 + 1``) where m is calculated in _get_strided
314
+ """
315
+ device, dtype = waveform.device, waveform.dtype
316
+ epsilon = _get_epsilon(device, dtype)
317
+
318
+ waveform, window_shift, window_size, padded_window_size = (
319
+ _get_waveform_and_window_properties(
320
+ waveform,
321
+ channel,
322
+ sample_frequency,
323
+ frame_shift,
324
+ frame_length,
325
+ round_to_power_of_two,
326
+ preemphasis_coefficient,
327
+ )
328
+ )
329
+
330
+ if len(waveform) < min_duration * sample_frequency:
331
+ # signal is too short
332
+ return torch.empty(0)
333
+
334
+ strided_input, signal_log_energy = _get_window(
335
+ waveform,
336
+ padded_window_size,
337
+ window_size,
338
+ window_shift,
339
+ window_type,
340
+ blackman_coeff,
341
+ snip_edges,
342
+ raw_energy,
343
+ energy_floor,
344
+ dither,
345
+ remove_dc_offset,
346
+ preemphasis_coefficient,
347
+ )
348
+
349
+ # size (m, padded_window_size // 2 + 1, 2)
350
+ fft = torch.fft.rfft(strided_input)
351
+
352
+ # Convert the FFT into a power spectrum
353
+ power_spectrum = torch.max(
354
+ fft.abs().pow(2.0), epsilon
355
+ ).log() # size (m, padded_window_size // 2 + 1)
356
+ power_spectrum[:, 0] = signal_log_energy
357
+
358
+ power_spectrum = _subtract_column_mean(power_spectrum, subtract_mean)
359
+ return power_spectrum
360
+
361
+
362
+ def inverse_mel_scale_scalar(mel_freq: float) -> float:
363
+ return 700.0 * (math.exp(mel_freq / 1127.0) - 1.0)
364
+
365
+
366
+ def inverse_mel_scale(mel_freq: Tensor) -> Tensor:
367
+ return 700.0 * ((mel_freq / 1127.0).exp() - 1.0)
368
+
369
+
370
+ def mel_scale_scalar(freq: float) -> float:
371
+ return 1127.0 * math.log(1.0 + freq / 700.0)
372
+
373
+
374
+ def mel_scale(freq: Tensor) -> Tensor:
375
+ return 1127.0 * (1.0 + freq / 700.0).log()
376
+
377
+
378
+ def vtln_warp_freq(
379
+ vtln_low_cutoff: float,
380
+ vtln_high_cutoff: float,
381
+ low_freq: float,
382
+ high_freq: float,
383
+ vtln_warp_factor: float,
384
+ freq: Tensor,
385
+ ) -> Tensor:
386
+ r"""This computes a VTLN warping function that is not the same as HTK's one,
387
+ but has similar inputs (this function has the advantage of never producing
388
+ empty bins).
389
+
390
+ This function computes a warp function F(freq), defined between low_freq
391
+ and high_freq inclusive, with the following properties:
392
+ F(low_freq) == low_freq
393
+ F(high_freq) == high_freq
394
+ The function is continuous and piecewise linear with two inflection
395
+ points.
396
+ The lower inflection point (measured in terms of the unwarped
397
+ frequency) is at frequency l, determined as described below.
398
+ The higher inflection point is at a frequency h, determined as
399
+ described below.
400
+ If l <= f <= h, then F(f) = f/vtln_warp_factor.
401
+ If the higher inflection point (measured in terms of the unwarped
402
+ frequency) is at h, then max(h, F(h)) == vtln_high_cutoff.
403
+ Since (by the last point) F(h) == h/vtln_warp_factor, then
404
+ max(h, h/vtln_warp_factor) == vtln_high_cutoff, so
405
+ h = vtln_high_cutoff / max(1, 1/vtln_warp_factor).
406
+ = vtln_high_cutoff * min(1, vtln_warp_factor).
407
+ If the lower inflection point (measured in terms of the unwarped
408
+ frequency) is at l, then min(l, F(l)) == vtln_low_cutoff
409
+ This implies that l = vtln_low_cutoff / min(1, 1/vtln_warp_factor)
410
+ = vtln_low_cutoff * max(1, vtln_warp_factor)
411
+ Args:
412
+ vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
413
+ vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
414
+ low_freq (float): Lower frequency cutoffs in mel computation
415
+ high_freq (float): Upper frequency cutoffs in mel computation
416
+ vtln_warp_factor (float): Vtln warp factor
417
+ freq (Tensor): given frequency in Hz
418
+
419
+ Returns:
420
+ Tensor: Freq after vtln warp
421
+ """
422
+ assert (
423
+ vtln_low_cutoff > low_freq
424
+ ), "be sure to set the vtln_low option higher than low_freq"
425
+ assert (
426
+ vtln_high_cutoff < high_freq
427
+ ), "be sure to set the vtln_high option lower than high_freq [or negative]"
428
+ l = vtln_low_cutoff * max(1.0, vtln_warp_factor)
429
+ h = vtln_high_cutoff * min(1.0, vtln_warp_factor)
430
+ scale = 1.0 / vtln_warp_factor
431
+ Fl = scale * l # F(l)
432
+ Fh = scale * h # F(h)
433
+ assert l > low_freq and h < high_freq
434
+ # slope of left part of the 3-piece linear function
435
+ scale_left = (Fl - low_freq) / (l - low_freq)
436
+ # [slope of center part is just "scale"]
437
+
438
+ # slope of right part of the 3-piece linear function
439
+ scale_right = (high_freq - Fh) / (high_freq - h)
440
+
441
+ res = torch.empty_like(freq)
442
+
443
+ outside_low_high_freq = torch.lt(freq, low_freq) | torch.gt(
444
+ freq, high_freq
445
+ ) # freq < low_freq || freq > high_freq
446
+ before_l = torch.lt(freq, l) # freq < l
447
+ before_h = torch.lt(freq, h) # freq < h
448
+ after_h = torch.ge(freq, h) # freq >= h
449
+
450
+ # order of operations matter here (since there is overlapping frequency regions)
451
+ res[after_h] = high_freq + scale_right * (freq[after_h] - high_freq)
452
+ res[before_h] = scale * freq[before_h]
453
+ res[before_l] = low_freq + scale_left * (freq[before_l] - low_freq)
454
+ res[outside_low_high_freq] = freq[outside_low_high_freq]
455
+
456
+ return res
457
+
458
+
459
+ def vtln_warp_mel_freq(
460
+ vtln_low_cutoff: float,
461
+ vtln_high_cutoff: float,
462
+ low_freq,
463
+ high_freq: float,
464
+ vtln_warp_factor: float,
465
+ mel_freq: Tensor,
466
+ ) -> Tensor:
467
+ r"""
468
+ Args:
469
+ vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
470
+ vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
471
+ low_freq (float): Lower frequency cutoffs in mel computation
472
+ high_freq (float): Upper frequency cutoffs in mel computation
473
+ vtln_warp_factor (float): Vtln warp factor
474
+ mel_freq (Tensor): Given frequency in Mel
475
+
476
+ Returns:
477
+ Tensor: ``mel_freq`` after vtln warp
478
+ """
479
+ return mel_scale(
480
+ vtln_warp_freq(
481
+ vtln_low_cutoff,
482
+ vtln_high_cutoff,
483
+ low_freq,
484
+ high_freq,
485
+ vtln_warp_factor,
486
+ inverse_mel_scale(mel_freq),
487
+ )
488
+ )
489
+
490
+
491
+ def get_mel_banks(
492
+ num_bins: int,
493
+ window_length_padded: int,
494
+ sample_freq: float,
495
+ low_freq: float,
496
+ high_freq: float,
497
+ vtln_low: float,
498
+ vtln_high: float,
499
+ vtln_warp_factor: float,
500
+ ) -> Tuple[Tensor, Tensor]:
501
+ """
502
+ Returns:
503
+ (Tensor, Tensor): The tuple consists of ``bins`` (which is
504
+ melbank of size (``num_bins``, ``num_fft_bins``)) and ``center_freqs`` (which is
505
+ center frequencies of bins of size (``num_bins``)).
506
+ """
507
+ assert num_bins > 3, "Must have at least 3 mel bins"
508
+ assert window_length_padded % 2 == 0
509
+ num_fft_bins = window_length_padded / 2
510
+ nyquist = 0.5 * sample_freq
511
+
512
+ if high_freq <= 0.0:
513
+ high_freq += nyquist
514
+
515
+ assert (
516
+ (0.0 <= low_freq < nyquist)
517
+ and (0.0 < high_freq <= nyquist)
518
+ and (low_freq < high_freq)
519
+ ), "Bad values in options: low-freq {} and high-freq {} vs. nyquist {}".format(
520
+ low_freq, high_freq, nyquist
521
+ )
522
+
523
+ # fft-bin width [think of it as Nyquist-freq / half-window-length]
524
+ fft_bin_width = sample_freq / window_length_padded
525
+ mel_low_freq = mel_scale_scalar(low_freq)
526
+ mel_high_freq = mel_scale_scalar(high_freq)
527
+
528
+ # divide by num_bins+1 in next line because of end-effects where the bins
529
+ # spread out to the sides.
530
+ mel_freq_delta = (mel_high_freq - mel_low_freq) / (num_bins + 1)
531
+
532
+ if vtln_high < 0.0:
533
+ vtln_high += nyquist
534
+
535
+ assert vtln_warp_factor == 1.0 or (
536
+ (low_freq < vtln_low < high_freq)
537
+ and (0.0 < vtln_high < high_freq)
538
+ and (vtln_low < vtln_high)
539
+ ), (
540
+ "Bad values in options: vtln-low {} and vtln-high {}, versus "
541
+ "low-freq {} and high-freq {}".format(vtln_low, vtln_high, low_freq, high_freq)
542
+ )
543
+
544
+ bin = torch.arange(num_bins).unsqueeze(1)
545
+ left_mel = mel_low_freq + bin * mel_freq_delta # size(num_bins, 1)
546
+ center_mel = mel_low_freq + (bin + 1.0) * mel_freq_delta # size(num_bins, 1)
547
+ right_mel = mel_low_freq + (bin + 2.0) * mel_freq_delta # size(num_bins, 1)
548
+
549
+ if vtln_warp_factor != 1.0:
550
+ left_mel = vtln_warp_mel_freq(
551
+ vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, left_mel
552
+ )
553
+ center_mel = vtln_warp_mel_freq(
554
+ vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, center_mel
555
+ )
556
+ right_mel = vtln_warp_mel_freq(
557
+ vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, right_mel
558
+ )
559
+
560
+ center_freqs = inverse_mel_scale(center_mel) # size (num_bins)
561
+ # size(1, num_fft_bins)
562
+ mel = mel_scale(fft_bin_width * torch.arange(num_fft_bins)).unsqueeze(0)
563
+
564
+ # size (num_bins, num_fft_bins)
565
+ up_slope = (mel - left_mel) / (center_mel - left_mel)
566
+ down_slope = (right_mel - mel) / (right_mel - center_mel)
567
+
568
+ if vtln_warp_factor == 1.0:
569
+ # left_mel < center_mel < right_mel so we can min the two slopes and clamp negative values
570
+ bins = torch.max(torch.zeros(1), torch.min(up_slope, down_slope))
571
+ else:
572
+ # warping can move the order of left_mel, center_mel, right_mel anywhere
573
+ bins = torch.zeros_like(up_slope)
574
+ up_idx = torch.gt(mel, left_mel) & torch.le(
575
+ mel, center_mel
576
+ ) # left_mel < mel <= center_mel
577
+ down_idx = torch.gt(mel, center_mel) & torch.lt(
578
+ mel, right_mel
579
+ ) # center_mel < mel < right_mel
580
+ bins[up_idx] = up_slope[up_idx]
581
+ bins[down_idx] = down_slope[down_idx]
582
+
583
+ return bins, center_freqs
584
+
585
+
586
+ def fbank(
587
+ waveform: Tensor,
588
+ blackman_coeff: float = 0.42,
589
+ channel: int = -1,
590
+ dither: float = 0.0,
591
+ energy_floor: float = 1.0,
592
+ frame_length: float = 25.0,
593
+ frame_shift: float = 10.0,
594
+ high_freq: float = 0.0,
595
+ htk_compat: bool = False,
596
+ low_freq: float = 20.0,
597
+ min_duration: float = 0.0,
598
+ num_mel_bins: int = 23,
599
+ preemphasis_coefficient: float = 0.97,
600
+ raw_energy: bool = True,
601
+ remove_dc_offset: bool = True,
602
+ round_to_power_of_two: bool = True,
603
+ sample_frequency: float = 16000.0,
604
+ snip_edges: bool = True,
605
+ subtract_mean: bool = False,
606
+ use_energy: bool = False,
607
+ use_log_fbank: bool = True,
608
+ use_power: bool = True,
609
+ vtln_high: float = -500.0,
610
+ vtln_low: float = 100.0,
611
+ vtln_warp: float = 1.0,
612
+ window_type: str = POVEY,
613
+ ) -> Tensor:
614
+ r"""Create a fbank from a raw audio signal. This matches the input/output of Kaldi's
615
+ compute-fbank-feats.
616
+
617
+ Args:
618
+ waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
619
+ blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
620
+ channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
621
+ dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
622
+ the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
623
+ energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
624
+ this floor is applied to the zeroth component, representing the total signal energy. The floor on the
625
+ individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
626
+ frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
627
+ frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
628
+ high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
629
+ (Default: ``0.0``)
630
+ htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible features
631
+ (need to change other parameters). (Default: ``False``)
632
+ low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
633
+ min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
634
+ num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
635
+ preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
636
+ raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
637
+ remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
638
+ round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
639
+ to FFT. (Default: ``True``)
640
+ sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
641
+ specified there) (Default: ``16000.0``)
642
+ snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
643
+ in the file, and the number of frames depends on the frame_length. If False, the number of frames
644
+ depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
645
+ subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
646
+ it this way. (Default: ``False``)
647
+ use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
648
+ use_log_fbank (bool, optional):If true, produce log-filterbank, else produce linear. (Default: ``True``)
649
+ use_power (bool, optional): If true, use power, else use magnitude. (Default: ``True``)
650
+ vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
651
+ negative, offset from high-mel-freq (Default: ``-500.0``)
652
+ vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
653
+ vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
654
+ window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
655
+ (Default: ``'povey'``)
656
+
657
+ Returns:
658
+ Tensor: A fbank identical to what Kaldi would output. The shape is (m, ``num_mel_bins + use_energy``)
659
+ where m is calculated in _get_strided
660
+ """
661
+ device, dtype = waveform.device, waveform.dtype
662
+
663
+ waveform, window_shift, window_size, padded_window_size = (
664
+ _get_waveform_and_window_properties(
665
+ waveform,
666
+ channel,
667
+ sample_frequency,
668
+ frame_shift,
669
+ frame_length,
670
+ round_to_power_of_two,
671
+ preemphasis_coefficient,
672
+ )
673
+ )
674
+
675
+ if len(waveform) < min_duration * sample_frequency:
676
+ # signal is too short
677
+ return torch.empty(0, device=device, dtype=dtype)
678
+
679
+ # strided_input, size (m, padded_window_size) and signal_log_energy, size (m)
680
+ strided_input, signal_log_energy = _get_window(
681
+ waveform,
682
+ padded_window_size,
683
+ window_size,
684
+ window_shift,
685
+ window_type,
686
+ blackman_coeff,
687
+ snip_edges,
688
+ raw_energy,
689
+ energy_floor,
690
+ dither,
691
+ remove_dc_offset,
692
+ preemphasis_coefficient,
693
+ )
694
+
695
+ # size (m, padded_window_size // 2 + 1)
696
+ spectrum = torch.fft.rfft(strided_input).abs()
697
+ if use_power:
698
+ spectrum = spectrum.pow(2.0)
699
+
700
+ # size (num_mel_bins, padded_window_size // 2)
701
+ mel_energies, _ = get_mel_banks(
702
+ num_mel_bins,
703
+ padded_window_size,
704
+ sample_frequency,
705
+ low_freq,
706
+ high_freq,
707
+ vtln_low,
708
+ vtln_high,
709
+ vtln_warp,
710
+ )
711
+ mel_energies = mel_energies.to(device=device, dtype=dtype)
712
+
713
+ # pad right column with zeros and add dimension, size (num_mel_bins, padded_window_size // 2 + 1)
714
+ mel_energies = torch.nn.functional.pad(
715
+ mel_energies, (0, 1), mode="constant", value=0
716
+ )
717
+
718
+ # sum with mel fiterbanks over the power spectrum, size (m, num_mel_bins)
719
+ mel_energies = torch.mm(spectrum, mel_energies.T)
720
+ if use_log_fbank:
721
+ # avoid log of zero (which should be prevented anyway by dithering)
722
+ mel_energies = torch.max(mel_energies, _get_epsilon(device, dtype)).log()
723
+
724
+ # if use_energy then add it as the last column for htk_compat == true else first column
725
+ if use_energy:
726
+ signal_log_energy = signal_log_energy.unsqueeze(1) # size (m, 1)
727
+ # returns size (m, num_mel_bins + 1)
728
+ if htk_compat:
729
+ mel_energies = torch.cat((mel_energies, signal_log_energy), dim=1)
730
+ else:
731
+ mel_energies = torch.cat((signal_log_energy, mel_energies), dim=1)
732
+
733
+ mel_energies = _subtract_column_mean(mel_energies, subtract_mean)
734
+ return mel_energies
735
+
736
+
737
+ def _get_dct_matrix(num_ceps: int, num_mel_bins: int) -> Tensor:
738
+ # returns a dct matrix of size (num_mel_bins, num_ceps)
739
+ # size (num_mel_bins, num_mel_bins)
740
+ dct_matrix = torchaudio.functional.create_dct(num_mel_bins, num_mel_bins, "ortho")
741
+ # kaldi expects the first cepstral to be weighted sum of factor sqrt(1/num_mel_bins)
742
+ # this would be the first column in the dct_matrix for torchaudio as it expects a
743
+ # right multiply (which would be the first column of the kaldi's dct_matrix as kaldi
744
+ # expects a left multiply e.g. dct_matrix * vector).
745
+ dct_matrix[:, 0] = math.sqrt(1 / float(num_mel_bins))
746
+ dct_matrix = dct_matrix[:, :num_ceps]
747
+ return dct_matrix
748
+
749
+
750
+ def _get_lifter_coeffs(num_ceps: int, cepstral_lifter: float) -> Tensor:
751
+ # returns size (num_ceps)
752
+ # Compute liftering coefficients (scaling on cepstral coeffs)
753
+ # coeffs are numbered slightly differently from HTK: the zeroth index is C0, which is not affected.
754
+ i = torch.arange(num_ceps)
755
+ return 1.0 + 0.5 * cepstral_lifter * torch.sin(math.pi * i / cepstral_lifter)
756
+
757
+
758
+ def mfcc(
759
+ waveform: Tensor,
760
+ blackman_coeff: float = 0.42,
761
+ cepstral_lifter: float = 22.0,
762
+ channel: int = -1,
763
+ dither: float = 0.0,
764
+ energy_floor: float = 1.0,
765
+ frame_length: float = 25.0,
766
+ frame_shift: float = 10.0,
767
+ high_freq: float = 0.0,
768
+ htk_compat: bool = False,
769
+ low_freq: float = 20.0,
770
+ num_ceps: int = 13,
771
+ min_duration: float = 0.0,
772
+ num_mel_bins: int = 23,
773
+ preemphasis_coefficient: float = 0.97,
774
+ raw_energy: bool = True,
775
+ remove_dc_offset: bool = True,
776
+ round_to_power_of_two: bool = True,
777
+ sample_frequency: float = 16000.0,
778
+ snip_edges: bool = True,
779
+ subtract_mean: bool = False,
780
+ use_energy: bool = False,
781
+ vtln_high: float = -500.0,
782
+ vtln_low: float = 100.0,
783
+ vtln_warp: float = 1.0,
784
+ window_type: str = POVEY,
785
+ ) -> Tensor:
786
+ r"""Create a mfcc from a raw audio signal. This matches the input/output of Kaldi's
787
+ compute-mfcc-feats.
788
+
789
+ Args:
790
+ waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
791
+ blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
792
+ cepstral_lifter (float, optional): Constant that controls scaling of MFCCs (Default: ``22.0``)
793
+ channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
794
+ dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
795
+ the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
796
+ energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
797
+ this floor is applied to the zeroth component, representing the total signal energy. The floor on the
798
+ individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
799
+ frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
800
+ frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
801
+ high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
802
+ (Default: ``0.0``)
803
+ htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible
804
+ features (need to change other parameters). (Default: ``False``)
805
+ low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
806
+ num_ceps (int, optional): Number of cepstra in MFCC computation (including C0) (Default: ``13``)
807
+ min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
808
+ num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
809
+ preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
810
+ raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
811
+ remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
812
+ round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
813
+ to FFT. (Default: ``True``)
814
+ sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
815
+ specified there) (Default: ``16000.0``)
816
+ snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
817
+ in the file, and the number of frames depends on the frame_length. If False, the number of frames
818
+ depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
819
+ subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
820
+ it this way. (Default: ``False``)
821
+ use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
822
+ vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
823
+ negative, offset from high-mel-freq (Default: ``-500.0``)
824
+ vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
825
+ vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
826
+ window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
827
+ (Default: ``"povey"``)
828
+
829
+ Returns:
830
+ Tensor: A mfcc identical to what Kaldi would output. The shape is (m, ``num_ceps``)
831
+ where m is calculated in _get_strided
832
+ """
833
+ assert (
834
+ num_ceps <= num_mel_bins
835
+ ), "num_ceps cannot be larger than num_mel_bins: %d vs %d" % (
836
+ num_ceps,
837
+ num_mel_bins,
838
+ )
839
+
840
+ device, dtype = waveform.device, waveform.dtype
841
+
842
+ # The mel_energies should not be squared (use_power=True), not have mean subtracted
843
+ # (subtract_mean=False), and use log (use_log_fbank=True).
844
+ # size (m, num_mel_bins + use_energy)
845
+ feature = fbank(
846
+ waveform=waveform,
847
+ blackman_coeff=blackman_coeff,
848
+ channel=channel,
849
+ dither=dither,
850
+ energy_floor=energy_floor,
851
+ frame_length=frame_length,
852
+ frame_shift=frame_shift,
853
+ high_freq=high_freq,
854
+ htk_compat=htk_compat,
855
+ low_freq=low_freq,
856
+ min_duration=min_duration,
857
+ num_mel_bins=num_mel_bins,
858
+ preemphasis_coefficient=preemphasis_coefficient,
859
+ raw_energy=raw_energy,
860
+ remove_dc_offset=remove_dc_offset,
861
+ round_to_power_of_two=round_to_power_of_two,
862
+ sample_frequency=sample_frequency,
863
+ snip_edges=snip_edges,
864
+ subtract_mean=False,
865
+ use_energy=use_energy,
866
+ use_log_fbank=True,
867
+ use_power=True,
868
+ vtln_high=vtln_high,
869
+ vtln_low=vtln_low,
870
+ vtln_warp=vtln_warp,
871
+ window_type=window_type,
872
+ )
873
+
874
+ if use_energy:
875
+ # size (m)
876
+ signal_log_energy = feature[:, num_mel_bins if htk_compat else 0]
877
+ # offset is 0 if htk_compat==True else 1
878
+ mel_offset = int(not htk_compat)
879
+ feature = feature[:, mel_offset : (num_mel_bins + mel_offset)]
880
+
881
+ # size (num_mel_bins, num_ceps)
882
+ dct_matrix = _get_dct_matrix(num_ceps, num_mel_bins).to(dtype=dtype, device=device)
883
+
884
+ # size (m, num_ceps)
885
+ feature = feature.matmul(dct_matrix)
886
+
887
+ if cepstral_lifter != 0.0:
888
+ # size (1, num_ceps)
889
+ lifter_coeffs = _get_lifter_coeffs(num_ceps, cepstral_lifter).unsqueeze(0)
890
+ feature *= lifter_coeffs.to(device=device, dtype=dtype)
891
+
892
+ # if use_energy then replace the last column for htk_compat == true else first column
893
+ if use_energy:
894
+ feature[:, 0] = signal_log_energy
895
+
896
+ if htk_compat:
897
+ energy = feature[:, 0].unsqueeze(1) # size (m, 1)
898
+ feature = feature[:, 1:] # size (m, num_ceps - 1)
899
+ if not use_energy:
900
+ # scale on C0 (actually removing a scale we previously added that's
901
+ # part of one common definition of the cosine transform.)
902
+ energy *= math.sqrt(2)
903
+
904
+ feature = torch.cat((feature, energy), dim=1)
905
+
906
+ feature = _subtract_column_mean(feature, subtract_mean)
907
+ return feature
wakeup_model/zipformer/scaling.py ADDED
@@ -0,0 +1,1911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022-2023 Xiaomi Corp. (authors: Daniel Povey)
2
+ #
3
+ # See ../../../../LICENSE for clarification regarding multiple authors
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ import logging
19
+ import math
20
+ import random
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import k2
24
+ import torch
25
+ import torch.nn as nn
26
+ from torch import Tensor
27
+ from torch.cuda.amp import custom_bwd, custom_fwd
28
+
29
+ from icefall.utils import torch_autocast
30
+
31
+
32
+ def logaddexp_onnx(x: Tensor, y: Tensor) -> Tensor:
33
+ max_value = torch.max(x, y)
34
+ diff = torch.abs(x - y)
35
+ return max_value + torch.log1p(torch.exp(-diff))
36
+
37
+
38
+ # RuntimeError: Exporting the operator logaddexp to ONNX opset version
39
+ # 14 is not supported. Please feel free to request support or submit
40
+ # a pull request on PyTorch GitHub.
41
+ #
42
+ # The following function is to solve the above error when exporting
43
+ # models to ONNX via torch.jit.trace()
44
+ def logaddexp(x: Tensor, y: Tensor) -> Tensor:
45
+ # Caution(fangjun): Put torch.jit.is_scripting() before
46
+ # torch.onnx.is_in_onnx_export();
47
+ # otherwise, it will cause errors for torch.jit.script().
48
+ #
49
+ # torch.logaddexp() works for both torch.jit.script() and
50
+ # torch.jit.trace() but it causes errors for ONNX export.
51
+ #
52
+ if torch.jit.is_scripting():
53
+ # Note: We cannot use torch.jit.is_tracing() here as it also
54
+ # matches torch.onnx.export().
55
+ return torch.logaddexp(x, y)
56
+ elif torch.onnx.is_in_onnx_export():
57
+ return logaddexp_onnx(x, y)
58
+ else:
59
+ # for torch.jit.trace()
60
+ return torch.logaddexp(x, y)
61
+
62
+
63
+ class PiecewiseLinear(object):
64
+ """
65
+ Piecewise linear function, from float to float, specified as nonempty list of (x,y) pairs with
66
+ the x values in order. x values <[initial x] or >[final x] are map to [initial y], [final y]
67
+ respectively.
68
+ """
69
+
70
+ def __init__(self, *args):
71
+ assert len(args) >= 1, len(args)
72
+ if len(args) == 1 and isinstance(args[0], PiecewiseLinear):
73
+ self.pairs = list(args[0].pairs)
74
+ else:
75
+ self.pairs = [(float(x), float(y)) for x, y in args]
76
+ for x, y in self.pairs:
77
+ assert isinstance(x, (float, int)), type(x)
78
+ assert isinstance(y, (float, int)), type(y)
79
+
80
+ for i in range(len(self.pairs) - 1):
81
+ assert self.pairs[i + 1][0] > self.pairs[i][0], (
82
+ i,
83
+ self.pairs[i],
84
+ self.pairs[i + 1],
85
+ )
86
+
87
+ def __str__(self):
88
+ # e.g. 'PiecewiseLinear((0., 10.), (100., 0.))'
89
+ return f"PiecewiseLinear({str(self.pairs)[1:-1]})"
90
+
91
+ def __call__(self, x):
92
+ if x <= self.pairs[0][0]:
93
+ return self.pairs[0][1]
94
+ elif x >= self.pairs[-1][0]:
95
+ return self.pairs[-1][1]
96
+ else:
97
+ cur_x, cur_y = self.pairs[0]
98
+ for i in range(1, len(self.pairs)):
99
+ next_x, next_y = self.pairs[i]
100
+ if x >= cur_x and x <= next_x:
101
+ return cur_y + (next_y - cur_y) * (x - cur_x) / (next_x - cur_x)
102
+ cur_x, cur_y = next_x, next_y
103
+ assert False
104
+
105
+ def __mul__(self, alpha):
106
+ return PiecewiseLinear(*[(x, y * alpha) for x, y in self.pairs])
107
+
108
+ def __add__(self, x):
109
+ if isinstance(x, (float, int)):
110
+ return PiecewiseLinear(*[(p[0], p[1] + x) for p in self.pairs])
111
+ s, x = self.get_common_basis(x)
112
+ return PiecewiseLinear(
113
+ *[(sp[0], sp[1] + xp[1]) for sp, xp in zip(s.pairs, x.pairs)]
114
+ )
115
+
116
+ def max(self, x):
117
+ if isinstance(x, (float, int)):
118
+ x = PiecewiseLinear((0, x))
119
+ s, x = self.get_common_basis(x, include_crossings=True)
120
+ return PiecewiseLinear(
121
+ *[(sp[0], max(sp[1], xp[1])) for sp, xp in zip(s.pairs, x.pairs)]
122
+ )
123
+
124
+ def min(self, x):
125
+ if isinstance(x, float) or isinstance(x, int):
126
+ x = PiecewiseLinear((0, x))
127
+ s, x = self.get_common_basis(x, include_crossings=True)
128
+ return PiecewiseLinear(
129
+ *[(sp[0], min(sp[1], xp[1])) for sp, xp in zip(s.pairs, x.pairs)]
130
+ )
131
+
132
+ def __eq__(self, other):
133
+ return self.pairs == other.pairs
134
+
135
+ def get_common_basis(self, p: "PiecewiseLinear", include_crossings: bool = False):
136
+ """
137
+ Returns (self_mod, p_mod) which are equivalent piecewise linear
138
+ functions to self and p, but with the same x values.
139
+
140
+ p: the other piecewise linear function
141
+ include_crossings: if true, include in the x values positions
142
+ where the functions indicate by this and p cross.
143
+ """
144
+ assert isinstance(p, PiecewiseLinear), type(p)
145
+
146
+ # get sorted x-values without repetition.
147
+ x_vals = sorted(set([x for x, _ in self.pairs] + [x for x, _ in p.pairs]))
148
+ y_vals1 = [self(x) for x in x_vals]
149
+ y_vals2 = [p(x) for x in x_vals]
150
+
151
+ if include_crossings:
152
+ extra_x_vals = []
153
+ for i in range(len(x_vals) - 1):
154
+ if (y_vals1[i] > y_vals2[i]) != (y_vals1[i + 1] > y_vals2[i + 1]):
155
+ # if the two lines in this subsegment potentially cross each other..
156
+ diff_cur = abs(y_vals1[i] - y_vals2[i])
157
+ diff_next = abs(y_vals1[i + 1] - y_vals2[i + 1])
158
+ # `pos`, between 0 and 1, gives the relative x position,
159
+ # with 0 being x_vals[i] and 1 being x_vals[i+1].
160
+ pos = diff_cur / (diff_cur + diff_next)
161
+ extra_x_val = x_vals[i] + pos * (x_vals[i + 1] - x_vals[i])
162
+ extra_x_vals.append(extra_x_val)
163
+ if len(extra_x_vals) > 0:
164
+ x_vals = sorted(set(x_vals + extra_x_vals))
165
+
166
+ y_vals1 = [self(x) for x in x_vals]
167
+ y_vals2 = [p(x) for x in x_vals]
168
+
169
+ return (
170
+ PiecewiseLinear(*zip(x_vals, y_vals1)),
171
+ PiecewiseLinear(*zip(x_vals, y_vals2)),
172
+ )
173
+
174
+
175
+ class ScheduledFloat(torch.nn.Module):
176
+ """
177
+ This object is a torch.nn.Module only because we want it to show up in [top_level module].modules();
178
+ it does not have a working forward() function. You are supposed to cast it to float, as
179
+ in, float(parent_module.whatever), and use it as something like a dropout prob.
180
+
181
+ It is a floating point value whose value changes depending on the batch count of the
182
+ training loop. It is a piecewise linear function where you specify the (x,y) pairs
183
+ in sorted order on x; x corresponds to the batch index. For batch-index values before the
184
+ first x or after the last x, we just use the first or last y value.
185
+
186
+ Example:
187
+ self.dropout = ScheduledFloat((0.0, 0.2), (4000.0, 0.0), default=0.0)
188
+
189
+ `default` is used when self.batch_count is not set or not in training mode or in
190
+ torch.jit scripting mode.
191
+ """
192
+
193
+ def __init__(self, *args, default: float = 0.0):
194
+ super().__init__()
195
+ # self.batch_count and self.name will be written to in the training loop.
196
+ self.batch_count = None
197
+ self.name = None
198
+ self.default = default
199
+ self.schedule = PiecewiseLinear(*args)
200
+
201
+ def extra_repr(self) -> str:
202
+ return (
203
+ f"batch_count={self.batch_count}, schedule={str(self.schedule.pairs[1:-1])}"
204
+ )
205
+
206
+ def __float__(self):
207
+ batch_count = self.batch_count
208
+ if (
209
+ batch_count is None
210
+ or not self.training
211
+ or torch.jit.is_scripting()
212
+ or torch.jit.is_tracing()
213
+ ):
214
+ return float(self.default)
215
+ else:
216
+ ans = self.schedule(self.batch_count)
217
+ if random.random() < 0.0002:
218
+ logging.info(
219
+ f"ScheduledFloat: name={self.name}, batch_count={self.batch_count}, ans={ans}"
220
+ )
221
+ return ans
222
+
223
+ def __add__(self, x):
224
+ if isinstance(x, float) or isinstance(x, int):
225
+ return ScheduledFloat(self.schedule + x, default=self.default)
226
+ else:
227
+ return ScheduledFloat(
228
+ self.schedule + x.schedule, default=self.default + x.default
229
+ )
230
+
231
+ def max(self, x):
232
+ if isinstance(x, float) or isinstance(x, int):
233
+ return ScheduledFloat(self.schedule.max(x), default=self.default)
234
+ else:
235
+ return ScheduledFloat(
236
+ self.schedule.max(x.schedule), default=max(self.default, x.default)
237
+ )
238
+
239
+
240
+ FloatLike = Union[float, ScheduledFloat]
241
+
242
+
243
+ def random_cast_to_half(x: Tensor, min_abs: float = 5.0e-06) -> Tensor:
244
+ """
245
+ A randomized way of casting a floating point value to half precision.
246
+ """
247
+ if x.dtype == torch.float16:
248
+ return x
249
+ x_abs = x.abs()
250
+ is_too_small = x_abs < min_abs
251
+ # for elements where is_too_small is true, random_val will contain +-min_abs with
252
+ # probability (x.abs() / min_abs), and 0.0 otherwise. [so this preserves expectations,
253
+ # for those elements].
254
+ random_val = min_abs * x.sign() * (torch.rand_like(x) * min_abs < x_abs)
255
+ return torch.where(is_too_small, random_val, x).to(torch.float16)
256
+
257
+
258
+ class CutoffEstimator:
259
+ """
260
+ Estimates cutoffs of an arbitrary numerical quantity such that a specified
261
+ proportion of items will be above the cutoff on average.
262
+
263
+ p is the proportion of items that should be above the cutoff.
264
+ """
265
+
266
+ def __init__(self, p: float):
267
+ self.p = p
268
+ # total count of items
269
+ self.count = 0
270
+ # total count of items that were above the cutoff
271
+ self.count_above = 0
272
+ # initial cutoff value
273
+ self.cutoff = 0
274
+
275
+ def __call__(self, x: float) -> bool:
276
+ """
277
+ Returns true if x is above the cutoff.
278
+ """
279
+ ans = x > self.cutoff
280
+ self.count += 1
281
+ if ans:
282
+ self.count_above += 1
283
+ cur_p = self.count_above / self.count
284
+ delta_p = cur_p - self.p
285
+ if (delta_p > 0) == ans:
286
+ q = abs(delta_p)
287
+ self.cutoff = x * q + self.cutoff * (1 - q)
288
+ return ans
289
+
290
+
291
+ class SoftmaxFunction(torch.autograd.Function):
292
+ """
293
+ Tries to handle half-precision derivatives in a randomized way that should
294
+ be more accurate for training than the default behavior.
295
+ """
296
+
297
+ @staticmethod
298
+ def forward(ctx, x: Tensor, dim: int):
299
+ ans = x.softmax(dim=dim)
300
+ # if x dtype is float16, x.softmax() returns a float32 because
301
+ # (presumably) that op does not support float16, and autocast
302
+ # is enabled.
303
+ if torch.is_autocast_enabled():
304
+ ans = ans.to(torch.get_autocast_gpu_dtype())
305
+ ctx.save_for_backward(ans)
306
+ ctx.x_dtype = x.dtype
307
+ ctx.dim = dim
308
+ return ans
309
+
310
+ @staticmethod
311
+ def backward(ctx, ans_grad: Tensor):
312
+ (ans,) = ctx.saved_tensors
313
+ with torch_autocast(enabled=False):
314
+ ans_grad = ans_grad.to(torch.float32)
315
+ ans = ans.to(torch.float32)
316
+ x_grad = ans_grad * ans
317
+ x_grad = x_grad - ans * x_grad.sum(dim=ctx.dim, keepdim=True)
318
+ return x_grad, None
319
+
320
+
321
+ def softmax(x: Tensor, dim: int):
322
+ if not x.requires_grad or torch.jit.is_scripting() or torch.jit.is_tracing():
323
+ return x.softmax(dim=dim)
324
+
325
+ return SoftmaxFunction.apply(x, dim)
326
+
327
+
328
+ class MaxEigLimiterFunction(torch.autograd.Function):
329
+ @staticmethod
330
+ def forward(
331
+ ctx,
332
+ x: Tensor,
333
+ coeffs: Tensor,
334
+ direction: Tensor,
335
+ channel_dim: int,
336
+ grad_scale: float,
337
+ ) -> Tensor:
338
+ ctx.channel_dim = channel_dim
339
+ ctx.grad_scale = grad_scale
340
+ ctx.save_for_backward(x.detach(), coeffs.detach(), direction.detach())
341
+ return x
342
+
343
+ @staticmethod
344
+ def backward(ctx, x_grad, *args):
345
+ with torch.enable_grad():
346
+ x_orig, coeffs, new_direction = ctx.saved_tensors
347
+ x_orig.requires_grad = True
348
+ num_channels = x_orig.shape[ctx.channel_dim]
349
+ x = x_orig.transpose(ctx.channel_dim, -1).reshape(-1, num_channels)
350
+ new_direction.requires_grad = False
351
+ x = x - x.mean(dim=0)
352
+ x_var = (x**2).mean()
353
+ x_residual = x - coeffs * new_direction
354
+ x_residual_var = (x_residual**2).mean()
355
+ # `variance_proportion` is the proportion of the variance accounted for
356
+ # by the top eigen-direction. This is to be minimized.
357
+ variance_proportion = (x_var - x_residual_var) / (x_var + 1.0e-20)
358
+ variance_proportion.backward()
359
+ x_orig_grad = x_orig.grad
360
+ x_extra_grad = (
361
+ x_orig.grad
362
+ * ctx.grad_scale
363
+ * x_grad.norm()
364
+ / (x_orig_grad.norm() + 1.0e-20)
365
+ )
366
+ return x_grad + x_extra_grad.detach(), None, None, None, None
367
+
368
+
369
+ class BiasNormFunction(torch.autograd.Function):
370
+ # This computes:
371
+ # scales = (torch.mean((x - bias) ** 2, keepdim=True)) ** -0.5 * log_scale.exp()
372
+ # return x * scales
373
+ # (after unsqueezing the bias), but it does it in a memory-efficient way so that
374
+ # it can just store the returned value (chances are, this will also be needed for
375
+ # some other reason, related to the next operation, so we can save memory).
376
+ @staticmethod
377
+ def forward(
378
+ ctx,
379
+ x: Tensor,
380
+ bias: Tensor,
381
+ log_scale: Tensor,
382
+ channel_dim: int,
383
+ store_output_for_backprop: bool,
384
+ ) -> Tensor:
385
+ assert bias.ndim == 1
386
+ if channel_dim < 0:
387
+ channel_dim = channel_dim + x.ndim
388
+ ctx.store_output_for_backprop = store_output_for_backprop
389
+ ctx.channel_dim = channel_dim
390
+ for _ in range(channel_dim + 1, x.ndim):
391
+ bias = bias.unsqueeze(-1)
392
+ scales = (
393
+ torch.mean((x - bias) ** 2, dim=channel_dim, keepdim=True) ** -0.5
394
+ ) * log_scale.exp()
395
+ ans = x * scales
396
+ ctx.save_for_backward(
397
+ ans.detach() if store_output_for_backprop else x,
398
+ scales.detach(),
399
+ bias.detach(),
400
+ log_scale.detach(),
401
+ )
402
+ return ans
403
+
404
+ @staticmethod
405
+ def backward(ctx, ans_grad: Tensor) -> Tensor:
406
+ ans_or_x, scales, bias, log_scale = ctx.saved_tensors
407
+ if ctx.store_output_for_backprop:
408
+ x = ans_or_x / scales
409
+ else:
410
+ x = ans_or_x
411
+ x = x.detach()
412
+ x.requires_grad = True
413
+ bias.requires_grad = True
414
+ log_scale.requires_grad = True
415
+ with torch.enable_grad():
416
+ # recompute scales from x, bias and log_scale.
417
+ scales = (
418
+ torch.mean((x - bias) ** 2, dim=ctx.channel_dim, keepdim=True) ** -0.5
419
+ ) * log_scale.exp()
420
+ ans = x * scales
421
+ ans.backward(gradient=ans_grad)
422
+ return x.grad, bias.grad.flatten(), log_scale.grad, None, None
423
+
424
+
425
+ class BiasNorm(torch.nn.Module):
426
+ """
427
+ This is intended to be a simpler, and hopefully cheaper, replacement for
428
+ LayerNorm. The observation this is based on, is that Transformer-type
429
+ networks, especially with pre-norm, sometimes seem to set one of the
430
+ feature dimensions to a large constant value (e.g. 50), which "defeats"
431
+ the LayerNorm because the output magnitude is then not strongly dependent
432
+ on the other (useful) features. Presumably the weight and bias of the
433
+ LayerNorm are required to allow it to do this.
434
+
435
+ Instead, we give the BiasNorm a trainable bias that it can use when
436
+ computing the scale for normalization. We also give it a (scalar)
437
+ trainable scale on the output.
438
+
439
+
440
+ Args:
441
+ num_channels: the number of channels, e.g. 512.
442
+ channel_dim: the axis/dimension corresponding to the channel,
443
+ interpreted as an offset from the input's ndim if negative.
444
+ This is NOT the num_channels; it should typically be one of
445
+ {-2, -1, 0, 1, 2, 3}.
446
+ log_scale: the initial log-scale that we multiply the output by; this
447
+ is learnable.
448
+ log_scale_min: FloatLike, minimum allowed value of log_scale
449
+ log_scale_max: FloatLike, maximum allowed value of log_scale
450
+ store_output_for_backprop: only possibly affects memory use; recommend
451
+ to set to True if you think the output of this module is more likely
452
+ than the input of this module to be required to be stored for the
453
+ backprop.
454
+ """
455
+
456
+ def __init__(
457
+ self,
458
+ num_channels: int,
459
+ channel_dim: int = -1, # CAUTION: see documentation.
460
+ log_scale: float = 1.0,
461
+ log_scale_min: float = -1.5,
462
+ log_scale_max: float = 1.5,
463
+ store_output_for_backprop: bool = False,
464
+ ) -> None:
465
+ super(BiasNorm, self).__init__()
466
+ self.num_channels = num_channels
467
+ self.channel_dim = channel_dim
468
+ self.log_scale = nn.Parameter(torch.tensor(log_scale))
469
+ self.bias = nn.Parameter(torch.empty(num_channels).normal_(mean=0, std=1e-4))
470
+
471
+ self.log_scale_min = log_scale_min
472
+ self.log_scale_max = log_scale_max
473
+
474
+ self.store_output_for_backprop = store_output_for_backprop
475
+
476
+ def forward(self, x: Tensor) -> Tensor:
477
+ assert x.shape[self.channel_dim] == self.num_channels
478
+
479
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
480
+ channel_dim = self.channel_dim
481
+ if channel_dim < 0:
482
+ channel_dim += x.ndim
483
+ bias = self.bias
484
+ for _ in range(channel_dim + 1, x.ndim):
485
+ bias = bias.unsqueeze(-1)
486
+ scales = (
487
+ torch.mean((x - bias) ** 2, dim=channel_dim, keepdim=True) ** -0.5
488
+ ) * self.log_scale.exp()
489
+ return x * scales
490
+
491
+ log_scale = limit_param_value(
492
+ self.log_scale,
493
+ min=float(self.log_scale_min),
494
+ max=float(self.log_scale_max),
495
+ training=self.training,
496
+ )
497
+
498
+ return BiasNormFunction.apply(
499
+ x, self.bias, log_scale, self.channel_dim, self.store_output_for_backprop
500
+ )
501
+
502
+
503
+ def ScaledLinear(*args, initial_scale: float = 1.0, **kwargs) -> nn.Linear:
504
+ """
505
+ Behaves like a constructor of a modified version of nn.Linear
506
+ that gives an easy way to set the default initial parameter scale.
507
+
508
+ Args:
509
+ Accepts the standard args and kwargs that nn.Linear accepts
510
+ e.g. in_features, out_features, bias=False.
511
+
512
+ initial_scale: you can override this if you want to increase
513
+ or decrease the initial magnitude of the module's output
514
+ (affects the initialization of weight_scale and bias_scale).
515
+ Another option, if you want to do something like this, is
516
+ to re-initialize the parameters.
517
+ """
518
+ ans = nn.Linear(*args, **kwargs)
519
+ with torch.no_grad():
520
+ ans.weight[:] *= initial_scale
521
+ if ans.bias is not None:
522
+ torch.nn.init.uniform_(ans.bias, -0.1 * initial_scale, 0.1 * initial_scale)
523
+ return ans
524
+
525
+
526
+ def ScaledConv1d(*args, initial_scale: float = 1.0, **kwargs) -> nn.Conv1d:
527
+ """
528
+ Behaves like a constructor of a modified version of nn.Conv1d
529
+ that gives an easy way to set the default initial parameter scale.
530
+
531
+ Args:
532
+ Accepts the standard args and kwargs that nn.Linear accepts
533
+ e.g. in_features, out_features, bias=False.
534
+
535
+ initial_scale: you can override this if you want to increase
536
+ or decrease the initial magnitude of the module's output
537
+ (affects the initialization of weight_scale and bias_scale).
538
+ Another option, if you want to do something like this, is
539
+ to re-initialize the parameters.
540
+ """
541
+ ans = nn.Conv1d(*args, **kwargs)
542
+ with torch.no_grad():
543
+ ans.weight[:] *= initial_scale
544
+ if ans.bias is not None:
545
+ torch.nn.init.uniform_(ans.bias, -0.1 * initial_scale, 0.1 * initial_scale)
546
+ return ans
547
+
548
+
549
+ def ScaledConv2d(*args, initial_scale: float = 1.0, **kwargs) -> nn.Conv2d:
550
+ """
551
+ Behaves like a constructor of a modified version of nn.Conv2d
552
+ that gives an easy way to set the default initial parameter scale.
553
+
554
+ Args:
555
+ Accepts the standard args and kwargs that nn.Linear accepts
556
+ e.g. in_features, out_features, bias=False, but:
557
+ NO PADDING-RELATED ARGS.
558
+
559
+ initial_scale: you can override this if you want to increase
560
+ or decrease the initial magnitude of the module's output
561
+ (affects the initialization of weight_scale and bias_scale).
562
+ Another option, if you want to do something like this, is
563
+ to re-initialize the parameters.
564
+ """
565
+ ans = nn.Conv2d(*args, **kwargs)
566
+ with torch.no_grad():
567
+ ans.weight[:] *= initial_scale
568
+ if ans.bias is not None:
569
+ torch.nn.init.uniform_(ans.bias, -0.1 * initial_scale, 0.1 * initial_scale)
570
+ return ans
571
+
572
+
573
+ class ChunkCausalDepthwiseConv1d(torch.nn.Module):
574
+ """
575
+ Behaves like a depthwise 1d convolution, except that it is causal in
576
+ a chunkwise way, as if we had a block-triangular attention mask.
577
+ The chunk size is provided at test time (it should probably be
578
+ kept in sync with the attention mask).
579
+
580
+ This has a little more than twice the parameters of a conventional
581
+ depthwise conv1d module: we implement it by having one
582
+ depthwise convolution, of half the width, that is causal (via
583
+ right-padding); and one depthwise convolution that is applied only
584
+ within chunks, that we multiply by a scaling factor which depends
585
+ on the position within the chunk.
586
+
587
+ Args:
588
+ Accepts the standard args and kwargs that nn.Linear accepts
589
+ e.g. in_features, out_features, bias=False.
590
+
591
+ initial_scale: you can override this if you want to increase
592
+ or decrease the initial magnitude of the module's output
593
+ (affects the initialization of weight_scale and bias_scale).
594
+ Another option, if you want to do something like this, is
595
+ to re-initialize the parameters.
596
+ """
597
+
598
+ def __init__(
599
+ self,
600
+ channels: int,
601
+ kernel_size: int,
602
+ initial_scale: float = 1.0,
603
+ bias: bool = True,
604
+ ):
605
+ super().__init__()
606
+ assert kernel_size % 2 == 1
607
+
608
+ half_kernel_size = (kernel_size + 1) // 2
609
+ # will pad manually, on one side.
610
+ self.causal_conv = nn.Conv1d(
611
+ in_channels=channels,
612
+ out_channels=channels,
613
+ groups=channels,
614
+ kernel_size=half_kernel_size,
615
+ padding=0,
616
+ bias=True,
617
+ )
618
+
619
+ self.chunkwise_conv = nn.Conv1d(
620
+ in_channels=channels,
621
+ out_channels=channels,
622
+ groups=channels,
623
+ kernel_size=kernel_size,
624
+ padding=kernel_size // 2,
625
+ bias=bias,
626
+ )
627
+
628
+ # first row is correction factors added to the scale near the left edge of the chunk,
629
+ # second row is correction factors added to the scale near the right edge of the chunk,
630
+ # both of these are added to a default scale of 1.0.
631
+ self.chunkwise_conv_scale = nn.Parameter(torch.zeros(2, channels, kernel_size))
632
+ self.kernel_size = kernel_size
633
+
634
+ with torch.no_grad():
635
+ self.causal_conv.weight[:] *= initial_scale
636
+ self.chunkwise_conv.weight[:] *= initial_scale
637
+ if bias:
638
+ torch.nn.init.uniform_(
639
+ self.causal_conv.bias, -0.1 * initial_scale, 0.1 * initial_scale
640
+ )
641
+
642
+ def forward(self, x: Tensor, chunk_size: int = -1) -> Tensor:
643
+ """Forward function.
644
+
645
+ Args:
646
+ x: a Tensor of shape (batch_size, channels, seq_len)
647
+ chunk_size: the chunk size, in frames; does not have to divide seq_len exactly.
648
+ """
649
+ batch_size, num_channels, seq_len = x.shape
650
+
651
+ # half_kernel_size = self.kernel_size + 1 // 2
652
+ # left_pad is half_kernel_size - 1 where half_kernel_size is the size used
653
+ # in the causal conv. It's the amount by which we must pad on the left,
654
+ # to make the convolution causal.
655
+ left_pad = self.kernel_size // 2
656
+
657
+ if chunk_size < 0 or chunk_size > seq_len:
658
+ chunk_size = seq_len
659
+ right_pad = -seq_len % chunk_size
660
+
661
+ x = torch.nn.functional.pad(x, (left_pad, right_pad))
662
+
663
+ x_causal = self.causal_conv(x[..., : left_pad + seq_len])
664
+ assert x_causal.shape == (batch_size, num_channels, seq_len)
665
+
666
+ x_chunk = x[..., left_pad:]
667
+ num_chunks = x_chunk.shape[2] // chunk_size
668
+ x_chunk = x_chunk.reshape(batch_size, num_channels, num_chunks, chunk_size)
669
+ x_chunk = x_chunk.permute(0, 2, 1, 3).reshape(
670
+ batch_size * num_chunks, num_channels, chunk_size
671
+ )
672
+ x_chunk = self.chunkwise_conv(x_chunk) # does not change shape
673
+
674
+ chunk_scale = self._get_chunk_scale(chunk_size)
675
+
676
+ x_chunk = x_chunk * chunk_scale
677
+ x_chunk = x_chunk.reshape(
678
+ batch_size, num_chunks, num_channels, chunk_size
679
+ ).permute(0, 2, 1, 3)
680
+ x_chunk = x_chunk.reshape(batch_size, num_channels, num_chunks * chunk_size)[
681
+ ..., :seq_len
682
+ ]
683
+
684
+ return x_chunk + x_causal
685
+
686
+ def _get_chunk_scale(self, chunk_size: int):
687
+ """Returns tensor of shape (num_channels, chunk_size) that will be used to
688
+ scale the output of self.chunkwise_conv."""
689
+ left_edge = self.chunkwise_conv_scale[0]
690
+ right_edge = self.chunkwise_conv_scale[1]
691
+ if chunk_size < self.kernel_size:
692
+ left_edge = left_edge[:, :chunk_size]
693
+ right_edge = right_edge[:, -chunk_size:]
694
+ else:
695
+ t = chunk_size - self.kernel_size
696
+ channels = left_edge.shape[0]
697
+ pad = torch.zeros(
698
+ channels, t, device=left_edge.device, dtype=left_edge.dtype
699
+ )
700
+ left_edge = torch.cat((left_edge, pad), dim=-1)
701
+ right_edge = torch.cat((pad, right_edge), dim=-1)
702
+ return 1.0 + (left_edge + right_edge)
703
+
704
+ def streaming_forward(
705
+ self,
706
+ x: Tensor,
707
+ cache: Tensor,
708
+ ) -> Tuple[Tensor, Tensor]:
709
+ """Streaming Forward function.
710
+
711
+ Args:
712
+ x: a Tensor of shape (batch_size, channels, seq_len)
713
+ cache: cached left context of shape (batch_size, channels, left_pad)
714
+ """
715
+ batch_size, num_channels, seq_len = x.shape
716
+
717
+ # left_pad is half_kernel_size - 1 where half_kernel_size is the size used
718
+ # in the causal conv. It's the amount by which we must pad on the left,
719
+ # to make the convolution causal.
720
+ left_pad = self.kernel_size // 2
721
+
722
+ # Pad cache
723
+ assert cache.shape[-1] == left_pad, (cache.shape[-1], left_pad)
724
+ x = torch.cat([cache, x], dim=2)
725
+ # Update cache
726
+ cache = x[..., -left_pad:]
727
+
728
+ x_causal = self.causal_conv(x)
729
+ assert x_causal.shape == (batch_size, num_channels, seq_len)
730
+
731
+ x_chunk = x[..., left_pad:]
732
+ x_chunk = self.chunkwise_conv(x_chunk) # does not change shape
733
+
734
+ chunk_scale = self._get_chunk_scale(chunk_size=seq_len)
735
+ x_chunk = x_chunk * chunk_scale
736
+
737
+ return x_chunk + x_causal, cache
738
+
739
+
740
+ class BalancerFunction(torch.autograd.Function):
741
+ @staticmethod
742
+ def forward(
743
+ ctx,
744
+ x: Tensor,
745
+ min_mean: float,
746
+ max_mean: float,
747
+ min_rms: float,
748
+ max_rms: float,
749
+ grad_scale: float,
750
+ channel_dim: int,
751
+ ) -> Tensor:
752
+ if channel_dim < 0:
753
+ channel_dim += x.ndim
754
+ ctx.channel_dim = channel_dim
755
+ ctx.save_for_backward(x)
756
+ ctx.config = (min_mean, max_mean, min_rms, max_rms, grad_scale, channel_dim)
757
+ return x
758
+
759
+ @staticmethod
760
+ def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None, None, None]:
761
+ (x,) = ctx.saved_tensors
762
+ min_mean, max_mean, min_rms, max_rms, grad_scale, channel_dim = ctx.config
763
+
764
+ try:
765
+ with torch.enable_grad():
766
+ with torch_autocast(enabled=False):
767
+ x = x.to(torch.float32)
768
+ x = x.detach()
769
+ x.requires_grad = True
770
+ mean_dims = [i for i in range(x.ndim) if i != channel_dim]
771
+ uncentered_var = (x**2).mean(dim=mean_dims, keepdim=True)
772
+ mean = x.mean(dim=mean_dims, keepdim=True)
773
+ stddev = (uncentered_var - (mean * mean)).clamp(min=1.0e-20).sqrt()
774
+ rms = uncentered_var.clamp(min=1.0e-20).sqrt()
775
+
776
+ m = mean / stddev
777
+ # part of loss that relates to mean / stddev
778
+ m_loss = (m - m.clamp(min=min_mean, max=max_mean)).abs()
779
+
780
+ # put a much larger scale on the RMS-max-limit loss, so that if both it and the
781
+ # m_loss are violated we fix the RMS loss first.
782
+ rms_clamped = rms.clamp(min=min_rms, max=max_rms)
783
+ r_loss = (rms_clamped / rms).log().abs()
784
+
785
+ loss = m_loss + r_loss
786
+
787
+ loss.backward(gradient=torch.ones_like(loss))
788
+ loss_grad = x.grad
789
+ loss_grad_rms = (
790
+ (loss_grad**2)
791
+ .mean(dim=mean_dims, keepdim=True)
792
+ .sqrt()
793
+ .clamp(min=1.0e-20)
794
+ )
795
+
796
+ loss_grad = loss_grad * (grad_scale / loss_grad_rms)
797
+
798
+ x_grad_float = x_grad.to(torch.float32)
799
+ # scale each element of loss_grad by the absolute value of the corresponding
800
+ # element of x_grad, which we view as a noisy estimate of its magnitude for that
801
+ # (frame and dimension). later we can consider factored versions.
802
+ x_grad_mod = x_grad_float + (x_grad_float.abs() * loss_grad)
803
+ x_grad = x_grad_mod.to(x_grad.dtype)
804
+ except Exception as e:
805
+ logging.info(
806
+ f"Caught exception in Balancer backward: {e}, size={list(x_grad.shape)}, will continue."
807
+ )
808
+
809
+ return x_grad, None, None, None, None, None, None
810
+
811
+
812
+ class Balancer(torch.nn.Module):
813
+ """
814
+ Modifies the backpropped derivatives of a function to try to encourage, for
815
+ each channel, that it is positive at least a proportion `threshold` of the
816
+ time. It does this by multiplying negative derivative values by up to
817
+ (1+max_factor), and positive derivative values by up to (1-max_factor),
818
+ interpolated from 1 at the threshold to those extremal values when none
819
+ of the inputs are positive.
820
+
821
+ Args:
822
+ num_channels: the number of channels
823
+ channel_dim: the dimension/axis corresponding to the channel, e.g.
824
+ -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
825
+ min_positive: the minimum, per channel, of the proportion of the time
826
+ that (x > 0), below which we start to modify the derivatives.
827
+ max_positive: the maximum, per channel, of the proportion of the time
828
+ that (x > 0), above which we start to modify the derivatives.
829
+ scale_gain_factor: determines the 'gain' with which we increase the
830
+ change in gradient once the constraints on min_abs and max_abs
831
+ are violated.
832
+ min_abs: the minimum average-absolute-value difference from the mean
833
+ value per channel, which we allow, before we start to modify
834
+ the derivatives to prevent this.
835
+ max_abs: the maximum average-absolute-value difference from the mean
836
+ value per channel, which we allow, before we start to modify
837
+ the derivatives to prevent this.
838
+ prob: determines the minimum probability with which we modify the
839
+ gradients for the {min,max}_positive and {min,max}_abs constraints,
840
+ on each forward(). This is done randomly to prevent all layers
841
+ from doing it at the same time.
842
+ """
843
+
844
+ def __init__(
845
+ self,
846
+ num_channels: int,
847
+ channel_dim: int,
848
+ min_positive: FloatLike = 0.05,
849
+ max_positive: FloatLike = 0.95,
850
+ min_abs: FloatLike = 0.2,
851
+ max_abs: FloatLike = 100.0,
852
+ grad_scale: FloatLike = 0.04,
853
+ prob: Optional[FloatLike] = None,
854
+ ):
855
+ super().__init__()
856
+
857
+ if prob is None:
858
+ prob = ScheduledFloat((0.0, 0.5), (8000.0, 0.125), default=0.4)
859
+ self.prob = prob
860
+ # 5% of the time we will return and do nothing because memory usage is
861
+ # too high.
862
+ self.mem_cutoff = CutoffEstimator(0.05)
863
+
864
+ # actually self.num_channels is no longer needed except for an assertion.
865
+ self.num_channels = num_channels
866
+ self.channel_dim = channel_dim
867
+ self.min_positive = min_positive
868
+ self.max_positive = max_positive
869
+ self.min_abs = min_abs
870
+ self.max_abs = max_abs
871
+ self.grad_scale = grad_scale
872
+
873
+ def forward(self, x: Tensor) -> Tensor:
874
+ if (
875
+ torch.jit.is_scripting()
876
+ or not x.requires_grad
877
+ or (x.is_cuda and self.mem_cutoff(torch.cuda.memory_allocated()))
878
+ ):
879
+ return _no_op(x)
880
+
881
+ prob = float(self.prob)
882
+ if random.random() < prob:
883
+ # The following inner-functions convert from the way we historically specified
884
+ # these limitations, as limits on the absolute value and the proportion of positive
885
+ # values, to limits on the RMS value and the (mean / stddev).
886
+ def _abs_to_rms(x):
887
+ # for normally distributed data, if the expected absolute value is x, the
888
+ # expected rms value will be sqrt(pi/2) * x.
889
+ return 1.25331413732 * x
890
+
891
+ def _proportion_positive_to_mean(x):
892
+ def _atanh(x):
893
+ eps = 1.0e-10
894
+ # eps is to prevent crashes if x is exactly 0 or 1.
895
+ # we'll just end up returning a fairly large value.
896
+ return (math.log(1 + x + eps) - math.log(1 - x + eps)) / 2.0
897
+
898
+ def _approx_inverse_erf(x):
899
+ # 1 / (sqrt(pi) * ln(2)),
900
+ # see https://math.stackexchange.com/questions/321569/approximating-the-error-function-erf-by-analytical-functions
901
+ # this approximation is extremely crude and gets progressively worse for
902
+ # x very close to -1 or +1, but we mostly care about the "middle" region
903
+ # e.g. _approx_inverse_erf(0.05) = 0.0407316414078772,
904
+ # and math.erf(0.0407316414078772) = 0.045935330944660666,
905
+ # which is pretty close to 0.05.
906
+ return 0.8139535143 * _atanh(x)
907
+
908
+ # first convert x from the range 0..1 to the range -1..1 which the error
909
+ # function returns
910
+ x = -1 + (2 * x)
911
+ return _approx_inverse_erf(x)
912
+
913
+ min_mean = _proportion_positive_to_mean(float(self.min_positive))
914
+ max_mean = _proportion_positive_to_mean(float(self.max_positive))
915
+ min_rms = _abs_to_rms(float(self.min_abs))
916
+ max_rms = _abs_to_rms(float(self.max_abs))
917
+ grad_scale = float(self.grad_scale)
918
+
919
+ assert x.shape[self.channel_dim] == self.num_channels
920
+
921
+ return BalancerFunction.apply(
922
+ x, min_mean, max_mean, min_rms, max_rms, grad_scale, self.channel_dim
923
+ )
924
+ else:
925
+ return _no_op(x)
926
+
927
+
928
+ def penalize_abs_values_gt(
929
+ x: Tensor, limit: float, penalty: float, name: str = None
930
+ ) -> Tensor:
931
+ """
932
+ Returns x unmodified, but in backprop will put a penalty for the excess of
933
+ the absolute values of elements of x over the limit "limit". E.g. if
934
+ limit == 10.0, then if x has any values over 10 it will get a penalty.
935
+
936
+ Caution: the value of this penalty will be affected by grad scaling used
937
+ in automatic mixed precision training. For this reasons we use this,
938
+ it shouldn't really matter, or may even be helpful; we just use this
939
+ to disallow really implausible values of scores to be given to softmax.
940
+
941
+ The name is for randomly printed debug info.
942
+ """
943
+ x_sign = x.sign()
944
+ over_limit = (x.abs() - limit) > 0
945
+ # The following is a memory efficient way to penalize the absolute values of
946
+ # x that's over the limit. (The memory efficiency comes when you think
947
+ # about which items torch needs to cache for the autograd, and which ones it
948
+ # can throw away). The numerical value of aux_loss as computed here will
949
+ # actually be larger than it should be, by limit * over_limit.sum(), but it
950
+ # has the same derivative as the real aux_loss which is penalty * (x.abs() -
951
+ # limit).relu().
952
+ aux_loss = penalty * ((x_sign * over_limit).to(torch.int8) * x)
953
+ # note: we don't do sum() here on aux)_loss, but it's as if we had done
954
+ # sum() due to how with_loss() works.
955
+ x = with_loss(x, aux_loss, name)
956
+ # you must use x for something, or this will be ineffective.
957
+ return x
958
+
959
+
960
+ def _diag(x: Tensor): # like .diag(), but works for tensors with 3 dims.
961
+ if x.ndim == 2:
962
+ return x.diag()
963
+ else:
964
+ batch, dim, dim = x.shape
965
+ x = x.reshape(batch, dim * dim)
966
+ x = x[:, :: dim + 1]
967
+ assert x.shape == (batch, dim)
968
+ return x
969
+
970
+
971
+ def _whitening_metric(x: Tensor, num_groups: int):
972
+ """
973
+ Computes the "whitening metric", a value which will be 1.0 if all the eigenvalues of
974
+ of the centered feature covariance are the same within each group's covariance matrix
975
+ and also between groups.
976
+ Args:
977
+ x: a Tensor of shape (*, num_channels)
978
+ num_groups: the number of groups of channels, a number >=1 that divides num_channels
979
+ Returns:
980
+ Returns a scalar Tensor that will be 1.0 if the data is "perfectly white" and
981
+ greater than 1.0 otherwise.
982
+ """
983
+ assert x.dtype != torch.float16
984
+ x = x.reshape(-1, x.shape[-1])
985
+ num_frames, num_channels = x.shape
986
+ assert num_channels % num_groups == 0
987
+ channels_per_group = num_channels // num_groups
988
+ x = x.reshape(num_frames, num_groups, channels_per_group).transpose(0, 1)
989
+ # x now has shape (num_groups, num_frames, channels_per_group)
990
+ # subtract the mean so we use the centered, not uncentered, covariance.
991
+ # My experience has been that when we "mess with the gradients" like this,
992
+ # it's better not do anything that tries to move the mean around, because
993
+ # that can easily cause instability.
994
+ x = x - x.mean(dim=1, keepdim=True)
995
+ # x_covar: (num_groups, channels_per_group, channels_per_group)
996
+ x_covar = torch.matmul(x.transpose(1, 2), x)
997
+ x_covar_mean_diag = _diag(x_covar).mean()
998
+ # the following expression is what we'd get if we took the matrix product
999
+ # of each covariance and measured the mean of its trace, i.e.
1000
+ # the same as _diag(torch.matmul(x_covar, x_covar)).mean().
1001
+ x_covarsq_mean_diag = (x_covar**2).sum() / (num_groups * channels_per_group)
1002
+ # this metric will be >= 1.0; the larger it is, the less 'white' the data was.
1003
+ metric = x_covarsq_mean_diag / (x_covar_mean_diag**2 + 1.0e-20)
1004
+ return metric
1005
+
1006
+
1007
+ class WhiteningPenaltyFunction(torch.autograd.Function):
1008
+ @staticmethod
1009
+ def forward(ctx, x: Tensor, module: nn.Module) -> Tensor:
1010
+ ctx.save_for_backward(x)
1011
+ ctx.module = module
1012
+ return x
1013
+
1014
+ @staticmethod
1015
+ def backward(ctx, x_grad: Tensor):
1016
+ (x_orig,) = ctx.saved_tensors
1017
+ w = ctx.module
1018
+
1019
+ try:
1020
+ with torch.enable_grad():
1021
+ with torch_autocast(enabled=False):
1022
+ x_detached = x_orig.to(torch.float32).detach()
1023
+ x_detached.requires_grad = True
1024
+
1025
+ metric = _whitening_metric(x_detached, w.num_groups)
1026
+
1027
+ if random.random() < 0.005 or __name__ == "__main__":
1028
+ logging.info(
1029
+ f"Whitening: name={w.name}, num_groups={w.num_groups}, num_channels={x_orig.shape[-1]}, "
1030
+ f"metric={metric.item():.2f} vs. limit={float(w.whitening_limit)}"
1031
+ )
1032
+
1033
+ if metric < float(w.whitening_limit):
1034
+ w.prob = w.min_prob
1035
+ return x_grad, None
1036
+ else:
1037
+ w.prob = w.max_prob
1038
+ metric.backward()
1039
+ penalty_grad = x_detached.grad
1040
+ scale = float(w.grad_scale) * (
1041
+ x_grad.to(torch.float32).norm()
1042
+ / (penalty_grad.norm() + 1.0e-20)
1043
+ )
1044
+ penalty_grad = penalty_grad * scale
1045
+ return x_grad + penalty_grad.to(x_grad.dtype), None
1046
+ except Exception as e:
1047
+ logging.info(
1048
+ f"Caught exception in Whiten backward: {e}, size={list(x_grad.shape)}, will continue."
1049
+ )
1050
+ return x_grad, None
1051
+
1052
+
1053
+ class Whiten(nn.Module):
1054
+ def __init__(
1055
+ self,
1056
+ num_groups: int,
1057
+ whitening_limit: FloatLike,
1058
+ prob: Union[float, Tuple[float, float]],
1059
+ grad_scale: FloatLike,
1060
+ ):
1061
+ """
1062
+ Args:
1063
+ num_groups: the number of groups to divide the channel dim into before
1064
+ whitening. We will attempt to make the feature covariance
1065
+ within each group, after mean subtraction, as "white" as possible,
1066
+ while having the same trace across all groups.
1067
+ whitening_limit: a value greater than 1.0, that dictates how much
1068
+ freedom we have to violate the constraints. 1.0 would mean perfectly
1069
+ white, with exactly the same trace across groups; larger values
1070
+ give more freedom. E.g. 2.0.
1071
+ prob: the probability with which we apply the gradient modification
1072
+ (also affects the grad scale). May be supplied as a float,
1073
+ or as a pair (min_prob, max_prob)
1074
+
1075
+ grad_scale: determines the scale on the gradient term from this object,
1076
+ relative to the rest of the gradient on the attention weights.
1077
+ E.g. 0.02 (you may want to use smaller values than this if prob is large)
1078
+ """
1079
+ super(Whiten, self).__init__()
1080
+ assert num_groups >= 1
1081
+ assert float(whitening_limit) >= 1
1082
+ assert float(grad_scale) >= 0
1083
+ self.num_groups = num_groups
1084
+ self.whitening_limit = whitening_limit
1085
+ self.grad_scale = grad_scale
1086
+
1087
+ if isinstance(prob, float):
1088
+ prob = (prob, prob)
1089
+ self.min_prob, self.max_prob = prob
1090
+ assert 0 < self.min_prob <= self.max_prob <= 1
1091
+ self.prob = self.max_prob
1092
+ self.name = None # will be set in training loop
1093
+
1094
+ def forward(self, x: Tensor) -> Tensor:
1095
+ """
1096
+ In the forward pass, this function just returns the input unmodified.
1097
+ In the backward pass, it will modify the gradients to ensure that the
1098
+ distribution in each group has close to (lambda times I) as the covariance
1099
+ after mean subtraction, with the same lambda across groups.
1100
+ For whitening_limit > 1, there will be more freedom to violate this
1101
+ constraint.
1102
+
1103
+ Args:
1104
+ x: the input of shape (*, num_channels)
1105
+
1106
+ Returns:
1107
+ x, unmodified. You should make sure
1108
+ you use the returned value, or the graph will be freed
1109
+ and nothing will happen in backprop.
1110
+ """
1111
+ grad_scale = float(self.grad_scale)
1112
+ if not x.requires_grad or random.random() > self.prob or grad_scale == 0:
1113
+ return _no_op(x)
1114
+ else:
1115
+ return WhiteningPenaltyFunction.apply(x, self)
1116
+
1117
+
1118
+ class WithLoss(torch.autograd.Function):
1119
+ @staticmethod
1120
+ def forward(ctx, x: Tensor, y: Tensor, name: str):
1121
+ ctx.y_shape = y.shape
1122
+ if random.random() < 0.002 and name is not None:
1123
+ loss_sum = y.sum().item()
1124
+ logging.info(f"WithLoss: name={name}, loss-sum={loss_sum:.3e}")
1125
+ return x
1126
+
1127
+ @staticmethod
1128
+ def backward(ctx, ans_grad: Tensor):
1129
+ return (
1130
+ ans_grad,
1131
+ torch.ones(ctx.y_shape, dtype=ans_grad.dtype, device=ans_grad.device),
1132
+ None,
1133
+ )
1134
+
1135
+
1136
+ def with_loss(x, y, name):
1137
+ # returns x but adds y.sum() to the loss function.
1138
+ return WithLoss.apply(x, y, name)
1139
+
1140
+
1141
+ class ScaleGradFunction(torch.autograd.Function):
1142
+ @staticmethod
1143
+ def forward(ctx, x: Tensor, alpha: float) -> Tensor:
1144
+ ctx.alpha = alpha
1145
+ return x
1146
+
1147
+ @staticmethod
1148
+ def backward(ctx, grad: Tensor):
1149
+ return grad * ctx.alpha, None
1150
+
1151
+
1152
+ def scale_grad(x: Tensor, alpha: float):
1153
+ return ScaleGradFunction.apply(x, alpha)
1154
+
1155
+
1156
+ class ScaleGrad(nn.Module):
1157
+ def __init__(self, alpha: float):
1158
+ super().__init__()
1159
+ self.alpha = alpha
1160
+
1161
+ def forward(self, x: Tensor) -> Tensor:
1162
+ if torch.jit.is_scripting() or torch.jit.is_tracing() or not self.training:
1163
+ return x
1164
+ return scale_grad(x, self.alpha)
1165
+
1166
+
1167
+ class LimitParamValue(torch.autograd.Function):
1168
+ @staticmethod
1169
+ def forward(ctx, x: Tensor, min: float, max: float):
1170
+ ctx.save_for_backward(x)
1171
+ assert max >= min
1172
+ ctx.min = min
1173
+ ctx.max = max
1174
+ return x
1175
+
1176
+ @staticmethod
1177
+ def backward(ctx, x_grad: Tensor):
1178
+ (x,) = ctx.saved_tensors
1179
+ # where x < ctx.min, ensure all grads are negative (this will tend to make
1180
+ # x more positive).
1181
+ x_grad = x_grad * torch.where(
1182
+ torch.logical_and(x_grad > 0, x < ctx.min), -1.0, 1.0
1183
+ )
1184
+ # where x > ctx.max, ensure all grads are positive (this will tend to make
1185
+ # x more negative).
1186
+ x_grad *= torch.where(torch.logical_and(x_grad < 0, x > ctx.max), -1.0, 1.0)
1187
+ return x_grad, None, None
1188
+
1189
+
1190
+ def limit_param_value(
1191
+ x: Tensor, min: float, max: float, prob: float = 0.6, training: bool = True
1192
+ ):
1193
+ # You apply this to (typically) an nn.Parameter during training to ensure that its
1194
+ # (elements mostly) stays within a supplied range. This is done by modifying the
1195
+ # gradients in backprop.
1196
+ # It's not necessary to do this on every batch: do it only some of the time,
1197
+ # to save a little time.
1198
+ if training and random.random() < prob:
1199
+ return LimitParamValue.apply(x, min, max)
1200
+ else:
1201
+ return x
1202
+
1203
+
1204
+ def _no_op(x: Tensor) -> Tensor:
1205
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1206
+ return x
1207
+ else:
1208
+ # a no-op function that will have a node in the autograd graph,
1209
+ # to avoid certain bugs relating to backward hooks
1210
+ return x.chunk(1, dim=-1)[0]
1211
+
1212
+
1213
+ class Identity(torch.nn.Module):
1214
+ def __init__(self):
1215
+ super(Identity, self).__init__()
1216
+
1217
+ def forward(self, x):
1218
+ return _no_op(x)
1219
+
1220
+
1221
+ class DoubleSwishFunction(torch.autograd.Function):
1222
+ """
1223
+ double_swish(x) = x * torch.sigmoid(x-1)
1224
+
1225
+ This is a definition, originally motivated by its close numerical
1226
+ similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
1227
+
1228
+ Memory-efficient derivative computation:
1229
+ double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
1230
+ double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
1231
+ Now, s'(x) = s(x) * (1-s(x)).
1232
+ double_swish'(x) = x * s'(x) + s(x).
1233
+ = x * s(x) * (1-s(x)) + s(x).
1234
+ = double_swish(x) * (1-s(x)) + s(x)
1235
+ ... so we just need to remember s(x) but not x itself.
1236
+ """
1237
+
1238
+ @staticmethod
1239
+ def forward(ctx, x: Tensor) -> Tensor:
1240
+ requires_grad = x.requires_grad
1241
+ if x.dtype == torch.float16 or x.dtype == torch.bfloat16:
1242
+ x = x.to(torch.float32)
1243
+
1244
+ s = torch.sigmoid(x - 1.0)
1245
+ y = x * s
1246
+
1247
+ if requires_grad:
1248
+ deriv = y * (1 - s) + s
1249
+
1250
+ # notes on derivative of x * sigmoid(x - 1):
1251
+ # https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
1252
+ # min \simeq -0.043638. Take floor as -0.044 so it's a lower bund
1253
+ # max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
1254
+ # the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
1255
+ # floors), should be expectation-preserving.
1256
+ floor = -0.044
1257
+ ceil = 1.2
1258
+ d_scaled = (deriv - floor) * (255.0 / (ceil - floor)) + torch.rand_like(
1259
+ deriv
1260
+ )
1261
+ if __name__ == "__main__":
1262
+ # for self-testing only.
1263
+ assert d_scaled.min() >= 0.0
1264
+ assert d_scaled.max() < 256.0
1265
+ d_int = d_scaled.to(torch.uint8)
1266
+ ctx.save_for_backward(d_int)
1267
+ if x.dtype == torch.float16 or torch.is_autocast_enabled():
1268
+ y = y.to(torch.float16)
1269
+ return y
1270
+
1271
+ @staticmethod
1272
+ def backward(ctx, y_grad: Tensor) -> Tensor:
1273
+ (d,) = ctx.saved_tensors
1274
+ # the same constants as used in forward pass.
1275
+ floor = -0.043637
1276
+ ceil = 1.2
1277
+
1278
+ d = d * ((ceil - floor) / 255.0) + floor
1279
+ return y_grad * d
1280
+
1281
+
1282
+ class DoubleSwish(torch.nn.Module):
1283
+ def __init__(self):
1284
+ super().__init__()
1285
+
1286
+ def forward(self, x: Tensor) -> Tensor:
1287
+ """Return double-swish activation function which is an approximation to Swish(Swish(x)),
1288
+ that we approximate closely with x * sigmoid(x-1).
1289
+ """
1290
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1291
+ return x * torch.sigmoid(x - 1.0)
1292
+ return DoubleSwishFunction.apply(x)
1293
+
1294
+
1295
+ # Dropout2 is just like normal dropout, except it supports schedules on the dropout rates.
1296
+ class Dropout2(nn.Module):
1297
+ def __init__(self, p: FloatLike):
1298
+ super().__init__()
1299
+ self.p = p
1300
+
1301
+ def forward(self, x: Tensor) -> Tensor:
1302
+ return torch.nn.functional.dropout(x, p=float(self.p), training=self.training)
1303
+
1304
+
1305
+ class MulForDropout3(torch.autograd.Function):
1306
+ # returns (x * y * alpha) where alpha is a float and y doesn't require
1307
+ # grad and is zero-or-one.
1308
+ @staticmethod
1309
+ @custom_fwd
1310
+ def forward(ctx, x, y, alpha):
1311
+ assert not y.requires_grad
1312
+ ans = x * y * alpha
1313
+ ctx.save_for_backward(ans)
1314
+ ctx.alpha = alpha
1315
+ return ans
1316
+
1317
+ @staticmethod
1318
+ @custom_bwd
1319
+ def backward(ctx, ans_grad):
1320
+ (ans,) = ctx.saved_tensors
1321
+ x_grad = ctx.alpha * ans_grad * (ans != 0)
1322
+ return x_grad, None, None
1323
+
1324
+
1325
+ # Dropout3 is just like normal dropout, except it supports schedules on the dropout rates,
1326
+ # and it lets you choose one dimension to share the dropout mask over
1327
+ class Dropout3(nn.Module):
1328
+ def __init__(self, p: FloatLike, shared_dim: int):
1329
+ super().__init__()
1330
+ self.p = p
1331
+ self.shared_dim = shared_dim
1332
+
1333
+ def forward(self, x: Tensor) -> Tensor:
1334
+ p = float(self.p)
1335
+ if not self.training or p == 0:
1336
+ return _no_op(x)
1337
+ scale = 1.0 / (1 - p)
1338
+ rand_shape = list(x.shape)
1339
+ rand_shape[self.shared_dim] = 1
1340
+ mask = torch.rand(*rand_shape, device=x.device) > p
1341
+ ans = MulForDropout3.apply(x, mask, scale)
1342
+ return ans
1343
+
1344
+
1345
+ class SwooshLFunction(torch.autograd.Function):
1346
+ """
1347
+ swoosh_l(x) = log(1 + exp(x-4)) - 0.08*x - 0.035
1348
+ """
1349
+
1350
+ @staticmethod
1351
+ def forward(ctx, x: Tensor) -> Tensor:
1352
+ requires_grad = x.requires_grad
1353
+ if x.dtype == torch.float16 or x.dtype == torch.bfloat16:
1354
+ x = x.to(torch.float32)
1355
+
1356
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1357
+
1358
+ coeff = -0.08
1359
+
1360
+ with torch_autocast(enabled=False):
1361
+ with torch.enable_grad():
1362
+ x = x.detach()
1363
+ x.requires_grad = True
1364
+ y = torch.logaddexp(zero, x - 4.0) + coeff * x - 0.035
1365
+
1366
+ if not requires_grad:
1367
+ return y
1368
+
1369
+ y.backward(gradient=torch.ones_like(y))
1370
+
1371
+ grad = x.grad
1372
+ floor = coeff
1373
+ ceil = 1.0 + coeff + 0.005
1374
+
1375
+ d_scaled = (grad - floor) * (255.0 / (ceil - floor)) + torch.rand_like(
1376
+ grad
1377
+ )
1378
+ if __name__ == "__main__":
1379
+ # for self-testing only.
1380
+ assert d_scaled.min() >= 0.0
1381
+ assert d_scaled.max() < 256.0
1382
+
1383
+ d_int = d_scaled.to(torch.uint8)
1384
+ ctx.save_for_backward(d_int)
1385
+ if x.dtype == torch.float16 or torch.is_autocast_enabled():
1386
+ y = y.to(torch.get_autocast_gpu_dtype())
1387
+ return y
1388
+
1389
+ @staticmethod
1390
+ def backward(ctx, y_grad: Tensor) -> Tensor:
1391
+ (d,) = ctx.saved_tensors
1392
+ # the same constants as used in forward pass.
1393
+
1394
+ coeff = -0.08
1395
+ floor = coeff
1396
+ ceil = 1.0 + coeff + 0.005
1397
+ d = d * ((ceil - floor) / 255.0) + floor
1398
+ return y_grad * d
1399
+
1400
+
1401
+ class SwooshL(torch.nn.Module):
1402
+ def forward(self, x: Tensor) -> Tensor:
1403
+ """Return Swoosh-L activation."""
1404
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1405
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1406
+ return logaddexp(zero, x - 4.0) - 0.08 * x - 0.035
1407
+ if not x.requires_grad:
1408
+ return k2.swoosh_l_forward(x).to(x.dtype)
1409
+ else:
1410
+ return k2.swoosh_l(x).to(x.dtype)
1411
+ # return SwooshLFunction.apply(x)
1412
+
1413
+
1414
+ class SwooshLOnnx(torch.nn.Module):
1415
+ def forward(self, x: Tensor) -> Tensor:
1416
+ """Return Swoosh-L activation."""
1417
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1418
+ return logaddexp_onnx(zero, x - 4.0) - 0.08 * x - 0.035
1419
+
1420
+
1421
+ class SwooshRFunction(torch.autograd.Function):
1422
+ """
1423
+ swoosh_r(x) = log(1 + exp(x-1)) - 0.08*x - 0.313261687
1424
+
1425
+ derivatives are between -0.08 and 0.92.
1426
+ """
1427
+
1428
+ @staticmethod
1429
+ def forward(ctx, x: Tensor) -> Tensor:
1430
+ requires_grad = x.requires_grad
1431
+
1432
+ if x.dtype == torch.float16 or x.dtype == torch.bfloat16:
1433
+ x = x.to(torch.float32)
1434
+
1435
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1436
+
1437
+ with torch_autocast(enabled=False):
1438
+ with torch.enable_grad():
1439
+ x = x.detach()
1440
+ x.requires_grad = True
1441
+ y = torch.logaddexp(zero, x - 1.0) - 0.08 * x - 0.313261687
1442
+
1443
+ if not requires_grad:
1444
+ return y
1445
+ y.backward(gradient=torch.ones_like(y))
1446
+
1447
+ grad = x.grad
1448
+ floor = -0.08
1449
+ ceil = 0.925
1450
+
1451
+ d_scaled = (grad - floor) * (255.0 / (ceil - floor)) + torch.rand_like(
1452
+ grad
1453
+ )
1454
+ if __name__ == "__main__":
1455
+ # for self-testing only.
1456
+ assert d_scaled.min() >= 0.0
1457
+ assert d_scaled.max() < 256.0
1458
+
1459
+ d_int = d_scaled.to(torch.uint8)
1460
+ ctx.save_for_backward(d_int)
1461
+ if x.dtype == torch.float16 or torch.is_autocast_enabled():
1462
+ y = y.to(torch.get_autocast_gpu_dtype())
1463
+ return y
1464
+
1465
+ @staticmethod
1466
+ def backward(ctx, y_grad: Tensor) -> Tensor:
1467
+ (d,) = ctx.saved_tensors
1468
+ # the same constants as used in forward pass.
1469
+ floor = -0.08
1470
+ ceil = 0.925
1471
+ d = d * ((ceil - floor) / 255.0) + floor
1472
+ return y_grad * d
1473
+
1474
+
1475
+ class SwooshR(torch.nn.Module):
1476
+ def forward(self, x: Tensor) -> Tensor:
1477
+ """Return Swoosh-R activation."""
1478
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1479
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1480
+ return logaddexp(zero, x - 1.0) - 0.08 * x - 0.313261687
1481
+ if not x.requires_grad:
1482
+ return k2.swoosh_r_forward(x).to(x.dtype)
1483
+ else:
1484
+ return k2.swoosh_r(x).to(x.dtype)
1485
+ # return SwooshRFunction.apply(x)
1486
+
1487
+
1488
+ class SwooshROnnx(torch.nn.Module):
1489
+ def forward(self, x: Tensor) -> Tensor:
1490
+ """Return Swoosh-R activation."""
1491
+ zero = torch.tensor(0.0, dtype=x.dtype, device=x.device)
1492
+ return logaddexp_onnx(zero, x - 1.0) - 0.08 * x - 0.313261687
1493
+
1494
+
1495
+ # simple version of SwooshL that does not redefine the backprop, used in
1496
+ # ActivationDropoutAndLinearFunction.
1497
+ def SwooshLForward(x: Tensor):
1498
+ x_offset = x - 4.0
1499
+ log_sum = (1.0 + x_offset.exp()).log().to(x.dtype)
1500
+ log_sum = torch.where(log_sum == float("inf"), x_offset, log_sum)
1501
+ return log_sum - 0.08 * x - 0.035
1502
+
1503
+
1504
+ # simple version of SwooshR that does not redefine the backprop, used in
1505
+ # ActivationDropoutAndLinearFunction.
1506
+ def SwooshRForward(x: Tensor):
1507
+ x_offset = x - 1.0
1508
+ log_sum = (1.0 + x_offset.exp()).log().to(x.dtype)
1509
+ log_sum = torch.where(log_sum == float("inf"), x_offset, log_sum)
1510
+ return log_sum - 0.08 * x - 0.313261687
1511
+
1512
+
1513
+ class ActivationDropoutAndLinearFunction(torch.autograd.Function):
1514
+ @staticmethod
1515
+ @custom_fwd
1516
+ def forward(
1517
+ ctx,
1518
+ x: Tensor,
1519
+ weight: Tensor,
1520
+ bias: Optional[Tensor],
1521
+ activation: str,
1522
+ dropout_p: float,
1523
+ dropout_shared_dim: Optional[int],
1524
+ ):
1525
+ if dropout_p != 0.0:
1526
+ dropout_shape = list(x.shape)
1527
+ if dropout_shared_dim is not None:
1528
+ dropout_shape[dropout_shared_dim] = 1
1529
+ # else it won't be very memory efficient.
1530
+ dropout_mask = (1.0 / (1.0 - dropout_p)) * (
1531
+ torch.rand(*dropout_shape, device=x.device, dtype=x.dtype) > dropout_p
1532
+ )
1533
+ else:
1534
+ dropout_mask = None
1535
+
1536
+ ctx.save_for_backward(x, weight, bias, dropout_mask)
1537
+
1538
+ ctx.activation = activation
1539
+
1540
+ forward_activation_dict = {
1541
+ "SwooshL": k2.swoosh_l_forward,
1542
+ "SwooshR": k2.swoosh_r_forward,
1543
+ }
1544
+ # it will raise a KeyError if this fails. This will be an error. We let it
1545
+ # propagate to the user.
1546
+ activation_func = forward_activation_dict[activation]
1547
+ x = activation_func(x)
1548
+ if dropout_mask is not None:
1549
+ x = x * dropout_mask
1550
+ x = torch.nn.functional.linear(x, weight, bias)
1551
+ return x
1552
+
1553
+ @staticmethod
1554
+ @custom_bwd
1555
+ def backward(ctx, ans_grad: Tensor):
1556
+ saved = ctx.saved_tensors
1557
+ x, weight, bias, dropout_mask = saved
1558
+
1559
+ forward_and_deriv_activation_dict = {
1560
+ "SwooshL": k2.swoosh_l_forward_and_deriv,
1561
+ "SwooshR": k2.swoosh_r_forward_and_deriv,
1562
+ }
1563
+ # the following lines a KeyError if the activation is unrecognized.
1564
+ # This will be an error. We let it propagate to the user.
1565
+ func = forward_and_deriv_activation_dict[ctx.activation]
1566
+
1567
+ y, func_deriv = func(x)
1568
+ if dropout_mask is not None:
1569
+ y = y * dropout_mask
1570
+ # now compute derivative of y w.r.t. weight and bias..
1571
+ # y: (..., in_channels), ans_grad: (..., out_channels),
1572
+ out_channels, in_channels = weight.shape
1573
+
1574
+ in_channels = y.shape[-1]
1575
+ g = ans_grad.reshape(-1, out_channels)
1576
+ weight_deriv = torch.matmul(g.t(), y.reshape(-1, in_channels))
1577
+ y_deriv = torch.matmul(ans_grad, weight)
1578
+ bias_deriv = None if bias is None else g.sum(dim=0)
1579
+ x_deriv = y_deriv * func_deriv
1580
+ if dropout_mask is not None:
1581
+ # order versus func_deriv does not matter
1582
+ x_deriv = x_deriv * dropout_mask
1583
+
1584
+ return x_deriv, weight_deriv, bias_deriv, None, None, None
1585
+
1586
+
1587
+ class ActivationDropoutAndLinear(torch.nn.Module):
1588
+ """
1589
+ This merges an activation function followed by dropout and then a nn.Linear module;
1590
+ it does so in a memory efficient way so that it only stores the input to the whole
1591
+ module. If activation == SwooshL and dropout_shared_dim != None, this will be
1592
+ equivalent to:
1593
+ nn.Sequential(SwooshL(),
1594
+ Dropout3(dropout_p, shared_dim=dropout_shared_dim),
1595
+ ScaledLinear(in_channels, out_channels, bias=bias,
1596
+ initial_scale=initial_scale))
1597
+ If dropout_shared_dim is None, the dropout would be equivalent to
1598
+ Dropout2(dropout_p). Note: Dropout3 will be more memory efficient as the dropout
1599
+ mask is smaller.
1600
+
1601
+ Args:
1602
+ in_channels: number of input channels, e.g. 256
1603
+ out_channels: number of output channels, e.g. 256
1604
+ bias: if true, have a bias
1605
+ activation: the activation function, for now just support SwooshL.
1606
+ dropout_p: the dropout probability or schedule (happens after nonlinearity).
1607
+ dropout_shared_dim: the dimension, if any, across which the dropout mask is
1608
+ shared (e.g. the time dimension). If None, this may be less memory
1609
+ efficient if there are modules before this one that cache the input
1610
+ for their backprop (e.g. Balancer or Whiten).
1611
+ """
1612
+
1613
+ def __init__(
1614
+ self,
1615
+ in_channels: int,
1616
+ out_channels: int,
1617
+ bias: bool = True,
1618
+ activation: str = "SwooshL",
1619
+ dropout_p: FloatLike = 0.0,
1620
+ dropout_shared_dim: Optional[int] = -1,
1621
+ initial_scale: float = 1.0,
1622
+ ):
1623
+ super().__init__()
1624
+ # create a temporary module of nn.Linear that we'll steal the
1625
+ # weights and bias from
1626
+ l = ScaledLinear(
1627
+ in_channels, out_channels, bias=bias, initial_scale=initial_scale
1628
+ )
1629
+
1630
+ self.weight = l.weight
1631
+ # register_parameter properly handles making it a parameter when l.bias
1632
+ # is None. I think there is some reason for doing it this way rather
1633
+ # than just setting it to None but I don't know what it is, maybe
1634
+ # something to do with exporting the module..
1635
+ self.register_parameter("bias", l.bias)
1636
+
1637
+ self.activation = activation
1638
+ self.dropout_p = dropout_p
1639
+ self.dropout_shared_dim = dropout_shared_dim
1640
+
1641
+ def forward(self, x: Tensor):
1642
+ if not self.training or torch.jit.is_scripting() or torch.jit.is_tracing():
1643
+ if self.activation == "SwooshL":
1644
+ x = SwooshLForward(x)
1645
+ elif self.activation == "SwooshR":
1646
+ x = SwooshRForward(x)
1647
+ else:
1648
+ assert False, self.activation
1649
+ return torch.nn.functional.linear(x, self.weight, self.bias)
1650
+
1651
+ return ActivationDropoutAndLinearFunction.apply(
1652
+ x,
1653
+ self.weight,
1654
+ self.bias,
1655
+ self.activation,
1656
+ float(self.dropout_p),
1657
+ self.dropout_shared_dim,
1658
+ )
1659
+
1660
+
1661
+ def convert_num_channels(x: Tensor, num_channels: int) -> Tensor:
1662
+ if num_channels <= x.shape[-1]:
1663
+ return x[..., :num_channels]
1664
+ else:
1665
+ shape = list(x.shape)
1666
+ shape[-1] = num_channels - shape[-1]
1667
+ zeros = torch.zeros(shape, dtype=x.dtype, device=x.device)
1668
+ return torch.cat((x, zeros), dim=-1)
1669
+
1670
+
1671
+ def _test_whiten():
1672
+ for proportion in [0.1, 0.5, 10.0]:
1673
+ logging.info(f"_test_whiten(): proportion = {proportion}")
1674
+ x = torch.randn(100, 128)
1675
+ direction = torch.randn(128)
1676
+ coeffs = torch.randn(100, 1)
1677
+ x += proportion * direction * coeffs
1678
+
1679
+ x.requires_grad = True
1680
+
1681
+ m = Whiten(
1682
+ 1, 5.0, prob=1.0, grad_scale=0.1 # num_groups # whitening_limit,
1683
+ ) # grad_scale
1684
+
1685
+ for _ in range(4):
1686
+ y = m(x)
1687
+
1688
+ y_grad = torch.randn_like(x)
1689
+ y.backward(gradient=y_grad)
1690
+
1691
+ if proportion < 0.2:
1692
+ assert torch.allclose(x.grad, y_grad)
1693
+ elif proportion > 1.0:
1694
+ assert not torch.allclose(x.grad, y_grad)
1695
+
1696
+
1697
+ def _test_balancer_sign():
1698
+ probs = torch.arange(0, 1, 0.01)
1699
+ N = 1000
1700
+ x = 1.0 * ((2.0 * (torch.rand(probs.numel(), N) < probs.unsqueeze(-1))) - 1.0)
1701
+ x = x.detach()
1702
+ x.requires_grad = True
1703
+ m = Balancer(
1704
+ probs.numel(),
1705
+ channel_dim=0,
1706
+ min_positive=0.05,
1707
+ max_positive=0.95,
1708
+ min_abs=0.0,
1709
+ prob=1.0,
1710
+ )
1711
+
1712
+ y_grad = torch.sign(torch.randn(probs.numel(), N))
1713
+
1714
+ y = m(x)
1715
+ y.backward(gradient=y_grad)
1716
+ print("_test_balancer_sign: x = ", x)
1717
+ print("_test_balancer_sign: y grad = ", y_grad)
1718
+ print("_test_balancer_sign: x grad = ", x.grad)
1719
+
1720
+
1721
+ def _test_balancer_magnitude():
1722
+ magnitudes = torch.arange(0, 1, 0.01)
1723
+ N = 1000
1724
+ x = torch.sign(torch.randn(magnitudes.numel(), N)) * magnitudes.unsqueeze(-1)
1725
+ x = x.detach()
1726
+ x.requires_grad = True
1727
+ m = Balancer(
1728
+ magnitudes.numel(),
1729
+ channel_dim=0,
1730
+ min_positive=0.0,
1731
+ max_positive=1.0,
1732
+ min_abs=0.2,
1733
+ max_abs=0.7,
1734
+ prob=1.0,
1735
+ )
1736
+
1737
+ y_grad = torch.sign(torch.randn(magnitudes.numel(), N))
1738
+
1739
+ y = m(x)
1740
+ y.backward(gradient=y_grad)
1741
+ print("_test_balancer_magnitude: x = ", x)
1742
+ print("_test_balancer_magnitude: y grad = ", y_grad)
1743
+ print("_test_balancer_magnitude: x grad = ", x.grad)
1744
+
1745
+
1746
+ def _test_double_swish_deriv():
1747
+ x = torch.randn(10, 12, dtype=torch.double) * 3.0
1748
+ x.requires_grad = True
1749
+ m = DoubleSwish()
1750
+
1751
+ tol = (1.2 - (-0.043637)) / 255.0
1752
+ torch.autograd.gradcheck(m, x, atol=tol)
1753
+
1754
+ # for self-test.
1755
+ x = torch.randn(1000, 1000, dtype=torch.double) * 3.0
1756
+ x.requires_grad = True
1757
+ y = m(x)
1758
+
1759
+
1760
+ def _test_swooshl_deriv():
1761
+ x = torch.randn(10, 12, dtype=torch.double) * 3.0
1762
+ x.requires_grad = True
1763
+ m = SwooshL()
1764
+
1765
+ tol = 1.0 / 255.0
1766
+ torch.autograd.gradcheck(m, x, atol=tol, eps=0.01)
1767
+
1768
+ # for self-test.
1769
+ x = torch.randn(1000, 1000, dtype=torch.double) * 3.0
1770
+ x.requires_grad = True
1771
+ y = m(x)
1772
+
1773
+
1774
+ def _test_swooshr_deriv():
1775
+ x = torch.randn(10, 12, dtype=torch.double) * 3.0
1776
+ x.requires_grad = True
1777
+ m = SwooshR()
1778
+
1779
+ tol = 1.0 / 255.0
1780
+ torch.autograd.gradcheck(m, x, atol=tol, eps=0.01)
1781
+
1782
+ # for self-test.
1783
+ x = torch.randn(1000, 1000, dtype=torch.double) * 3.0
1784
+ x.requires_grad = True
1785
+ y = m(x)
1786
+
1787
+
1788
+ def _test_softmax():
1789
+ a = torch.randn(2, 10, dtype=torch.float64)
1790
+ b = a.clone()
1791
+ a.requires_grad = True
1792
+ b.requires_grad = True
1793
+ a.softmax(dim=1)[:, 0].sum().backward()
1794
+ print("a grad = ", a.grad)
1795
+ softmax(b, dim=1)[:, 0].sum().backward()
1796
+ print("b grad = ", b.grad)
1797
+ assert torch.allclose(a.grad, b.grad)
1798
+
1799
+
1800
+ def _test_piecewise_linear():
1801
+ p = PiecewiseLinear((0, 10.0))
1802
+ for x in [-100, 0, 100]:
1803
+ assert p(x) == 10.0
1804
+ p = PiecewiseLinear((0, 10.0), (1, 0.0))
1805
+ for x, y in [(-100, 10.0), (0, 10.0), (0.5, 5.0), (1, 0.0), (2, 0.0)]:
1806
+ print("x, y = ", x, y)
1807
+ assert p(x) == y, (x, p(x), y)
1808
+
1809
+ q = PiecewiseLinear((0.5, 15.0), (0.6, 1.0))
1810
+ x_vals = [-1.0, 0.0, 0.1, 0.2, 0.5, 0.6, 0.7, 0.9, 1.0, 2.0]
1811
+ pq = p.max(q)
1812
+ for x in x_vals:
1813
+ y1 = max(p(x), q(x))
1814
+ y2 = pq(x)
1815
+ assert abs(y1 - y2) < 0.001
1816
+ pq = p.min(q)
1817
+ for x in x_vals:
1818
+ y1 = min(p(x), q(x))
1819
+ y2 = pq(x)
1820
+ assert abs(y1 - y2) < 0.001
1821
+ pq = p + q
1822
+ for x in x_vals:
1823
+ y1 = p(x) + q(x)
1824
+ y2 = pq(x)
1825
+ assert abs(y1 - y2) < 0.001
1826
+
1827
+
1828
+ def _test_activation_dropout_and_linear():
1829
+ in_channels = 20
1830
+ out_channels = 30
1831
+
1832
+ for bias in [True, False]:
1833
+ # actually we don't test for dropout_p != 0.0 because forward functions will give
1834
+ # different answers. This is because we are using the k2 implementation of
1835
+ # swoosh_l an swoosh_r inside SwooshL() and SwooshR(), and they call randn()
1836
+ # internally, messing up the random state.
1837
+ for dropout_p in [0.0]:
1838
+ for activation in ["SwooshL", "SwooshR"]:
1839
+ m1 = nn.Sequential(
1840
+ SwooshL() if activation == "SwooshL" else SwooshR(),
1841
+ Dropout3(p=dropout_p, shared_dim=-1),
1842
+ ScaledLinear(
1843
+ in_channels, out_channels, bias=bias, initial_scale=0.5
1844
+ ),
1845
+ )
1846
+ m2 = ActivationDropoutAndLinear(
1847
+ in_channels,
1848
+ out_channels,
1849
+ bias=bias,
1850
+ initial_scale=0.5,
1851
+ activation=activation,
1852
+ dropout_p=dropout_p,
1853
+ )
1854
+ with torch.no_grad():
1855
+ m2.weight[:] = m1[2].weight
1856
+ if bias:
1857
+ m2.bias[:] = m1[2].bias
1858
+ # make sure forward gives same result.
1859
+ x1 = torch.randn(10, in_channels)
1860
+ x1.requires_grad = True
1861
+
1862
+ # TEMP.
1863
+ assert torch.allclose(
1864
+ SwooshRFunction.apply(x1), SwooshRForward(x1), atol=1.0e-03
1865
+ )
1866
+
1867
+ x2 = x1.clone().detach()
1868
+ x2.requires_grad = True
1869
+ seed = 10
1870
+ torch.manual_seed(seed)
1871
+ y1 = m1(x1)
1872
+ y_grad = torch.randn_like(y1)
1873
+ y1.backward(gradient=y_grad)
1874
+ torch.manual_seed(seed)
1875
+ y2 = m2(x2)
1876
+ y2.backward(gradient=y_grad)
1877
+
1878
+ print(
1879
+ f"bias = {bias}, dropout_p = {dropout_p}, activation = {activation}"
1880
+ )
1881
+ print("y1 = ", y1)
1882
+ print("y2 = ", y2)
1883
+ assert torch.allclose(y1, y2, atol=0.02)
1884
+ assert torch.allclose(m1[2].weight.grad, m2.weight.grad, atol=1.0e-05)
1885
+ if bias:
1886
+ assert torch.allclose(m1[2].bias.grad, m2.bias.grad, atol=1.0e-05)
1887
+ print("x1.grad = ", x1.grad)
1888
+ print("x2.grad = ", x2.grad)
1889
+
1890
+ def isclose(a, b):
1891
+ # return true if cosine similarity is > 0.9.
1892
+ return (a * b).sum() > 0.9 * ((a**2).sum() * (b**2).sum()).sqrt()
1893
+
1894
+ # the SwooshL() implementation has a noisy gradient due to 1-byte
1895
+ # storage of it.
1896
+ assert isclose(x1.grad, x2.grad)
1897
+
1898
+
1899
+ if __name__ == "__main__":
1900
+ logging.getLogger().setLevel(logging.INFO)
1901
+ torch.set_num_threads(1)
1902
+ torch.set_num_interop_threads(1)
1903
+ _test_piecewise_linear()
1904
+ _test_softmax()
1905
+ _test_whiten()
1906
+ _test_balancer_sign()
1907
+ _test_balancer_magnitude()
1908
+ _test_double_swish_deriv()
1909
+ _test_swooshr_deriv()
1910
+ _test_swooshl_deriv()
1911
+ _test_activation_dropout_and_linear()
wakeup_model/zipformer/subsampling.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2023 Xiaomi Corp. (authors: Daniel Povey,
3
+ # Zengwei Yao)
4
+ #
5
+ # See ../../../../LICENSE for clarification regarding multiple authors
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import warnings
20
+ from typing import Tuple
21
+
22
+ import torch
23
+ from scaling import (
24
+ Balancer,
25
+ BiasNorm,
26
+ Dropout3,
27
+ FloatLike,
28
+ Optional,
29
+ ScaledConv2d,
30
+ ScaleGrad,
31
+ ScheduledFloat,
32
+ SwooshL,
33
+ SwooshR,
34
+ Whiten,
35
+ )
36
+ from torch import Tensor, nn
37
+
38
+
39
+ class ConvNeXt(nn.Module):
40
+ """
41
+ Our interpretation of the ConvNeXt module as used in https://arxiv.org/pdf/2206.14747.pdf
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ channels: int,
47
+ hidden_ratio: int = 3,
48
+ kernel_size: Tuple[int, int] = (7, 7),
49
+ layerdrop_rate: FloatLike = None,
50
+ ):
51
+ super().__init__()
52
+ self.padding = ((kernel_size[0] - 1) // 2, (kernel_size[1] - 1) // 2)
53
+ hidden_channels = channels * hidden_ratio
54
+ if layerdrop_rate is None:
55
+ layerdrop_rate = ScheduledFloat((0.0, 0.2), (20000.0, 0.015))
56
+ self.layerdrop_rate = layerdrop_rate
57
+
58
+ self.depthwise_conv = nn.Conv2d(
59
+ in_channels=channels,
60
+ out_channels=channels,
61
+ groups=channels,
62
+ kernel_size=kernel_size,
63
+ padding=self.padding,
64
+ )
65
+
66
+ self.pointwise_conv1 = nn.Conv2d(
67
+ in_channels=channels, out_channels=hidden_channels, kernel_size=1
68
+ )
69
+
70
+ self.hidden_balancer = Balancer(
71
+ hidden_channels,
72
+ channel_dim=1,
73
+ min_positive=0.3,
74
+ max_positive=1.0,
75
+ min_abs=0.75,
76
+ max_abs=5.0,
77
+ )
78
+
79
+ self.activation = SwooshL()
80
+ self.pointwise_conv2 = ScaledConv2d(
81
+ in_channels=hidden_channels,
82
+ out_channels=channels,
83
+ kernel_size=1,
84
+ initial_scale=0.01,
85
+ )
86
+
87
+ self.out_balancer = Balancer(
88
+ channels,
89
+ channel_dim=1,
90
+ min_positive=0.4,
91
+ max_positive=0.6,
92
+ min_abs=1.0,
93
+ max_abs=6.0,
94
+ )
95
+ self.out_whiten = Whiten(
96
+ num_groups=1,
97
+ whitening_limit=5.0,
98
+ prob=(0.025, 0.25),
99
+ grad_scale=0.01,
100
+ )
101
+
102
+ def forward(self, x: Tensor) -> Tensor:
103
+ if torch.jit.is_scripting() or torch.jit.is_tracing() or not self.training:
104
+ return self.forward_internal(x)
105
+ layerdrop_rate = float(self.layerdrop_rate)
106
+
107
+ if layerdrop_rate != 0.0:
108
+ batch_size = x.shape[0]
109
+ mask = (
110
+ torch.rand((batch_size, 1, 1, 1), dtype=x.dtype, device=x.device)
111
+ > layerdrop_rate
112
+ )
113
+ else:
114
+ mask = None
115
+ # turns out this caching idea does not work with --world-size > 1
116
+ # return caching_eval(self.forward_internal, x, mask)
117
+ return self.forward_internal(x, mask)
118
+
119
+ def forward_internal(
120
+ self, x: Tensor, layer_skip_mask: Optional[Tensor] = None
121
+ ) -> Tensor:
122
+ """
123
+ x layout: (N, C, H, W), i.e. (batch_size, num_channels, num_frames, num_freqs)
124
+
125
+ The returned value has the same shape as x.
126
+ """
127
+ bypass = x
128
+ x = self.depthwise_conv(x)
129
+ x = self.pointwise_conv1(x)
130
+ x = self.hidden_balancer(x)
131
+ x = self.activation(x)
132
+ x = self.pointwise_conv2(x)
133
+
134
+ if layer_skip_mask is not None:
135
+ x = x * layer_skip_mask
136
+
137
+ x = bypass + x
138
+ x = self.out_balancer(x)
139
+
140
+ if x.requires_grad:
141
+ x = x.transpose(1, 3) # (N, W, H, C); need channel dim to be last
142
+ x = self.out_whiten(x)
143
+ x = x.transpose(1, 3) # (N, C, H, W)
144
+
145
+ return x
146
+
147
+ def streaming_forward(
148
+ self,
149
+ x: Tensor,
150
+ cached_left_pad: Tensor,
151
+ ) -> Tuple[Tensor, Tensor]:
152
+ """
153
+ Args:
154
+ x layout: (N, C, H, W), i.e. (batch_size, num_channels, num_frames, num_freqs)
155
+ cached_left_pad: (batch_size, num_channels, left_pad, num_freqs)
156
+
157
+ Returns:
158
+ - The returned value has the same shape as x.
159
+ - Updated cached_left_pad.
160
+ """
161
+ padding = self.padding
162
+
163
+ # The length without right padding for depth-wise conv
164
+ T = x.size(2) - padding[0]
165
+
166
+ bypass = x[:, :, :T, :]
167
+
168
+ # Pad left side
169
+ assert cached_left_pad.size(2) == padding[0], (
170
+ cached_left_pad.size(2),
171
+ padding[0],
172
+ )
173
+ x = torch.cat([cached_left_pad, x], dim=2)
174
+ # Update cached left padding
175
+ cached_left_pad = x[:, :, T : padding[0] + T, :]
176
+
177
+ # depthwise_conv
178
+ x = torch.nn.functional.conv2d(
179
+ x,
180
+ weight=self.depthwise_conv.weight,
181
+ bias=self.depthwise_conv.bias,
182
+ padding=(0, padding[1]),
183
+ groups=self.depthwise_conv.groups,
184
+ )
185
+ x = self.pointwise_conv1(x)
186
+ x = self.hidden_balancer(x)
187
+ x = self.activation(x)
188
+ x = self.pointwise_conv2(x)
189
+
190
+ x = bypass + x
191
+ return x, cached_left_pad
192
+
193
+
194
+ class Conv2dSubsampling(nn.Module):
195
+ """Convolutional 2D subsampling (to 1/2 length).
196
+
197
+ Convert an input of shape (N, T, idim) to an output
198
+ with shape (N, T', odim), where
199
+ T' = (T-3)//2 - 2 == (T-7)//2
200
+
201
+ It is based on
202
+ https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py # noqa
203
+ """
204
+
205
+ def __init__(
206
+ self,
207
+ in_channels: int,
208
+ out_channels: int,
209
+ layer1_channels: int = 8,
210
+ layer2_channels: int = 32,
211
+ layer3_channels: int = 128,
212
+ dropout: FloatLike = 0.1,
213
+ ) -> None:
214
+ """
215
+ Args:
216
+ in_channels:
217
+ Number of channels in. The input shape is (N, T, in_channels).
218
+ Caution: It requires: T >=7, in_channels >=7
219
+ out_channels
220
+ Output dim. The output shape is (N, (T-3)//2, out_channels)
221
+ layer1_channels:
222
+ Number of channels in layer1
223
+ layer1_channels:
224
+ Number of channels in layer2
225
+ bottleneck:
226
+ bottleneck dimension for 1d squeeze-excite
227
+ """
228
+ assert in_channels >= 7
229
+ super().__init__()
230
+
231
+ # The ScaleGrad module is there to prevent the gradients
232
+ # w.r.t. the weight or bias of the first Conv2d module in self.conv from
233
+ # exceeding the range of fp16 when using automatic mixed precision (amp)
234
+ # training. (The second one is necessary to stop its bias from getting
235
+ # a too-large gradient).
236
+
237
+ self.conv = nn.Sequential(
238
+ nn.Conv2d(
239
+ in_channels=1,
240
+ out_channels=layer1_channels,
241
+ kernel_size=3,
242
+ padding=(0, 1), # (time, freq)
243
+ ),
244
+ ScaleGrad(0.2),
245
+ Balancer(layer1_channels, channel_dim=1, max_abs=1.0),
246
+ SwooshR(),
247
+ nn.Conv2d(
248
+ in_channels=layer1_channels,
249
+ out_channels=layer2_channels,
250
+ kernel_size=3,
251
+ stride=2,
252
+ padding=0,
253
+ ),
254
+ Balancer(layer2_channels, channel_dim=1, max_abs=4.0),
255
+ SwooshR(),
256
+ nn.Conv2d(
257
+ in_channels=layer2_channels,
258
+ out_channels=layer3_channels,
259
+ kernel_size=3,
260
+ stride=(1, 2), # (time, freq)
261
+ ),
262
+ Balancer(layer3_channels, channel_dim=1, max_abs=4.0),
263
+ SwooshR(),
264
+ )
265
+
266
+ # just one convnext layer
267
+ self.convnext = ConvNeXt(layer3_channels, kernel_size=(7, 7))
268
+
269
+ # (in_channels-3)//4
270
+ self.out_width = (((in_channels - 1) // 2) - 1) // 2
271
+ self.layer3_channels = layer3_channels
272
+
273
+ self.out = nn.Linear(self.out_width * layer3_channels, out_channels)
274
+ # use a larger than normal grad_scale on this whitening module; there is
275
+ # only one such module, so there is not a concern about adding together
276
+ # many copies of this extra gradient term.
277
+ self.out_whiten = Whiten(
278
+ num_groups=1,
279
+ whitening_limit=ScheduledFloat((0.0, 4.0), (20000.0, 8.0), default=4.0),
280
+ prob=(0.025, 0.25),
281
+ grad_scale=0.02,
282
+ )
283
+
284
+ # max_log_eps=0.0 is to prevent both eps and the output of self.out from
285
+ # getting large, there is an unnecessary degree of freedom.
286
+ self.out_norm = BiasNorm(out_channels)
287
+ self.dropout = Dropout3(dropout, shared_dim=1)
288
+
289
+ def forward(
290
+ self, x: torch.Tensor, x_lens: torch.Tensor
291
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
292
+ """Subsample x.
293
+
294
+ Args:
295
+ x:
296
+ Its shape is (N, T, idim).
297
+ x_lens:
298
+ A tensor of shape (batch_size,) containing the number of frames in
299
+
300
+ Returns:
301
+ - a tensor of shape (N, (T-7)//2, odim)
302
+ - output lengths, of shape (batch_size,)
303
+ """
304
+ # On entry, x is (N, T, idim)
305
+ x = x.unsqueeze(1) # (N, T, idim) -> (N, 1, T, idim) i.e., (N, C, H, W)
306
+ # scaling x by 0.1 allows us to use a larger grad-scale in fp16 "amp" (automatic mixed precision)
307
+ # training, since the weights in the first convolution are otherwise the limiting factor for getting infinite
308
+ # gradients.
309
+ x = self.conv(x)
310
+ x = self.convnext(x)
311
+
312
+ # Now x is of shape (N, odim, (T-7)//2, (idim-3)//4)
313
+ b, c, t, f = x.size()
314
+
315
+ x = x.transpose(1, 2).reshape(b, t, c * f)
316
+ # now x: (N, (T-7)//2, out_width * layer3_channels))
317
+
318
+ x = self.out(x)
319
+ # Now x is of shape (N, (T-7)//2, odim)
320
+ x = self.out_whiten(x)
321
+ x = self.out_norm(x)
322
+ x = self.dropout(x)
323
+
324
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
325
+ x_lens = (x_lens - 7) // 2
326
+ else:
327
+ with warnings.catch_warnings():
328
+ warnings.simplefilter("ignore")
329
+ x_lens = (x_lens - 7) // 2
330
+ assert x.size(1) == x_lens.max().item(), (x.size(1), x_lens.max())
331
+
332
+ return x, x_lens
333
+
334
+ def streaming_forward(
335
+ self,
336
+ x: torch.Tensor,
337
+ x_lens: torch.Tensor,
338
+ cached_left_pad: Tensor,
339
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
340
+ """Subsample x.
341
+
342
+ Args:
343
+ x:
344
+ Its shape is (N, T, idim).
345
+ x_lens:
346
+ A tensor of shape (batch_size,) containing the number of frames in
347
+
348
+ Returns:
349
+ - a tensor of shape (N, (T-7)//2, odim)
350
+ - output lengths, of shape (batch_size,)
351
+ - updated cache
352
+ """
353
+ # On entry, x is (N, T, idim)
354
+ x = x.unsqueeze(1) # (N, T, idim) -> (N, 1, T, idim) i.e., (N, C, H, W)
355
+
356
+ # T' = (T-7)//2
357
+ x = self.conv(x)
358
+
359
+ # T' = (T-7)//2-3
360
+ x, cached_left_pad = self.convnext.streaming_forward(
361
+ x, cached_left_pad=cached_left_pad
362
+ )
363
+
364
+ # Now x is of shape (N, odim, T', ((idim-1)//2 - 1)//2)
365
+ b, c, t, f = x.size()
366
+
367
+ x = x.transpose(1, 2).reshape(b, t, c * f)
368
+ # now x: (N, T', out_width * layer3_channels))
369
+
370
+ x = self.out(x)
371
+ # Now x is of shape (N, T', odim)
372
+ x = self.out_norm(x)
373
+
374
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
375
+ assert self.convnext.padding[0] == 3
376
+ # The ConvNeXt module needs 3 frames of right padding after subsampling
377
+ x_lens = (x_lens - 7) // 2 - 3
378
+ else:
379
+ with warnings.catch_warnings():
380
+ warnings.simplefilter("ignore")
381
+ # The ConvNeXt module needs 3 frames of right padding after subsampling
382
+ assert self.convnext.padding[0] == 3
383
+ x_lens = (x_lens - 7) // 2 - 3
384
+
385
+ assert x.size(1) == x_lens.max().item(), (x.shape, x_lens.max())
386
+
387
+ return x, x_lens, cached_left_pad
388
+
389
+ @torch.jit.export
390
+ def get_init_states(
391
+ self,
392
+ batch_size: int = 1,
393
+ device: torch.device = torch.device("cpu"),
394
+ ) -> Tensor:
395
+ """Get initial states for Conv2dSubsampling module.
396
+ It is the cached left padding for ConvNeXt module,
397
+ of shape (batch_size, num_channels, left_pad, num_freqs)
398
+ """
399
+ left_pad = self.convnext.padding[0]
400
+ freq = self.out_width
401
+ channels = self.layer3_channels
402
+ cached_embed_left_pad = torch.zeros(batch_size, channels, left_pad, freq).to(
403
+ device
404
+ )
405
+
406
+ return cached_embed_left_pad
wakeup_model/zipformer/zipformer.py ADDED
@@ -0,0 +1,2469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2022-2023 Xiaomi Corp. (authors: Daniel Povey,
3
+ # Zengwei Yao)
4
+ #
5
+ # See ../../../../LICENSE for clarification regarding multiple authors
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import copy
20
+ import logging
21
+ import math
22
+ import random
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ from encoder_interface import EncoderInterface
28
+ from scaling import (
29
+ Identity, # more friendly to backward hooks than nn.Identity(), for diagnostic reasons.
30
+ )
31
+ from scaling import (
32
+ ScaledLinear, # not as in other dirs.. just scales down initial parameter values.
33
+ )
34
+ from scaling import (
35
+ ActivationDropoutAndLinear,
36
+ Balancer,
37
+ BiasNorm,
38
+ ChunkCausalDepthwiseConv1d,
39
+ Dropout2,
40
+ FloatLike,
41
+ ScheduledFloat,
42
+ Whiten,
43
+ convert_num_channels,
44
+ limit_param_value,
45
+ penalize_abs_values_gt,
46
+ softmax,
47
+ )
48
+ from torch import Tensor, nn
49
+
50
+ from icefall.utils import torch_autocast
51
+
52
+
53
+ class Zipformer2(EncoderInterface):
54
+ """
55
+ Args:
56
+
57
+ Note: all "int or Tuple[int]" arguments below will be treated as lists of the same length
58
+ as downsampling_factor if they are single ints or one-element tuples. The length of
59
+ downsampling_factor defines the number of stacks.
60
+
61
+ output_downsampling_factor (int): how much to downsample at the output. Note:
62
+ we also downsample by a factor of 2 in the Conv2dSubsampling encoder.
63
+ You should probably leave this at 2.
64
+ downsampling_factor (Tuple[int]): downsampling factor for each encoder stack.
65
+ Note: this is in addition to the downsampling factor of 2 that is applied in
66
+ the frontend (self.encoder_embed).
67
+ encoder_dim (Tuple[int]): embedding dimension of each of the encoder stacks, one per
68
+ encoder stack.
69
+ num_encoder_layers (int or Tuple[int])): number of encoder layers for each stack
70
+ encoder_unmasked_dim (int or Tuple[int]): unmasked dimension in each of
71
+ the encoder stacks for purposes of per-frame dropout (recommend 256 for
72
+ now).
73
+ query_head_dim (int or Tuple[int]): dimension of query and key per attention
74
+ head: per stack, if a tuple..
75
+ pos_head_dim (int or Tuple[int]): dimension of positional-encoding projection per
76
+ attention head
77
+ value_head_dim (int or Tuple[int]): dimension of value in each attention head
78
+ num_heads: (int or Tuple[int]): number of heads in the self-attention mechanism.
79
+ Must be at least 4.
80
+ feedforward_dim (int or Tuple[int]): hidden dimension in feedforward modules
81
+ cnn_module_kernel (int or Tuple[int])): Kernel size of convolution module
82
+
83
+ pos_dim (int): the dimension of each positional-encoding vector prior to projection,
84
+ e.g. 128.
85
+
86
+ dropout (float): dropout rate
87
+ warmup_batches (float): number of batches to warm up over; this controls
88
+ dropout of encoder layers.
89
+ causal (bool): if True, support chunkwise causal convolution. This should
90
+ not hurt WER as no modeling power is lost, but the convolution modules will be
91
+ slightly slower and use more memory. Enables use of the chunk_size and
92
+ left_context_chunks options in forward(), which simulates streaming
93
+ decoding.
94
+ chunk_size: (list of int): only set this to other than [-1] if causal;
95
+ the chunk size will be randomly chosen from this list. -1 means no chunking.
96
+ left_context_frames: (list of int): determines the number of left-
97
+ context chunks for causal training; will be rounded to a number of
98
+ chunks. Must not be less than cnn_module_kernel (after factoring in
99
+ rounding and downsampling); an error will be thrown if this is violated.
100
+ """
101
+
102
+ def __init__(
103
+ self,
104
+ output_downsampling_factor: int = 2,
105
+ downsampling_factor: Tuple[int] = (2, 4),
106
+ encoder_dim: Union[int, Tuple[int]] = 384,
107
+ num_encoder_layers: Union[int, Tuple[int]] = 4,
108
+ encoder_unmasked_dim: Union[int, Tuple[int]] = 256,
109
+ query_head_dim: Union[int, Tuple[int]] = 24,
110
+ pos_head_dim: Union[int, Tuple[int]] = 4,
111
+ value_head_dim: Union[int, Tuple[int]] = 12,
112
+ num_heads: Union[int, Tuple[int]] = 8,
113
+ feedforward_dim: Union[int, Tuple[int]] = 1536,
114
+ cnn_module_kernel: Union[int, Tuple[int]] = 31,
115
+ pos_dim: int = 192,
116
+ dropout: FloatLike = None, # see code below for default
117
+ warmup_batches: float = 4000.0,
118
+ causal: bool = False,
119
+ chunk_size: Tuple[int] = [-1],
120
+ left_context_frames: Tuple[int] = [-1],
121
+ ) -> None:
122
+ super(Zipformer2, self).__init__()
123
+
124
+ if dropout is None:
125
+ dropout = ScheduledFloat((0.0, 0.3), (20000.0, 0.1))
126
+
127
+ def _to_tuple(x):
128
+ """Converts a single int or a 1-tuple of an int to a tuple with the same length
129
+ as downsampling_factor"""
130
+ if isinstance(x, int):
131
+ x = (x,)
132
+ if len(x) == 1:
133
+ x = x * len(downsampling_factor)
134
+ else:
135
+ assert len(x) == len(downsampling_factor) and isinstance(x[0], int)
136
+ return x
137
+
138
+ self.output_downsampling_factor = output_downsampling_factor # int
139
+ self.downsampling_factor = downsampling_factor # tuple
140
+ self.encoder_dim = encoder_dim = _to_tuple(encoder_dim) # tuple
141
+ self.encoder_unmasked_dim = encoder_unmasked_dim = _to_tuple(
142
+ encoder_unmasked_dim
143
+ ) # tuple
144
+ num_encoder_layers = _to_tuple(num_encoder_layers)
145
+ self.num_encoder_layers = num_encoder_layers
146
+ self.query_head_dim = query_head_dim = _to_tuple(query_head_dim)
147
+ self.value_head_dim = value_head_dim = _to_tuple(value_head_dim)
148
+ pos_head_dim = _to_tuple(pos_head_dim)
149
+ self.num_heads = num_heads = _to_tuple(num_heads)
150
+ feedforward_dim = _to_tuple(feedforward_dim)
151
+ self.cnn_module_kernel = cnn_module_kernel = _to_tuple(cnn_module_kernel)
152
+
153
+ self.causal = causal
154
+ self.chunk_size = chunk_size
155
+ self.left_context_frames = left_context_frames
156
+
157
+ for u, d in zip(encoder_unmasked_dim, encoder_dim):
158
+ assert u <= d
159
+
160
+ # each one will be Zipformer2Encoder or DownsampledZipformer2Encoder
161
+ encoders = []
162
+
163
+ num_encoders = len(downsampling_factor)
164
+ for i in range(num_encoders):
165
+ encoder_layer = Zipformer2EncoderLayer(
166
+ embed_dim=encoder_dim[i],
167
+ pos_dim=pos_dim,
168
+ num_heads=num_heads[i],
169
+ query_head_dim=query_head_dim[i],
170
+ pos_head_dim=pos_head_dim[i],
171
+ value_head_dim=value_head_dim[i],
172
+ feedforward_dim=feedforward_dim[i],
173
+ dropout=dropout,
174
+ cnn_module_kernel=cnn_module_kernel[i],
175
+ causal=causal,
176
+ )
177
+
178
+ # For the segment of the warmup period, we let the Conv2dSubsampling
179
+ # layer learn something. Then we start to warm up the other encoders.
180
+ encoder = Zipformer2Encoder(
181
+ encoder_layer,
182
+ num_encoder_layers[i],
183
+ pos_dim=pos_dim,
184
+ dropout=dropout,
185
+ warmup_begin=warmup_batches * (i + 1) / (num_encoders + 1),
186
+ warmup_end=warmup_batches * (i + 2) / (num_encoders + 1),
187
+ final_layerdrop_rate=0.035 * (downsampling_factor[i] ** 0.5),
188
+ )
189
+
190
+ if downsampling_factor[i] != 1:
191
+ encoder = DownsampledZipformer2Encoder(
192
+ encoder,
193
+ dim=encoder_dim[i],
194
+ downsample=downsampling_factor[i],
195
+ dropout=dropout,
196
+ causal=causal,
197
+ )
198
+
199
+ encoders.append(encoder)
200
+
201
+ self.encoders = nn.ModuleList(encoders)
202
+
203
+ self.downsample_output = SimpleDownsample(
204
+ max(encoder_dim),
205
+ downsample=output_downsampling_factor,
206
+ dropout=dropout,
207
+ causal=causal,
208
+ )
209
+
210
+ def get_feature_masks(self, x: Tensor) -> Union[List[float], List[Tensor]]:
211
+ """
212
+ In eval mode, returns [1.0] * num_encoders; in training mode, returns a number of
213
+ randomized feature masks, one per encoder.
214
+ On e.g. 15% of frames, these masks will zero out all encoder dims larger than
215
+ some supplied number, e.g. >256, so in effect on those frames we are using
216
+ a smaller encoder dim.
217
+
218
+ We generate the random masks at this level because we want the 2 masks to 'agree'
219
+ all the way up the encoder stack. This will mean that the 1st mask will have
220
+ mask values repeated self.zipformer_subsampling_factor times.
221
+
222
+ Args:
223
+ x: the embeddings (needed for the shape and dtype and device), of shape
224
+ (1, batch_size, encoder_dims0)
225
+ """
226
+ num_encoders = len(self.encoder_dim)
227
+ if not self.training:
228
+ return [1.0] * num_encoders
229
+
230
+ num_frames0, batch_size, _encoder_dims0 = x.shape
231
+
232
+ assert self.encoder_dim[0] == _encoder_dims0, (
233
+ self.encoder_dim[0],
234
+ _encoder_dims0,
235
+ )
236
+
237
+ feature_mask_dropout_prob = 0.125
238
+
239
+ # mask1 shape: (1, batch_size, 1)
240
+ mask1 = (
241
+ torch.rand(1, batch_size, 1, device=x.device) > feature_mask_dropout_prob
242
+ ).to(x.dtype)
243
+
244
+ # mask2 has additional sequences masked, about twice the number.
245
+ mask2 = torch.logical_and(
246
+ mask1,
247
+ (
248
+ torch.rand(1, batch_size, 1, device=x.device)
249
+ > feature_mask_dropout_prob
250
+ ).to(x.dtype),
251
+ )
252
+
253
+ # dim: (1, batch_size, 2)
254
+ mask = torch.cat((mask1, mask2), dim=-1)
255
+
256
+ feature_masks = []
257
+ for i in range(num_encoders):
258
+ channels = self.encoder_dim[i]
259
+ feature_mask = torch.ones(
260
+ 1, batch_size, channels, dtype=x.dtype, device=x.device
261
+ )
262
+ u1 = self.encoder_unmasked_dim[i]
263
+ u2 = u1 + (channels - u1) // 2
264
+
265
+ feature_mask[:, :, u1:u2] *= mask[..., 0:1]
266
+ feature_mask[:, :, u2:] *= mask[..., 1:2]
267
+
268
+ feature_masks.append(feature_mask)
269
+
270
+ return feature_masks
271
+
272
+ def get_chunk_info(self) -> Tuple[int, int]:
273
+ """
274
+ Returns chunk_size and left_context_chunks.
275
+ """
276
+ if not self.causal:
277
+ return -1, -1
278
+
279
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
280
+ assert len(self.chunk_size) == 1, self.chunk_size
281
+ chunk_size = self.chunk_size[0]
282
+ else:
283
+ chunk_size = random.choice(self.chunk_size)
284
+
285
+ if chunk_size == -1:
286
+ left_context_chunks = -1
287
+ else:
288
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
289
+ assert len(self.left_context_frames) == 1, self.left_context_frames
290
+ left_context_frames = self.left_context_frames[0]
291
+ else:
292
+ left_context_frames = random.choice(self.left_context_frames)
293
+ # Note: in Python, -1 // n == -1 for n > 0
294
+ left_context_chunks = left_context_frames // chunk_size
295
+ if left_context_chunks == 0:
296
+ left_context_chunks = 1
297
+
298
+ return chunk_size, left_context_chunks
299
+
300
+ def forward(
301
+ self,
302
+ x: Tensor,
303
+ x_lens: Tensor,
304
+ src_key_padding_mask: Optional[Tensor] = None,
305
+ ) -> Tuple[Tensor, Tensor]:
306
+ """
307
+ Args:
308
+ x:
309
+ The input tensor. Its shape is (seq_len, batch_size, feature_dim).
310
+ x_lens:
311
+ A tensor of shape (batch_size,) containing the number of frames in
312
+ `x` before padding.
313
+ src_key_padding_mask:
314
+ The mask for padding, of shape (batch_size, seq_len); True means
315
+ masked position. May be None.
316
+ Returns:
317
+ Return a tuple containing 2 tensors:
318
+ - embeddings: its shape is (output_seq_len, batch_size, max(encoder_dim))
319
+ - lengths, a tensor of shape (batch_size,) containing the number
320
+ of frames in `embeddings` before padding.
321
+ """
322
+ outputs = []
323
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
324
+ feature_masks = [1.0] * len(self.encoder_dim)
325
+ else:
326
+ feature_masks = self.get_feature_masks(x)
327
+
328
+ chunk_size, left_context_chunks = self.get_chunk_info()
329
+
330
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
331
+ # Not support exporting a model for simulating streaming decoding
332
+ attn_mask = None
333
+ else:
334
+ attn_mask = self._get_attn_mask(x, chunk_size, left_context_chunks)
335
+
336
+ for i, module in enumerate(self.encoders):
337
+ ds = self.downsampling_factor[i]
338
+ x = convert_num_channels(x, self.encoder_dim[i])
339
+
340
+ x = module(
341
+ x,
342
+ chunk_size=chunk_size,
343
+ feature_mask=feature_masks[i],
344
+ src_key_padding_mask=(
345
+ None
346
+ if src_key_padding_mask is None
347
+ else src_key_padding_mask[..., ::ds]
348
+ ),
349
+ attn_mask=attn_mask,
350
+ )
351
+ outputs.append(x)
352
+
353
+ # if the last output has the largest dimension, x will be unchanged,
354
+ # it will be the same as outputs[-1]. Otherwise it will be concatenated
355
+ # from different pieces of 'outputs', taking each dimension from the
356
+ # most recent output that has it present.
357
+ x = self._get_full_dim_output(outputs)
358
+ x = self.downsample_output(x)
359
+ # class Downsample has this rounding behavior..
360
+ assert self.output_downsampling_factor == 2, self.output_downsampling_factor
361
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
362
+ lengths = (x_lens + 1) // 2
363
+ else:
364
+ with warnings.catch_warnings():
365
+ warnings.simplefilter("ignore")
366
+ lengths = (x_lens + 1) // 2
367
+
368
+ return x, lengths
369
+
370
+ def _get_attn_mask(
371
+ self, x: Tensor, chunk_size: int, left_context_chunks: int
372
+ ) -> Optional[Tensor]:
373
+ """
374
+ Return None if chunk_size == -1, else return attention mask of shape
375
+ (seq_len, seq_len), interpreted as (tgt_seq_len, src_seq_len). True
376
+ means a masked position.
377
+ Args:
378
+ x: embeddings after self.encoder_embed(), of shape (seq_len, batch_size, embed_dim).
379
+ chunk_size: chunk size, must divide
380
+ """
381
+ if chunk_size <= 0:
382
+ return None
383
+ assert all(chunk_size % d == 0 for d in self.downsampling_factor)
384
+ if left_context_chunks >= 0:
385
+ num_encoders = len(self.encoder_dim)
386
+ assert all(
387
+ chunk_size * left_context_chunks
388
+ >= (self.cnn_module_kernel[i] // 2) * self.downsampling_factor[i]
389
+ for i in range(num_encoders)
390
+ )
391
+ else:
392
+ left_context_chunks = 1000000
393
+
394
+ seq_len = x.shape[0]
395
+
396
+ # t is frame index, shape (seq_len,)
397
+ t = torch.arange(seq_len, dtype=torch.int32, device=x.device)
398
+ # c is chunk index for each frame, shape (seq_len,)
399
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
400
+ c = t // chunk_size
401
+ else:
402
+ with warnings.catch_warnings():
403
+ warnings.simplefilter("ignore")
404
+ c = t // chunk_size
405
+ src_c = c
406
+ tgt_c = c.unsqueeze(-1)
407
+
408
+ attn_mask = torch.logical_or(src_c > tgt_c, src_c < tgt_c - left_context_chunks)
409
+ if __name__ == "__main__":
410
+ logging.info(f"attn_mask = {attn_mask}")
411
+ return attn_mask
412
+
413
+ def _get_full_dim_output(self, outputs: List[Tensor]):
414
+ num_encoders = len(self.encoder_dim)
415
+ assert len(outputs) == num_encoders
416
+ output_dim = max(self.encoder_dim)
417
+ output_pieces = [outputs[-1]]
418
+ cur_dim = self.encoder_dim[-1]
419
+ for i in range(num_encoders - 2, -1, -1):
420
+ d = self.encoder_dim[i]
421
+ if d > cur_dim:
422
+ this_output = outputs[i]
423
+ output_pieces.append(this_output[..., cur_dim:d])
424
+ cur_dim = d
425
+ assert cur_dim == output_dim
426
+ return torch.cat(output_pieces, dim=-1)
427
+
428
+ def streaming_forward(
429
+ self,
430
+ x: Tensor,
431
+ x_lens: Tensor,
432
+ states: List[Tensor],
433
+ src_key_padding_mask: Tensor,
434
+ ) -> Tuple[Tensor, Tensor, List[Tensor]]:
435
+ """
436
+ Args:
437
+ x:
438
+ The input tensor. Its shape is (seq_len, batch_size, feature_dim).
439
+ x_lens:
440
+ A tensor of shape (batch_size,) containing the number of frames in
441
+ `x` before padding.
442
+ states: list of cached tensors of all encoder layers. For layer-i,
443
+ states[i*6:(i+1)*6] is (cached_key, cached_nonlin_attn, cached_val1, cached_val2,
444
+ cached_conv1, cached_conv2).
445
+ src_key_padding_mask:
446
+ The mask for padding, of shape (batch_size, seq_len); True means
447
+ masked position. May be None.
448
+ Returns:
449
+ Return a tuple containing 2 tensors:
450
+ - embeddings: its shape is (output_seq_len, batch_size, max(encoder_dim))
451
+ - lengths, a tensor of shape (batch_size,) containing the number
452
+ of frames in `embeddings` before padding.
453
+ - updated states
454
+ """
455
+ outputs = []
456
+ new_states = []
457
+ layer_offset = 0
458
+
459
+ for i, module in enumerate(self.encoders):
460
+ num_layers = module.num_layers
461
+ ds = self.downsampling_factor[i]
462
+ x = convert_num_channels(x, self.encoder_dim[i])
463
+
464
+ x, new_layer_states = module.streaming_forward(
465
+ x,
466
+ states=states[layer_offset * 6 : (layer_offset + num_layers) * 6],
467
+ left_context_len=self.left_context_frames[0] // ds,
468
+ src_key_padding_mask=src_key_padding_mask[..., ::ds],
469
+ )
470
+ layer_offset += num_layers
471
+ outputs.append(x)
472
+ new_states += new_layer_states
473
+
474
+ # if the last output has the largest dimension, x will be unchanged,
475
+ # it will be the same as outputs[-1]. Otherwise it will be concatenated
476
+ # from different pieces of 'outputs', taking each dimension from the
477
+ # most recent output that has it present.
478
+ x = self._get_full_dim_output(outputs)
479
+ x = self.downsample_output(x)
480
+ # class Downsample has this rounding behavior..
481
+ assert self.output_downsampling_factor == 2
482
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
483
+ lengths = (x_lens + 1) // 2
484
+ else:
485
+ with warnings.catch_warnings():
486
+ warnings.simplefilter("ignore")
487
+ lengths = (x_lens + 1) // 2
488
+
489
+ return x, lengths, new_states
490
+
491
+ @torch.jit.export
492
+ def get_init_states(
493
+ self,
494
+ batch_size: int = 1,
495
+ device: torch.device = torch.device("cpu"),
496
+ ) -> List[Tensor]:
497
+ """Get initial states.
498
+
499
+ A list of cached tensors of all encoder layers. For layer-i, states[i*6:(i+1)*6]
500
+ is (cached_key, cached_nonlin_attn, cached_val1, cached_val2, cached_conv1, cached_conv2).
501
+ """
502
+ states = []
503
+ for i, module in enumerate(self.encoders):
504
+ num_layers = module.num_layers
505
+ embed_dim = self.encoder_dim[i]
506
+ ds = self.downsampling_factor[i]
507
+ num_heads = self.num_heads[i]
508
+ key_dim = self.query_head_dim[i] * num_heads
509
+ value_dim = self.value_head_dim[i] * num_heads
510
+ downsample_left = self.left_context_frames[0] // ds
511
+ nonlin_attn_head_dim = 3 * embed_dim // 4
512
+ conv_left_pad = self.cnn_module_kernel[i] // 2
513
+ for layer in range(num_layers):
514
+ cached_key = torch.zeros(downsample_left, batch_size, key_dim).to(
515
+ device
516
+ )
517
+ cached_nonlin_attn = torch.zeros(
518
+ 1, batch_size, downsample_left, nonlin_attn_head_dim
519
+ ).to(device)
520
+ cached_val1 = torch.zeros(downsample_left, batch_size, value_dim).to(
521
+ device
522
+ )
523
+ cached_val2 = torch.zeros(downsample_left, batch_size, value_dim).to(
524
+ device
525
+ )
526
+ cached_conv1 = torch.zeros(batch_size, embed_dim, conv_left_pad).to(
527
+ device
528
+ )
529
+ cached_conv2 = torch.zeros(batch_size, embed_dim, conv_left_pad).to(
530
+ device
531
+ )
532
+ states += [
533
+ cached_key,
534
+ cached_nonlin_attn,
535
+ cached_val1,
536
+ cached_val2,
537
+ cached_conv1,
538
+ cached_conv2,
539
+ ]
540
+
541
+ return states
542
+
543
+
544
+ def _whitening_schedule(x: float, ratio: float = 2.0) -> ScheduledFloat:
545
+ return ScheduledFloat((0.0, x), (20000.0, ratio * x), default=x)
546
+
547
+
548
+ def _balancer_schedule(min_prob: float):
549
+ return ScheduledFloat((0.0, 0.4), (8000.0, min_prob))
550
+
551
+
552
+ class Zipformer2EncoderLayer(nn.Module):
553
+ """
554
+ Args:
555
+ embed_dim: the number of expected features in the input (required).
556
+ nhead: the number of heads in the multiheadattention models (required).
557
+ feedforward_dim: the dimension of the feedforward network model (required).
558
+ dropout: the dropout value (default=0.1).
559
+ cnn_module_kernel (int): Kernel size of convolution module (default=31).
560
+
561
+ Examples::
562
+ >>> encoder_layer = Zipformer2EncoderLayer(embed_dim=512, nhead=8)
563
+ >>> src = torch.rand(10, 32, 512)
564
+ >>> pos_emb = torch.rand(32, 19, 512)
565
+ >>> out = encoder_layer(src, pos_emb)
566
+ """
567
+
568
+ def __init__(
569
+ self,
570
+ embed_dim: int,
571
+ pos_dim: int,
572
+ num_heads: int,
573
+ query_head_dim: int,
574
+ pos_head_dim: int,
575
+ value_head_dim: int,
576
+ feedforward_dim: int,
577
+ dropout: FloatLike = 0.1,
578
+ cnn_module_kernel: int = 31,
579
+ causal: bool = False,
580
+ attention_skip_rate: FloatLike = ScheduledFloat(
581
+ (0.0, 0.2), (4000.0, 0.05), (16000, 0.0), default=0
582
+ ),
583
+ conv_skip_rate: FloatLike = ScheduledFloat(
584
+ (0.0, 0.2), (4000.0, 0.05), (16000, 0.0), default=0
585
+ ),
586
+ const_attention_rate: FloatLike = ScheduledFloat(
587
+ (0.0, 0.25), (4000.0, 0.025), default=0
588
+ ),
589
+ ff2_skip_rate: FloatLike = ScheduledFloat(
590
+ (0.0, 0.1), (4000.0, 0.01), (50000.0, 0.0)
591
+ ),
592
+ ff3_skip_rate: FloatLike = ScheduledFloat(
593
+ (0.0, 0.1), (4000.0, 0.01), (50000.0, 0.0)
594
+ ),
595
+ bypass_skip_rate: FloatLike = ScheduledFloat(
596
+ (0.0, 0.5), (4000.0, 0.02), default=0
597
+ ),
598
+ ) -> None:
599
+ super(Zipformer2EncoderLayer, self).__init__()
600
+ self.embed_dim = embed_dim
601
+
602
+ # self.bypass implements layer skipping as well as bypass; see its default values.
603
+ self.bypass = BypassModule(
604
+ embed_dim, skip_rate=bypass_skip_rate, straight_through_rate=0
605
+ )
606
+ # bypass_mid is bypass used in the middle of the layer.
607
+ self.bypass_mid = BypassModule(embed_dim, straight_through_rate=0)
608
+
609
+ # skip probability for dynamic modules (meaning: anything but feedforward).
610
+ self.attention_skip_rate = copy.deepcopy(attention_skip_rate)
611
+ # an additional skip probability that applies to ConvModule to stop it from
612
+ # contributing too much early on.
613
+ self.conv_skip_rate = copy.deepcopy(conv_skip_rate)
614
+
615
+ # ff2_skip_rate is to prevent the ff2 module from having output that's too big
616
+ # compared to its residual.
617
+ self.ff2_skip_rate = copy.deepcopy(ff2_skip_rate)
618
+ self.ff3_skip_rate = copy.deepcopy(ff3_skip_rate)
619
+
620
+ self.const_attention_rate = copy.deepcopy(const_attention_rate)
621
+
622
+ self.self_attn_weights = RelPositionMultiheadAttentionWeights(
623
+ embed_dim,
624
+ pos_dim=pos_dim,
625
+ num_heads=num_heads,
626
+ query_head_dim=query_head_dim,
627
+ pos_head_dim=pos_head_dim,
628
+ dropout=0.0,
629
+ )
630
+
631
+ self.self_attn1 = SelfAttention(embed_dim, num_heads, value_head_dim)
632
+
633
+ self.self_attn2 = SelfAttention(embed_dim, num_heads, value_head_dim)
634
+
635
+ self.feed_forward1 = FeedforwardModule(
636
+ embed_dim, (feedforward_dim * 3) // 4, dropout
637
+ )
638
+
639
+ self.feed_forward2 = FeedforwardModule(embed_dim, feedforward_dim, dropout)
640
+
641
+ self.feed_forward3 = FeedforwardModule(
642
+ embed_dim, (feedforward_dim * 5) // 4, dropout
643
+ )
644
+
645
+ self.nonlin_attention = NonlinAttention(
646
+ embed_dim, hidden_channels=3 * embed_dim // 4
647
+ )
648
+
649
+ self.conv_module1 = ConvolutionModule(
650
+ embed_dim, cnn_module_kernel, causal=causal
651
+ )
652
+
653
+ self.conv_module2 = ConvolutionModule(
654
+ embed_dim, cnn_module_kernel, causal=causal
655
+ )
656
+
657
+ # TODO: remove it
658
+ self.bypass_scale = nn.Parameter(torch.full((embed_dim,), 0.5))
659
+
660
+ self.norm = BiasNorm(embed_dim)
661
+
662
+ self.balancer1 = Balancer(
663
+ embed_dim,
664
+ channel_dim=-1,
665
+ min_positive=0.45,
666
+ max_positive=0.55,
667
+ min_abs=0.2,
668
+ max_abs=4.0,
669
+ )
670
+
671
+ # balancer for output of NonlinAttentionModule
672
+ self.balancer_na = Balancer(
673
+ embed_dim,
674
+ channel_dim=-1,
675
+ min_positive=0.3,
676
+ max_positive=0.7,
677
+ min_abs=ScheduledFloat((0.0, 0.004), (4000.0, 0.02)),
678
+ prob=0.05, # out of concern for memory usage
679
+ )
680
+
681
+ # balancer for output of feedforward2, prevent it from staying too
682
+ # small. give this a very small probability, even at the start of
683
+ # training, it's to fix a rare problem and it's OK to fix it slowly.
684
+ self.balancer_ff2 = Balancer(
685
+ embed_dim,
686
+ channel_dim=-1,
687
+ min_positive=0.3,
688
+ max_positive=0.7,
689
+ min_abs=ScheduledFloat((0.0, 0.0), (4000.0, 0.1), default=0.0),
690
+ max_abs=2.0,
691
+ prob=0.05,
692
+ )
693
+
694
+ self.balancer_ff3 = Balancer(
695
+ embed_dim,
696
+ channel_dim=-1,
697
+ min_positive=0.3,
698
+ max_positive=0.7,
699
+ min_abs=ScheduledFloat((0.0, 0.0), (4000.0, 0.2), default=0.0),
700
+ max_abs=4.0,
701
+ prob=0.05,
702
+ )
703
+
704
+ self.whiten = Whiten(
705
+ num_groups=1,
706
+ whitening_limit=_whitening_schedule(4.0, ratio=3.0),
707
+ prob=(0.025, 0.25),
708
+ grad_scale=0.01,
709
+ )
710
+
711
+ self.balancer2 = Balancer(
712
+ embed_dim,
713
+ channel_dim=-1,
714
+ min_positive=0.45,
715
+ max_positive=0.55,
716
+ min_abs=0.1,
717
+ max_abs=4.0,
718
+ )
719
+
720
+ def get_sequence_dropout_mask(
721
+ self, x: Tensor, dropout_rate: float
722
+ ) -> Optional[Tensor]:
723
+ if (
724
+ dropout_rate == 0.0
725
+ or not self.training
726
+ or torch.jit.is_scripting()
727
+ or torch.jit.is_tracing()
728
+ ):
729
+ return None
730
+ batch_size = x.shape[1]
731
+ mask = (torch.rand(batch_size, 1, device=x.device) > dropout_rate).to(x.dtype)
732
+ return mask
733
+
734
+ def sequence_dropout(self, x: Tensor, dropout_rate: float) -> Tensor:
735
+ """
736
+ Apply sequence-level dropout to x.
737
+ x shape: (seq_len, batch_size, embed_dim)
738
+ """
739
+ dropout_mask = self.get_sequence_dropout_mask(x, dropout_rate)
740
+ if dropout_mask is None:
741
+ return x
742
+ else:
743
+ return x * dropout_mask
744
+
745
+ def forward(
746
+ self,
747
+ src: Tensor,
748
+ pos_emb: Tensor,
749
+ chunk_size: int = -1,
750
+ attn_mask: Optional[Tensor] = None,
751
+ src_key_padding_mask: Optional[Tensor] = None,
752
+ ) -> Tensor:
753
+ """
754
+ Pass the input through the encoder layer.
755
+ Args:
756
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
757
+ pos_emb: (1, 2*seq_len-1, pos_emb_dim) or (batch_size, 2*seq_len-1, pos_emb_dim)
758
+ chunk_size: the number of frames per chunk, of >= 0; if -1, no chunking.
759
+ feature_mask: something that broadcasts with src, that we'll multiply `src`
760
+ by at every layer: if a Tensor, likely of shape (seq_len, batch_size, embedding_dim)
761
+ attn_mask: the attention mask, of shape (batch_size, seq_len, seq_len) or (seq_len, seq_len),
762
+ interpreted as (batch_size, tgt_seq_len, src_seq_len) or (tgt_seq_len, src_seq_len).
763
+ True means masked position. May be None.
764
+ src_key_padding_mask: the mask for padding, of shape (batch_size, seq_len); True means
765
+ masked position. May be None.
766
+
767
+ Returns:
768
+ A tensor which has the same shape as src
769
+ """
770
+ src_orig = src
771
+
772
+ # dropout rate for non-feedforward submodules
773
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
774
+ attention_skip_rate = 0.0
775
+ else:
776
+ attention_skip_rate = (
777
+ float(self.attention_skip_rate) if self.training else 0.0
778
+ )
779
+
780
+ # attn_weights: (num_heads, batch_size, seq_len, seq_len)
781
+ attn_weights = self.self_attn_weights(
782
+ src,
783
+ pos_emb=pos_emb,
784
+ attn_mask=attn_mask,
785
+ key_padding_mask=src_key_padding_mask,
786
+ )
787
+
788
+ src = src + self.feed_forward1(src)
789
+
790
+ self_attn_dropout_mask = self.get_sequence_dropout_mask(
791
+ src, attention_skip_rate
792
+ )
793
+
794
+ selected_attn_weights = attn_weights[0:1]
795
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
796
+ pass
797
+ elif self.training and random.random() < float(self.const_attention_rate):
798
+ # Make attention weights constant. The intention is to
799
+ # encourage these modules to do something similar to an
800
+ # averaging-over-time operation.
801
+ # only need the mask, can just use the 1st one and expand later
802
+ selected_attn_weights = selected_attn_weights[0:1]
803
+ selected_attn_weights = (selected_attn_weights > 0.0).to(
804
+ selected_attn_weights.dtype
805
+ )
806
+ selected_attn_weights = selected_attn_weights * (
807
+ 1.0 / selected_attn_weights.sum(dim=-1, keepdim=True)
808
+ )
809
+
810
+ na = self.balancer_na(self.nonlin_attention(src, selected_attn_weights))
811
+
812
+ src = src + (
813
+ na if self_attn_dropout_mask is None else na * self_attn_dropout_mask
814
+ )
815
+
816
+ self_attn = self.self_attn1(src, attn_weights)
817
+
818
+ src = src + (
819
+ self_attn
820
+ if self_attn_dropout_mask is None
821
+ else self_attn * self_attn_dropout_mask
822
+ )
823
+
824
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
825
+ conv_skip_rate = 0.0
826
+ else:
827
+ conv_skip_rate = float(self.conv_skip_rate) if self.training else 0.0
828
+ src = src + self.sequence_dropout(
829
+ self.conv_module1(
830
+ src, chunk_size=chunk_size, src_key_padding_mask=src_key_padding_mask
831
+ ),
832
+ conv_skip_rate,
833
+ )
834
+
835
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
836
+ ff2_skip_rate = 0.0
837
+ else:
838
+ ff2_skip_rate = float(self.ff2_skip_rate) if self.training else 0.0
839
+ src = src + self.sequence_dropout(
840
+ self.balancer_ff2(self.feed_forward2(src)), ff2_skip_rate
841
+ )
842
+
843
+ # bypass in the middle of the layer.
844
+ src = self.bypass_mid(src_orig, src)
845
+
846
+ self_attn = self.self_attn2(src, attn_weights)
847
+
848
+ src = src + (
849
+ self_attn
850
+ if self_attn_dropout_mask is None
851
+ else self_attn * self_attn_dropout_mask
852
+ )
853
+
854
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
855
+ conv_skip_rate = 0.0
856
+ else:
857
+ conv_skip_rate = float(self.conv_skip_rate) if self.training else 0.0
858
+ src = src + self.sequence_dropout(
859
+ self.conv_module2(
860
+ src, chunk_size=chunk_size, src_key_padding_mask=src_key_padding_mask
861
+ ),
862
+ conv_skip_rate,
863
+ )
864
+
865
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
866
+ ff3_skip_rate = 0.0
867
+ else:
868
+ ff3_skip_rate = float(self.ff3_skip_rate) if self.training else 0.0
869
+ src = src + self.sequence_dropout(
870
+ self.balancer_ff3(self.feed_forward3(src)), ff3_skip_rate
871
+ )
872
+
873
+ src = self.balancer1(src)
874
+ src = self.norm(src)
875
+
876
+ src = self.bypass(src_orig, src)
877
+
878
+ src = self.balancer2(src)
879
+ src = self.whiten(src)
880
+
881
+ return src
882
+
883
+ def streaming_forward(
884
+ self,
885
+ src: Tensor,
886
+ pos_emb: Tensor,
887
+ cached_key: Tensor,
888
+ cached_nonlin_attn: Tensor,
889
+ cached_val1: Tensor,
890
+ cached_val2: Tensor,
891
+ cached_conv1: Tensor,
892
+ cached_conv2: Tensor,
893
+ left_context_len: int,
894
+ src_key_padding_mask: Tensor,
895
+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
896
+ """Pass the input through the encoder layer in streaming forward mode.
897
+
898
+ Args:
899
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
900
+ pos_emb: (1, left_context_len+2*seq_len-1, pos_emb_dim) or
901
+ (batch_size, left_context_len+2*seq_len-1, pos_emb_dim)
902
+ cached_key: cached attention key tensor of left context,
903
+ of shape (left_context_len, batch_size, key_dim)
904
+ cached_nonlin_attn: left context for nonlin_attention module, a Tensor of shape
905
+ (num_heads, batch_size, left_context_len, head_dim)
906
+ cached_val1: cached left context for the first attention module,
907
+ of shape (left_context_len, batch_size, value_dim)
908
+ cached_val2: cached left context for the second attention module,
909
+ of shape (left_context_len, batch_size, value_dim)
910
+ cached_conv1: cached left context for the first convolution module,
911
+ of shape (batch_size, channels, left_pad)
912
+ cached_conv2: cached left context for the second convolution module,
913
+ of shape (batch_size, channels, left_pad)
914
+ left_context_len: number of left context frames.
915
+ src_key_padding_mask: the mask for padding, of shape
916
+ (batch_size, left_context_len + seq_len); True means masked position.
917
+ May be None.
918
+
919
+ Returns:
920
+ - x, with the same shape as src
921
+ - updated cached_key
922
+ - updated cached_nonlin_attn
923
+ - updated cached_val1
924
+ - updated cached_val2
925
+ - updated cached_conv1
926
+ - updated cached_conv2
927
+ """
928
+ src_orig = src
929
+
930
+ # attn_weights: (num_heads, batch_size, seq_len, seq_len)
931
+ attn_weights, cached_key = self.self_attn_weights.streaming_forward(
932
+ src,
933
+ pos_emb=pos_emb,
934
+ cached_key=cached_key,
935
+ left_context_len=left_context_len,
936
+ key_padding_mask=src_key_padding_mask,
937
+ )
938
+
939
+ src = src + self.feed_forward1(src)
940
+
941
+ na, cached_nonlin_attn = self.nonlin_attention.streaming_forward(
942
+ src,
943
+ attn_weights[0:1],
944
+ cached_x=cached_nonlin_attn,
945
+ left_context_len=left_context_len,
946
+ )
947
+ src = src + na
948
+
949
+ self_attn, cached_val1 = self.self_attn1.streaming_forward(
950
+ src,
951
+ attn_weights=attn_weights,
952
+ cached_val=cached_val1,
953
+ left_context_len=left_context_len,
954
+ )
955
+ src = src + self_attn
956
+
957
+ src_conv, cached_conv1 = self.conv_module1.streaming_forward(
958
+ src,
959
+ cache=cached_conv1,
960
+ src_key_padding_mask=src_key_padding_mask[:, left_context_len:],
961
+ )
962
+ src = src + src_conv
963
+
964
+ src = src + self.feed_forward2(src)
965
+
966
+ # bypass in the middle of the layer.
967
+ src = self.bypass_mid(src_orig, src)
968
+
969
+ self_attn, cached_val2 = self.self_attn2.streaming_forward(
970
+ src,
971
+ attn_weights=attn_weights,
972
+ cached_val=cached_val2,
973
+ left_context_len=left_context_len,
974
+ )
975
+ src = src + self_attn
976
+
977
+ src_conv, cached_conv2 = self.conv_module2.streaming_forward(
978
+ src,
979
+ cache=cached_conv2,
980
+ src_key_padding_mask=src_key_padding_mask[:, left_context_len:],
981
+ )
982
+ src = src + src_conv
983
+
984
+ src = src + self.feed_forward3(src)
985
+
986
+ src = self.norm(src)
987
+
988
+ src = self.bypass(src_orig, src)
989
+
990
+ return (
991
+ src,
992
+ cached_key,
993
+ cached_nonlin_attn,
994
+ cached_val1,
995
+ cached_val2,
996
+ cached_conv1,
997
+ cached_conv2,
998
+ )
999
+
1000
+
1001
+ class Zipformer2Encoder(nn.Module):
1002
+ r"""Zipformer2Encoder is a stack of N encoder layers
1003
+
1004
+ Args:
1005
+ encoder_layer: an instance of the Zipformer2EncoderLayer() class (required).
1006
+ num_layers: the number of sub-encoder-layers in the encoder (required).
1007
+ pos_dim: the dimension for the relative positional encoding
1008
+
1009
+ Examples::
1010
+ >>> encoder_layer = Zipformer2EncoderLayer(embed_dim=512, nhead=8)
1011
+ >>> zipformer_encoder = Zipformer2Encoder(encoder_layer, num_layers=6)
1012
+ >>> src = torch.rand(10, 32, 512)
1013
+ >>> out = zipformer_encoder(src)
1014
+ """
1015
+
1016
+ def __init__(
1017
+ self,
1018
+ encoder_layer: nn.Module,
1019
+ num_layers: int,
1020
+ pos_dim: int,
1021
+ dropout: float,
1022
+ warmup_begin: float,
1023
+ warmup_end: float,
1024
+ initial_layerdrop_rate: float = 0.5,
1025
+ final_layerdrop_rate: float = 0.05,
1026
+ ) -> None:
1027
+ super().__init__()
1028
+ self.encoder_pos = CompactRelPositionalEncoding(
1029
+ pos_dim, dropout_rate=0.15, length_factor=1.0
1030
+ )
1031
+
1032
+ self.layers = nn.ModuleList(
1033
+ [copy.deepcopy(encoder_layer) for i in range(num_layers)]
1034
+ )
1035
+ self.num_layers = num_layers
1036
+
1037
+ assert 0 <= warmup_begin <= warmup_end, (warmup_begin, warmup_end)
1038
+
1039
+ delta = (1.0 / num_layers) * (warmup_end - warmup_begin)
1040
+ cur_begin = warmup_begin # interpreted as a training batch index
1041
+ for i in range(num_layers):
1042
+ cur_end = cur_begin + delta
1043
+ self.layers[i].bypass.skip_rate = ScheduledFloat(
1044
+ (cur_begin, initial_layerdrop_rate),
1045
+ (cur_end, final_layerdrop_rate),
1046
+ default=0.0,
1047
+ )
1048
+ cur_begin = cur_end
1049
+
1050
+ def forward(
1051
+ self,
1052
+ src: Tensor,
1053
+ chunk_size: int = -1,
1054
+ feature_mask: Union[Tensor, float] = 1.0,
1055
+ attn_mask: Optional[Tensor] = None,
1056
+ src_key_padding_mask: Optional[Tensor] = None,
1057
+ ) -> Tensor:
1058
+ r"""Pass the input through the encoder layers in turn.
1059
+
1060
+ Args:
1061
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
1062
+ chunk_size: the number of frames per chunk, of >= 0; if -1, no chunking.
1063
+ feature_mask: something that broadcasts with src, that we'll multiply `src`
1064
+ by at every layer: if a Tensor, likely of shape (seq_len, batch_size, embedding_dim)
1065
+ attn_mask: the attention mask, of shape (batch_size, seq_len, seq_len) or (seq_len, seq_len),
1066
+ interpreted as (batch_size, tgt_seq_len, src_seq_len) or (tgt_seq_len, src_seq_len).
1067
+ True means masked position. May be None.
1068
+ src_key_padding_mask: the mask for padding, of shape (batch_size, seq_len); True means
1069
+ masked position. May be None.
1070
+
1071
+ Returns: a Tensor with the same shape as src.
1072
+ """
1073
+ pos_emb = self.encoder_pos(src)
1074
+ output = src
1075
+
1076
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1077
+ output = output * feature_mask
1078
+
1079
+ for i, mod in enumerate(self.layers):
1080
+ output = mod(
1081
+ output,
1082
+ pos_emb,
1083
+ chunk_size=chunk_size,
1084
+ attn_mask=attn_mask,
1085
+ src_key_padding_mask=src_key_padding_mask,
1086
+ )
1087
+
1088
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1089
+ output = output * feature_mask
1090
+
1091
+ return output
1092
+
1093
+ def streaming_forward(
1094
+ self,
1095
+ src: Tensor,
1096
+ states: List[Tensor],
1097
+ left_context_len: int,
1098
+ src_key_padding_mask: Tensor,
1099
+ ) -> Tuple[Tensor, List[Tensor]]:
1100
+ r"""Pass the input through the encoder layers in turn.
1101
+
1102
+ Args:
1103
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
1104
+ states: list of cached tensors of N encoder layers. For layer-i, states[i*6:(i+1)*6] is
1105
+ (cached_key, cached_nonlin_attn, cached_val1, cached_val2, cached_conv1, cached_conv2).
1106
+ left_context_len: Number of left context frames.
1107
+ src_key_padding_mask: the mask for padding, of shape
1108
+ (batch_size, left_context_len + seq_len); True means masked position.
1109
+ May be None.
1110
+
1111
+ Returns:
1112
+ - output, a Tensor with the same shape as src.
1113
+ - updated states
1114
+ """
1115
+ pos_emb = self.encoder_pos(src, left_context_len)
1116
+ output = src
1117
+
1118
+ new_states = []
1119
+ for i, mod in enumerate(self.layers):
1120
+ (
1121
+ cached_key,
1122
+ cached_nonlin_attn,
1123
+ cached_val1,
1124
+ cached_val2,
1125
+ cached_conv1,
1126
+ cached_conv2,
1127
+ ) = states[i * 6 : (i + 1) * 6]
1128
+ (
1129
+ output,
1130
+ new_cached_key,
1131
+ new_cached_nonlin_attn,
1132
+ new_cached_val1,
1133
+ new_cached_val2,
1134
+ new_cached_conv1,
1135
+ new_cached_conv2,
1136
+ ) = mod.streaming_forward(
1137
+ output,
1138
+ pos_emb,
1139
+ cached_key=cached_key,
1140
+ cached_nonlin_attn=cached_nonlin_attn,
1141
+ cached_val1=cached_val1,
1142
+ cached_val2=cached_val2,
1143
+ cached_conv1=cached_conv1,
1144
+ cached_conv2=cached_conv2,
1145
+ left_context_len=left_context_len,
1146
+ src_key_padding_mask=src_key_padding_mask,
1147
+ )
1148
+ new_states += [
1149
+ new_cached_key,
1150
+ new_cached_nonlin_attn,
1151
+ new_cached_val1,
1152
+ new_cached_val2,
1153
+ new_cached_conv1,
1154
+ new_cached_conv2,
1155
+ ]
1156
+
1157
+ return output, new_states
1158
+
1159
+
1160
+ class BypassModule(nn.Module):
1161
+ """
1162
+ An nn.Module that implements a learnable bypass scale, and also randomized per-sequence
1163
+ layer-skipping. The bypass is limited during early stages of training to be close to
1164
+ "straight-through", i.e. to not do the bypass operation much initially, in order to
1165
+ force all the modules to learn something.
1166
+ """
1167
+
1168
+ def __init__(
1169
+ self,
1170
+ embed_dim: int,
1171
+ skip_rate: FloatLike = 0.0,
1172
+ straight_through_rate: FloatLike = 0.0,
1173
+ scale_min: FloatLike = ScheduledFloat((0.0, 0.9), (20000.0, 0.2), default=0),
1174
+ scale_max: FloatLike = 1.0,
1175
+ ):
1176
+ super().__init__()
1177
+ self.bypass_scale = nn.Parameter(torch.full((embed_dim,), 0.5))
1178
+ self.skip_rate = copy.deepcopy(skip_rate)
1179
+ self.straight_through_rate = copy.deepcopy(straight_through_rate)
1180
+ self.scale_min = copy.deepcopy(scale_min)
1181
+ self.scale_max = copy.deepcopy(scale_max)
1182
+
1183
+ def _get_bypass_scale(self, batch_size: int):
1184
+ # returns bypass-scale of shape (num_channels,),
1185
+ # or (batch_size, num_channels,). This is actually the
1186
+ # scale on the non-residual term, so 0 corresponds to bypassing
1187
+ # this module.
1188
+ if torch.jit.is_scripting() or torch.jit.is_tracing() or not self.training:
1189
+ return self.bypass_scale
1190
+ else:
1191
+ ans = limit_param_value(
1192
+ self.bypass_scale, min=float(self.scale_min), max=float(self.scale_max)
1193
+ )
1194
+ skip_rate = float(self.skip_rate)
1195
+ if skip_rate != 0.0:
1196
+ mask = torch.rand((batch_size, 1), device=ans.device) > skip_rate
1197
+ ans = ans * mask
1198
+ # now ans is of shape (batch_size, num_channels), and is zero for sequences
1199
+ # on which we have randomly chosen to do layer-skipping.
1200
+ straight_through_rate = float(self.straight_through_rate)
1201
+ if straight_through_rate != 0.0:
1202
+ mask = (
1203
+ torch.rand((batch_size, 1), device=ans.device)
1204
+ < straight_through_rate
1205
+ )
1206
+ ans = torch.maximum(ans, mask.to(ans.dtype))
1207
+ return ans
1208
+
1209
+ def forward(self, src_orig: Tensor, src: Tensor):
1210
+ """
1211
+ Args: src_orig and src are both of shape (seq_len, batch_size, num_channels)
1212
+ Returns: something with the same shape as src and src_orig
1213
+ """
1214
+ bypass_scale = self._get_bypass_scale(src.shape[1])
1215
+ return src_orig + (src - src_orig) * bypass_scale
1216
+
1217
+
1218
+ class DownsampledZipformer2Encoder(nn.Module):
1219
+ r"""
1220
+ DownsampledZipformer2Encoder is a zipformer encoder evaluated at a reduced frame rate,
1221
+ after convolutional downsampling, and then upsampled again at the output, and combined
1222
+ with the origin input, so that the output has the same shape as the input.
1223
+ """
1224
+
1225
+ def __init__(
1226
+ self,
1227
+ encoder: nn.Module,
1228
+ dim: int,
1229
+ downsample: int,
1230
+ dropout: FloatLike,
1231
+ causal: bool,
1232
+ ):
1233
+ super(DownsampledZipformer2Encoder, self).__init__()
1234
+ self.downsample_factor = downsample
1235
+ self.downsample = SimpleDownsample(dim, downsample, dropout, causal)
1236
+ self.num_layers = encoder.num_layers
1237
+ self.encoder = encoder
1238
+ self.upsample = SimpleUpsample(dim, downsample)
1239
+ self.out_combiner = BypassModule(dim, straight_through_rate=0)
1240
+
1241
+ def forward(
1242
+ self,
1243
+ src: Tensor,
1244
+ chunk_size: int = -1,
1245
+ feature_mask: Union[Tensor, float] = 1.0,
1246
+ attn_mask: Optional[Tensor] = None,
1247
+ src_key_padding_mask: Optional[Tensor] = None,
1248
+ ) -> Tensor:
1249
+ r"""Downsample, go through encoder, upsample.
1250
+
1251
+ Args:
1252
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
1253
+ feature_mask: something that broadcasts with src, that we'll multiply `src`
1254
+ by at every layer: if a Tensor, likely of shape (seq_len, batch_size, embedding_dim)
1255
+ attn_mask: the attention mask, of shape (batch_size, seq_len, seq_len) or (seq_len, seq_len),
1256
+ interpreted as (batch_size, tgt_seq_len, src_seq_len) or (tgt_seq_len, src_seq_len).
1257
+ True means masked position. May be None.
1258
+ src_key_padding_mask: the mask for padding, of shape (batch_size, seq_len); True means
1259
+ masked position. May be None.
1260
+
1261
+ Returns: a Tensor with the same shape as src.
1262
+ """
1263
+ src_orig = src
1264
+ src = self.downsample(src)
1265
+ ds = self.downsample_factor
1266
+ if attn_mask is not None:
1267
+ attn_mask = attn_mask[::ds, ::ds]
1268
+
1269
+ src = self.encoder(
1270
+ src,
1271
+ chunk_size=chunk_size // ds,
1272
+ feature_mask=feature_mask,
1273
+ attn_mask=attn_mask,
1274
+ src_key_padding_mask=src_key_padding_mask,
1275
+ )
1276
+ src = self.upsample(src)
1277
+ # remove any extra frames that are not a multiple of downsample_factor
1278
+ src = src[: src_orig.shape[0]]
1279
+
1280
+ return self.out_combiner(src_orig, src)
1281
+
1282
+ def streaming_forward(
1283
+ self,
1284
+ src: Tensor,
1285
+ states: List[Tensor],
1286
+ left_context_len: int,
1287
+ src_key_padding_mask: Tensor,
1288
+ ) -> Tuple[Tensor, List[Tensor]]:
1289
+ r"""Downsample, go through encoder, upsample, in streaming forward mode.
1290
+
1291
+ Args:
1292
+ src: the sequence to the encoder (required): shape (seq_len, batch_size, embedding_dim).
1293
+ states: list of cached tensors of N encoder layers. For layer-i, states[i*6:(i+1)*6] is
1294
+ (cached_key, cached_nonlin_attn, cached_val1, cached_val2, cached_conv1, cached_conv2).
1295
+ left_context_len: Number of left context frames.
1296
+ src_key_padding_mask: the mask for padding, of shape (batch_size, left_context_len+seq_len);
1297
+ True means masked position. May be None.
1298
+
1299
+ Returns:
1300
+ - output, a Tensor with the same shape as src.
1301
+ - updated states
1302
+ """
1303
+ src_orig = src
1304
+ src = self.downsample(src)
1305
+
1306
+ src, new_states = self.encoder.streaming_forward(
1307
+ src,
1308
+ states=states,
1309
+ left_context_len=left_context_len,
1310
+ src_key_padding_mask=src_key_padding_mask,
1311
+ )
1312
+ src = self.upsample(src)
1313
+ # remove any extra frames that are not a multiple of downsample_factor
1314
+ src = src[: src_orig.shape[0]]
1315
+
1316
+ return self.out_combiner(src_orig, src), new_states
1317
+
1318
+
1319
+ class SimpleDownsample(torch.nn.Module):
1320
+ """
1321
+ Does downsampling with attention, by weighted sum, and a projection..
1322
+ """
1323
+
1324
+ def __init__(
1325
+ self, channels: int, downsample: int, dropout: FloatLike, causal: bool
1326
+ ):
1327
+ super(SimpleDownsample, self).__init__()
1328
+
1329
+ self.causal = causal
1330
+ self.bias = nn.Parameter(torch.zeros(downsample))
1331
+
1332
+ self.name = None # will be set from training code
1333
+ self.dropout = copy.deepcopy(dropout)
1334
+
1335
+ self.downsample = downsample
1336
+
1337
+ def forward(self, src: Tensor) -> Tensor:
1338
+ """
1339
+ x: (seq_len, batch_size, in_channels)
1340
+ Returns a tensor of shape
1341
+ ( (seq_len+downsample-1)//downsample, batch_size, channels)
1342
+ """
1343
+ seq_len, batch_size, in_channels = src.shape
1344
+ ds = self.downsample
1345
+ d_seq_len = (seq_len + ds - 1) // ds
1346
+
1347
+ # Pad to an exact multiple of self.downsample
1348
+ # right-pad src, repeating the last element.
1349
+ pad = d_seq_len * ds - seq_len
1350
+
1351
+ # If we are exporting a streaming model, then we skip the if statement
1352
+ if not self.causal or not torch.jit.is_tracing():
1353
+ if pad > 0:
1354
+ src_extra = src[src.shape[0] - 1 :].expand(
1355
+ pad, src.shape[1], src.shape[2]
1356
+ )
1357
+ src = torch.cat((src, src_extra), dim=0)
1358
+ elif self.causal and torch.jit.is_scripting():
1359
+ if pad > 0:
1360
+ src_extra = src[src.shape[0] - 1 :].expand(
1361
+ pad, src.shape[1], src.shape[2]
1362
+ )
1363
+ src = torch.cat((src, src_extra), dim=0)
1364
+
1365
+ src = src.reshape(d_seq_len, ds, batch_size, in_channels)
1366
+
1367
+ weights = self.bias.softmax(dim=0)
1368
+ # weights: (downsample, 1, 1)
1369
+ weights = weights.unsqueeze(-1).unsqueeze(-1)
1370
+
1371
+ # ans1 is the first `in_channels` channels of the output
1372
+ ans = (src * weights).sum(dim=1)
1373
+
1374
+ return ans
1375
+
1376
+
1377
+ class SimpleUpsample(torch.nn.Module):
1378
+ """
1379
+ A very simple form of upsampling that mostly just repeats the input, but
1380
+ also adds a position-specific bias.
1381
+ """
1382
+
1383
+ def __init__(self, num_channels: int, upsample: int):
1384
+ super(SimpleUpsample, self).__init__()
1385
+ self.upsample = upsample
1386
+
1387
+ def forward(self, src: Tensor) -> Tensor:
1388
+ """
1389
+ x: (seq_len, batch_size, num_channels)
1390
+ Returns a tensor of shape
1391
+ ( (seq_len*upsample), batch_size, num_channels)
1392
+ """
1393
+ upsample = self.upsample
1394
+ seq_len, batch_size, num_channels = src.shape
1395
+ src = src.unsqueeze(1).expand(seq_len, upsample, batch_size, num_channels)
1396
+ src = src.reshape(seq_len * upsample, batch_size, num_channels)
1397
+ return src
1398
+
1399
+
1400
+ class CompactRelPositionalEncoding(torch.nn.Module):
1401
+ """
1402
+ Relative positional encoding module. This version is "compact" meaning it is able to encode
1403
+ the important information about the relative position in a relatively small number of dimensions.
1404
+ The goal is to make it so that small differences between large relative offsets (e.g. 1000 vs. 1001)
1405
+ make very little difference to the embedding. Such differences were potentially important
1406
+ when encoding absolute position, but not important when encoding relative position because there
1407
+ is now no need to compare two large offsets with each other.
1408
+
1409
+ Our embedding works by projecting the interval [-infinity,infinity] to a finite interval
1410
+ using the atan() function, before doing the Fourier transform of that fixed interval. The
1411
+ atan() function would compress the "long tails" too small,
1412
+ making it hard to distinguish between different magnitudes of large offsets, so we use a logarithmic
1413
+ function to compress large offsets to a smaller range before applying atan().
1414
+ Scalings are chosen in such a way that the embedding can clearly distinguish individual offsets as long
1415
+ as they are quite close to the origin, e.g. abs(offset) <= about sqrt(embedding_dim)
1416
+
1417
+
1418
+ Args:
1419
+ embed_dim: Embedding dimension.
1420
+ dropout_rate: Dropout rate.
1421
+ max_len: Maximum input length: just a heuristic for initialization.
1422
+ length_factor: a heuristic scale (should be >= 1.0) which, if larger, gives
1423
+ less weight to small differences of offset near the origin.
1424
+ """
1425
+
1426
+ def __init__(
1427
+ self,
1428
+ embed_dim: int,
1429
+ dropout_rate: FloatLike,
1430
+ max_len: int = 2000,
1431
+ length_factor: float = 1.0,
1432
+ ) -> None:
1433
+ """Construct a CompactRelPositionalEncoding object."""
1434
+ super(CompactRelPositionalEncoding, self).__init__()
1435
+ self.embed_dim = embed_dim
1436
+ assert embed_dim % 2 == 0, embed_dim
1437
+ self.dropout = Dropout2(dropout_rate)
1438
+ self.pe = None
1439
+ assert length_factor >= 1.0, length_factor
1440
+ self.length_factor = length_factor
1441
+ self.extend_pe(torch.tensor(0.0).expand(max_len))
1442
+
1443
+ def extend_pe(self, x: Tensor, left_context_len: int = 0) -> None:
1444
+ """Reset the positional encodings."""
1445
+ T = x.size(0) + left_context_len
1446
+
1447
+ if self.pe is not None:
1448
+ # self.pe contains both positive and negative parts
1449
+ # the length of self.pe is 2 * input_len - 1
1450
+ if self.pe.size(0) >= T * 2 - 1:
1451
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
1452
+ return
1453
+
1454
+ # if T == 4, x would contain [ -3, -2, 1, 0, 1, 2, 3 ]
1455
+ x = torch.arange(-(T - 1), T, device=x.device).to(torch.float32).unsqueeze(1)
1456
+
1457
+ freqs = 1 + torch.arange(self.embed_dim // 2, device=x.device)
1458
+
1459
+ # `compression_length` this is arbitrary/heuristic, if it is larger we have more resolution
1460
+ # for small time offsets but less resolution for large time offsets.
1461
+ compression_length = self.embed_dim**0.5
1462
+ # x_compressed, like X, goes from -infinity to infinity as T goes from -infinity to infinity;
1463
+ # but it does so more slowly than T for large absolute values of T.
1464
+ # The formula is chosen so that d(x_compressed )/dx is 1 around x == 0, which
1465
+ # is important.
1466
+ x_compressed = (
1467
+ compression_length
1468
+ * x.sign()
1469
+ * ((x.abs() + compression_length).log() - math.log(compression_length))
1470
+ )
1471
+
1472
+ # if self.length_factor == 1.0, then length_scale is chosen so that the
1473
+ # FFT can exactly separate points close to the origin (T == 0). So this
1474
+ # part of the formulation is not really heuristic.
1475
+ # But empirically, for ASR at least, length_factor > 1.0 seems to work better.
1476
+ length_scale = self.length_factor * self.embed_dim / (2.0 * math.pi)
1477
+
1478
+ # note for machine implementations: if atan is not available, we can use:
1479
+ # x.sign() * ((1 / (x.abs() + 1)) - 1) * (-math.pi/2)
1480
+ # check on wolframalpha.com: plot(sign(x) * (1 / ( abs(x) + 1) - 1 ) * -pi/2 , atan(x))
1481
+ x_atan = (x_compressed / length_scale).atan() # results between -pi and pi
1482
+
1483
+ cosines = (x_atan * freqs).cos()
1484
+ sines = (x_atan * freqs).sin()
1485
+
1486
+ pe = torch.zeros(x.shape[0], self.embed_dim, device=x.device)
1487
+ pe[:, 0::2] = cosines
1488
+ pe[:, 1::2] = sines
1489
+ pe[:, -1] = 1.0 # for bias.
1490
+
1491
+ self.pe = pe.to(dtype=x.dtype)
1492
+
1493
+ def forward(self, x: Tensor, left_context_len: int = 0) -> Tensor:
1494
+ """Create positional encoding.
1495
+
1496
+ Args:
1497
+ x (Tensor): Input tensor (time, batch, `*`).
1498
+ left_context_len: (int): Length of cached left context.
1499
+
1500
+ Returns:
1501
+ positional embedding, of shape (batch, left_context_len + 2*time-1, `*`).
1502
+ """
1503
+ if not torch.jit.is_scripting():
1504
+ self.extend_pe(x, left_context_len)
1505
+ assert self.pe is not None
1506
+ pe = self.pe
1507
+ x_size_left = x.size(0) + left_context_len
1508
+ # length of positive side: x.size(0) + left_context_len
1509
+ # length of negative side: x.size(0)
1510
+ start_pos = pe.size(0) // 2 - x_size_left + 1
1511
+ end_pos = pe.size(0) // 2 + x.size(0)
1512
+ pos_emb = pe[start_pos:end_pos]
1513
+ pos_emb = pos_emb.unsqueeze(0)
1514
+ return self.dropout(pos_emb)
1515
+
1516
+
1517
+ class RelPositionMultiheadAttentionWeights(nn.Module):
1518
+ r"""Module that computes multi-head attention weights with relative position encoding.
1519
+ Various other modules consume the resulting attention weights: see, for example, the
1520
+ SimpleAttention module which allows you to compute conventional attention.
1521
+
1522
+ This is a quite heavily modified from: "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context",
1523
+ we have to write up the differences.
1524
+
1525
+
1526
+ Args:
1527
+ embed_dim: number of channels at the input to this module, e.g. 256
1528
+ pos_dim: dimension of the positional encoding vectors, e.g. 128.
1529
+ num_heads: number of heads to compute weights for, e.g. 8
1530
+ query_head_dim: dimension of the query (and key), per head. e.g. 24.
1531
+ pos_head_dim: dimension of the projected positional encoding per head, e.g. 4.
1532
+ dropout: dropout probability for attn_output_weights. Default: 0.0.
1533
+ pos_emb_skip_rate: probability for skipping the pos_emb part of the scores on
1534
+ any given call to forward(), in training time.
1535
+ """
1536
+
1537
+ def __init__(
1538
+ self,
1539
+ embed_dim: int,
1540
+ pos_dim: int,
1541
+ num_heads: int,
1542
+ query_head_dim: int,
1543
+ pos_head_dim: int,
1544
+ dropout: float = 0.0,
1545
+ pos_emb_skip_rate: FloatLike = ScheduledFloat((0.0, 0.5), (4000.0, 0.0)),
1546
+ ) -> None:
1547
+ super().__init__()
1548
+ self.embed_dim = embed_dim
1549
+ self.num_heads = num_heads
1550
+ self.query_head_dim = query_head_dim
1551
+ self.pos_head_dim = pos_head_dim
1552
+ self.dropout = dropout
1553
+ self.pos_emb_skip_rate = copy.deepcopy(pos_emb_skip_rate)
1554
+ self.name = None # will be overwritten in training code; for diagnostics.
1555
+
1556
+ key_head_dim = query_head_dim
1557
+ in_proj_dim = (query_head_dim + key_head_dim + pos_head_dim) * num_heads
1558
+
1559
+ # the initial_scale is supposed to take over the "scaling" factor of
1560
+ # head_dim ** -0.5 that has been used in previous forms of attention,
1561
+ # dividing it between the query and key. Note: this module is intended
1562
+ # to be used with the ScaledAdam optimizer; with most other optimizers,
1563
+ # it would be necessary to apply the scaling factor in the forward function.
1564
+ self.in_proj = ScaledLinear(
1565
+ embed_dim, in_proj_dim, bias=True, initial_scale=query_head_dim**-0.25
1566
+ )
1567
+
1568
+ self.whiten_keys = Whiten(
1569
+ num_groups=num_heads,
1570
+ whitening_limit=_whitening_schedule(3.0),
1571
+ prob=(0.025, 0.25),
1572
+ grad_scale=0.025,
1573
+ )
1574
+
1575
+ # add a balancer for the keys that runs with very small probability, and
1576
+ # tries to enforce that all dimensions have mean around zero. The
1577
+ # weights produced by this module are invariant to adding a constant to
1578
+ # the keys, so the derivative of the bias is mathematically zero; but
1579
+ # due to how Adam/ScaledAdam work, it can learn a fairly large nonzero
1580
+ # bias because the small numerical roundoff tends to have a non-random
1581
+ # sign. This module is intended to prevent that. Use a very small
1582
+ # probability; that should be sufficient to fix the problem.
1583
+ self.balance_keys = Balancer(
1584
+ key_head_dim * num_heads,
1585
+ channel_dim=-1,
1586
+ min_positive=0.4,
1587
+ max_positive=0.6,
1588
+ min_abs=0.0,
1589
+ max_abs=100.0,
1590
+ prob=0.025,
1591
+ )
1592
+
1593
+ # linear transformation for positional encoding.
1594
+ self.linear_pos = ScaledLinear(
1595
+ pos_dim, num_heads * pos_head_dim, bias=False, initial_scale=0.05
1596
+ )
1597
+
1598
+ # the following are for diagnostics only, see --print-diagnostics option
1599
+ self.copy_pos_query = Identity()
1600
+ self.copy_query = Identity()
1601
+
1602
+ def forward(
1603
+ self,
1604
+ x: Tensor,
1605
+ pos_emb: Tensor,
1606
+ key_padding_mask: Optional[Tensor] = None,
1607
+ attn_mask: Optional[Tensor] = None,
1608
+ ) -> Tensor:
1609
+ r"""
1610
+ Args:
1611
+ x: input of shape (seq_len, batch_size, embed_dim)
1612
+ pos_emb: Positional embedding tensor, of shape (1, 2*seq_len - 1, pos_dim)
1613
+ key_padding_mask: a bool tensor of shape (batch_size, seq_len). Positions that
1614
+ are True in this mask will be ignored as sources in the attention weighting.
1615
+ attn_mask: mask of shape (seq_len, seq_len) or (batch_size, seq_len, seq_len),
1616
+ interpreted as ([batch_size,] tgt_seq_len, src_seq_len)
1617
+ saying which positions are allowed to attend to which other positions.
1618
+ Returns:
1619
+ a tensor of attention weights, of shape (hum_heads, batch_size, seq_len, seq_len)
1620
+ interpreted as (hum_heads, batch_size, tgt_seq_len, src_seq_len).
1621
+ """
1622
+ x = self.in_proj(x)
1623
+ query_head_dim = self.query_head_dim
1624
+ pos_head_dim = self.pos_head_dim
1625
+ num_heads = self.num_heads
1626
+
1627
+ seq_len, batch_size, _ = x.shape
1628
+
1629
+ query_dim = query_head_dim * num_heads
1630
+
1631
+ # self-attention
1632
+ q = x[..., 0:query_dim]
1633
+ k = x[..., query_dim : 2 * query_dim]
1634
+ # p is the position-encoding query
1635
+ p = x[..., 2 * query_dim :]
1636
+ assert p.shape[-1] == num_heads * pos_head_dim, (
1637
+ p.shape[-1],
1638
+ num_heads,
1639
+ pos_head_dim,
1640
+ )
1641
+
1642
+ q = self.copy_query(q) # for diagnostics only, does nothing.
1643
+ k = self.whiten_keys(self.balance_keys(k)) # does nothing in the forward pass.
1644
+ p = self.copy_pos_query(p) # for diagnostics only, does nothing.
1645
+
1646
+ q = q.reshape(seq_len, batch_size, num_heads, query_head_dim)
1647
+ p = p.reshape(seq_len, batch_size, num_heads, pos_head_dim)
1648
+ k = k.reshape(seq_len, batch_size, num_heads, query_head_dim)
1649
+
1650
+ # time1 refers to target, time2 refers to source.
1651
+ q = q.permute(2, 1, 0, 3) # (head, batch, time1, query_head_dim)
1652
+ p = p.permute(2, 1, 0, 3) # (head, batch, time1, pos_head_dim)
1653
+ k = k.permute(2, 1, 3, 0) # (head, batch, d_k, time2)
1654
+
1655
+ attn_scores = torch.matmul(q, k)
1656
+
1657
+ use_pos_scores = False
1658
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1659
+ # We can't put random.random() in the same line
1660
+ use_pos_scores = True
1661
+ elif not self.training or random.random() >= float(self.pos_emb_skip_rate):
1662
+ use_pos_scores = True
1663
+
1664
+ if use_pos_scores:
1665
+ pos_emb = self.linear_pos(pos_emb)
1666
+ seq_len2 = 2 * seq_len - 1
1667
+ pos_emb = pos_emb.reshape(-1, seq_len2, num_heads, pos_head_dim).permute(
1668
+ 2, 0, 3, 1
1669
+ )
1670
+ # pos shape now: (head, {1 or batch_size}, pos_dim, seq_len2)
1671
+
1672
+ # (head, batch, time1, pos_dim) x (head, 1, pos_dim, seq_len2) -> (head, batch, time1, seq_len2)
1673
+ # [where seq_len2 represents relative position.]
1674
+ pos_scores = torch.matmul(p, pos_emb)
1675
+ # the following .as_strided() expression converts the last axis of pos_scores from relative
1676
+ # to absolute position. I don't know whether I might have got the time-offsets backwards or
1677
+ # not, but let this code define which way round it is supposed to be.
1678
+ if torch.jit.is_tracing():
1679
+ num_heads, batch_size, time1, n = pos_scores.shape
1680
+ rows = torch.arange(start=time1 - 1, end=-1, step=-1)
1681
+ cols = torch.arange(seq_len)
1682
+ rows = rows.repeat(batch_size * num_heads).unsqueeze(-1)
1683
+ indexes = rows + cols
1684
+ pos_scores = pos_scores.reshape(-1, n)
1685
+ pos_scores = torch.gather(pos_scores, dim=1, index=indexes)
1686
+ pos_scores = pos_scores.reshape(num_heads, batch_size, time1, seq_len)
1687
+ else:
1688
+ pos_scores = pos_scores.as_strided(
1689
+ (num_heads, batch_size, seq_len, seq_len),
1690
+ (
1691
+ pos_scores.stride(0),
1692
+ pos_scores.stride(1),
1693
+ pos_scores.stride(2) - pos_scores.stride(3),
1694
+ pos_scores.stride(3),
1695
+ ),
1696
+ storage_offset=pos_scores.stride(3) * (seq_len - 1),
1697
+ )
1698
+
1699
+ attn_scores = attn_scores + pos_scores
1700
+
1701
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1702
+ pass
1703
+ elif self.training and random.random() < 0.1:
1704
+ # This is a harder way of limiting the attention scores to not be
1705
+ # too large. It incurs a penalty if any of them has an absolute
1706
+ # value greater than 50.0. this should be outside the normal range
1707
+ # of the attention scores. We use this mechanism instead of, say,
1708
+ # something added to the loss function involving the entropy,
1709
+ # because once the entropy gets very small gradients through the
1710
+ # softmax can become very small, and we'd get zero derivatives. The
1711
+ # choices of 1.0e-04 as the scale on the penalty makes this
1712
+ # mechanism vulnerable to the absolute scale of the loss function,
1713
+ # but we view this as a failsafe to avoid "implausible" parameter
1714
+ # values rather than a regularization method that should be active
1715
+ # under normal circumstances.
1716
+ attn_scores = penalize_abs_values_gt(
1717
+ attn_scores, limit=25.0, penalty=1.0e-04, name=self.name
1718
+ )
1719
+
1720
+ assert attn_scores.shape == (num_heads, batch_size, seq_len, seq_len)
1721
+
1722
+ if attn_mask is not None:
1723
+ assert attn_mask.dtype == torch.bool
1724
+ # use -1000 to avoid nan's where attn_mask and key_padding_mask make
1725
+ # all scores zero. It's important that this be large enough that exp(-1000)
1726
+ # is exactly zero, for reasons related to const_attention_rate, it
1727
+ # compares the final weights with zero.
1728
+ attn_scores = attn_scores.masked_fill(attn_mask, -1000)
1729
+
1730
+ if key_padding_mask is not None:
1731
+ assert key_padding_mask.shape == (
1732
+ batch_size,
1733
+ seq_len,
1734
+ ), key_padding_mask.shape
1735
+ attn_scores = attn_scores.masked_fill(
1736
+ key_padding_mask.to(torch.bool).unsqueeze(1),
1737
+ -1000,
1738
+ )
1739
+
1740
+ # We use our own version of softmax, defined in scaling.py, which should
1741
+ # save a little of the memory used in backprop by, if we are in
1742
+ # automatic mixed precision mode (amp / autocast), by only storing the
1743
+ # half-precision output for backprop purposes.
1744
+ attn_weights = softmax(attn_scores, dim=-1)
1745
+
1746
+ if torch.jit.is_scripting() or torch.jit.is_tracing():
1747
+ pass
1748
+ elif random.random() < 0.001 and not self.training:
1749
+ self._print_attn_entropy(attn_weights)
1750
+
1751
+ attn_weights = nn.functional.dropout(
1752
+ attn_weights, p=self.dropout, training=self.training
1753
+ )
1754
+
1755
+ return attn_weights
1756
+
1757
+ def streaming_forward(
1758
+ self,
1759
+ x: Tensor,
1760
+ pos_emb: Tensor,
1761
+ cached_key: Tensor,
1762
+ left_context_len: int,
1763
+ key_padding_mask: Tensor,
1764
+ ) -> Tuple[Tensor, Tensor]:
1765
+ r"""
1766
+ Args:
1767
+ x: input of shape (seq_len, batch_size, embed_dim)
1768
+ pos_emb: Positional embedding tensor, of shape (1, left_context_len+2*seq_len-1, pos_dim)
1769
+ cached_key: cached attention key tensor of left context,
1770
+ of shape (left_context_len, batch_size, key_dim)
1771
+ left_context_len: number of left context frames.
1772
+ key_padding_mask: a bool tensor of shape (batch_size, seq_len). Positions that
1773
+ are True in this mask will be ignored as sources in the attention weighting.
1774
+
1775
+ Returns:
1776
+ - attention weights, of shape (hum_heads, batch_size, seq_len, seq_len2),
1777
+ interpreted as (hum_heads, batch_size, tgt_seq_len, src_seq_len).
1778
+ - updated cached attention key tensor of left context.
1779
+ """
1780
+ x = self.in_proj(x)
1781
+ query_head_dim = self.query_head_dim
1782
+ pos_head_dim = self.pos_head_dim
1783
+ num_heads = self.num_heads
1784
+
1785
+ seq_len, batch_size, _ = x.shape
1786
+
1787
+ query_dim = query_head_dim * num_heads
1788
+
1789
+ # self-attention
1790
+ q = x[..., 0:query_dim]
1791
+ k = x[..., query_dim : 2 * query_dim]
1792
+ # p is the position-encoding query
1793
+ p = x[..., 2 * query_dim :]
1794
+ assert p.shape[-1] == num_heads * pos_head_dim
1795
+
1796
+ # Pad cached left contexts
1797
+ assert cached_key.shape[0] == left_context_len, (
1798
+ cached_key.shape[0],
1799
+ left_context_len,
1800
+ )
1801
+ k = torch.cat([cached_key, k], dim=0)
1802
+ # Update cached left contexts
1803
+ cached_key = k[-left_context_len:, ...]
1804
+
1805
+ # The length of key
1806
+ k_len = k.shape[0]
1807
+
1808
+ q = q.reshape(seq_len, batch_size, num_heads, query_head_dim)
1809
+ p = p.reshape(seq_len, batch_size, num_heads, pos_head_dim)
1810
+ k = k.reshape(k_len, batch_size, num_heads, query_head_dim)
1811
+
1812
+ # time1 refers to target, time2 refers to source.
1813
+ q = q.permute(2, 1, 0, 3) # (head, batch, time1, query_head_dim)
1814
+ p = p.permute(2, 1, 0, 3) # (head, batch, time1, pos_head_dim)
1815
+ k = k.permute(2, 1, 3, 0) # (head, batch, d_k, time2)
1816
+
1817
+ attn_scores = torch.matmul(q, k)
1818
+
1819
+ pos_emb = self.linear_pos(pos_emb)
1820
+ seq_len2 = 2 * seq_len - 1 + left_context_len
1821
+ pos_emb = pos_emb.reshape(-1, seq_len2, num_heads, pos_head_dim).permute(
1822
+ 2, 0, 3, 1
1823
+ )
1824
+ # pos shape now: (head, {1 or batch_size}, pos_dim, seq_len2)
1825
+
1826
+ # (head, batch, time1, pos_dim) x (head, 1, pos_dim, seq_len2) -> (head, batch, time1, seq_len2)
1827
+ # [where seq_len2 represents relative position.]
1828
+ pos_scores = torch.matmul(p, pos_emb)
1829
+
1830
+ if torch.jit.is_tracing():
1831
+ num_heads, batch_size, time1, n = pos_scores.shape
1832
+ rows = torch.arange(start=time1 - 1, end=-1, step=-1)
1833
+ cols = torch.arange(k_len)
1834
+ rows = rows.repeat(batch_size * num_heads).unsqueeze(-1)
1835
+ indexes = rows + cols
1836
+ pos_scores = pos_scores.reshape(-1, n)
1837
+ pos_scores = torch.gather(pos_scores, dim=1, index=indexes)
1838
+ pos_scores = pos_scores.reshape(num_heads, batch_size, time1, k_len)
1839
+ # the following .as_strided() expression converts the last axis of pos_scores from relative
1840
+ # to absolute position. I don't know whether I might have got the time-offsets backwards or
1841
+ # not, but let this code define which way round it is supposed to be.
1842
+ else:
1843
+ pos_scores = pos_scores.as_strided(
1844
+ (num_heads, batch_size, seq_len, k_len),
1845
+ (
1846
+ pos_scores.stride(0),
1847
+ pos_scores.stride(1),
1848
+ pos_scores.stride(2) - pos_scores.stride(3),
1849
+ pos_scores.stride(3),
1850
+ ),
1851
+ storage_offset=pos_scores.stride(3) * (seq_len - 1),
1852
+ )
1853
+
1854
+ attn_scores = attn_scores + pos_scores
1855
+
1856
+ assert attn_scores.shape == (
1857
+ num_heads,
1858
+ batch_size,
1859
+ seq_len,
1860
+ k_len,
1861
+ ), attn_scores.shape
1862
+
1863
+ if key_padding_mask is not None:
1864
+ assert key_padding_mask.shape == (batch_size, k_len), key_padding_mask.shape
1865
+ attn_scores = attn_scores.masked_fill(
1866
+ key_padding_mask.to(torch.bool).unsqueeze(1),
1867
+ -1000,
1868
+ )
1869
+
1870
+ attn_weights = attn_scores.softmax(dim=-1)
1871
+
1872
+ return attn_weights, cached_key
1873
+
1874
+ def _print_attn_entropy(self, attn_weights: Tensor):
1875
+ # attn_weights: (num_heads, batch_size, seq_len, seq_len)
1876
+ num_heads, batch_size, seq_len, seq_len = attn_weights.shape
1877
+
1878
+ with torch.no_grad():
1879
+ with torch_autocast(enabled=False):
1880
+ attn_weights = attn_weights.to(torch.float32)
1881
+ attn_weights_entropy = (
1882
+ -((attn_weights + 1.0e-20).log() * attn_weights)
1883
+ .sum(dim=-1)
1884
+ .mean(dim=(1, 2))
1885
+ )
1886
+ logging.info(
1887
+ f"name={self.name}, attn_weights_entropy = {attn_weights_entropy}"
1888
+ )
1889
+
1890
+
1891
+ class SelfAttention(nn.Module):
1892
+ """
1893
+ The simplest possible attention module. This one works with already-computed attention
1894
+ weights, e.g. as computed by RelPositionMultiheadAttentionWeights.
1895
+
1896
+ Args:
1897
+ embed_dim: the input and output embedding dimension
1898
+ num_heads: the number of attention heads
1899
+ value_head_dim: the value dimension per head
1900
+ """
1901
+
1902
+ def __init__(
1903
+ self,
1904
+ embed_dim: int,
1905
+ num_heads: int,
1906
+ value_head_dim: int,
1907
+ ) -> None:
1908
+ super().__init__()
1909
+ self.in_proj = nn.Linear(embed_dim, num_heads * value_head_dim, bias=True)
1910
+
1911
+ self.out_proj = ScaledLinear(
1912
+ num_heads * value_head_dim, embed_dim, bias=True, initial_scale=0.05
1913
+ )
1914
+
1915
+ self.whiten = Whiten(
1916
+ num_groups=1,
1917
+ whitening_limit=_whitening_schedule(7.5, ratio=3.0),
1918
+ prob=(0.025, 0.25),
1919
+ grad_scale=0.01,
1920
+ )
1921
+
1922
+ def forward(
1923
+ self,
1924
+ x: Tensor,
1925
+ attn_weights: Tensor,
1926
+ ) -> Tensor:
1927
+ """
1928
+ Args:
1929
+ x: input tensor, of shape (seq_len, batch_size, embed_dim)
1930
+ attn_weights: a tensor of shape (num_heads, batch_size, seq_len, seq_len),
1931
+ with seq_len being interpreted as (tgt_seq_len, src_seq_len). Expect
1932
+ attn_weights.sum(dim=-1) == 1.
1933
+ Returns:
1934
+ a tensor with the same shape as x.
1935
+ """
1936
+ seq_len, batch_size, embed_dim = x.shape
1937
+ num_heads = attn_weights.shape[0]
1938
+ assert attn_weights.shape == (num_heads, batch_size, seq_len, seq_len)
1939
+
1940
+ x = self.in_proj(x) # (seq_len, batch_size, num_heads * value_head_dim)
1941
+ x = x.reshape(seq_len, batch_size, num_heads, -1).permute(2, 1, 0, 3)
1942
+ # now x: (num_heads, batch_size, seq_len, value_head_dim)
1943
+ value_head_dim = x.shape[-1]
1944
+
1945
+ # todo: see whether there is benefit in overriding matmul
1946
+ x = torch.matmul(attn_weights, x)
1947
+ # v: (num_heads, batch_size, seq_len, value_head_dim)
1948
+
1949
+ x = (
1950
+ x.permute(2, 1, 0, 3)
1951
+ .contiguous()
1952
+ .view(seq_len, batch_size, num_heads * value_head_dim)
1953
+ )
1954
+
1955
+ # returned value is of shape (seq_len, batch_size, embed_dim), like the input.
1956
+ x = self.out_proj(x)
1957
+ x = self.whiten(x)
1958
+
1959
+ return x
1960
+
1961
+ def streaming_forward(
1962
+ self,
1963
+ x: Tensor,
1964
+ attn_weights: Tensor,
1965
+ cached_val: Tensor,
1966
+ left_context_len: int,
1967
+ ) -> Tuple[Tensor, Tensor]:
1968
+ """
1969
+ Args:
1970
+ x: input tensor, of shape (seq_len, batch_size, embed_dim)
1971
+ attn_weights: a tensor of shape (num_heads, batch_size, seq_len, seq_len),
1972
+ with seq_len being interpreted as (tgt_seq_len, src_seq_len). Expect
1973
+ attn_weights.sum(dim=-1) == 1.
1974
+ cached_val: cached attention value tensor of left context,
1975
+ of shape (left_context_len, batch_size, value_dim)
1976
+ left_context_len: number of left context frames.
1977
+
1978
+ Returns:
1979
+ - attention weighted output, a tensor with the same shape as x.
1980
+ - updated cached attention value tensor of left context.
1981
+ """
1982
+ seq_len, batch_size, embed_dim = x.shape
1983
+ num_heads = attn_weights.shape[0]
1984
+ seq_len2 = seq_len + left_context_len
1985
+ assert attn_weights.shape == (num_heads, batch_size, seq_len, seq_len2)
1986
+
1987
+ x = self.in_proj(x) # (seq_len, batch_size, num_heads * value_head_dim)
1988
+
1989
+ # Pad cached left contexts
1990
+ assert cached_val.shape[0] == left_context_len, (
1991
+ cached_val.shape[0],
1992
+ left_context_len,
1993
+ )
1994
+ x = torch.cat([cached_val, x], dim=0)
1995
+ # Update cached left contexts
1996
+ cached_val = x[-left_context_len:, ...]
1997
+
1998
+ x = x.reshape(seq_len2, batch_size, num_heads, -1).permute(2, 1, 0, 3)
1999
+ # now x: (num_heads, batch_size, seq_len, value_head_dim)
2000
+ value_head_dim = x.shape[-1]
2001
+
2002
+ # todo: see whether there is benefit in overriding matmul
2003
+ x = torch.matmul(attn_weights, x)
2004
+ # v: (num_heads, batch_size, seq_len, value_head_dim)
2005
+
2006
+ x = (
2007
+ x.permute(2, 1, 0, 3)
2008
+ .contiguous()
2009
+ .view(seq_len, batch_size, num_heads * value_head_dim)
2010
+ )
2011
+
2012
+ # returned value is of shape (seq_len, batch_size, embed_dim), like the input.
2013
+ x = self.out_proj(x)
2014
+
2015
+ return x, cached_val
2016
+
2017
+
2018
+ class FeedforwardModule(nn.Module):
2019
+ """Feedforward module in Zipformer2 model."""
2020
+
2021
+ def __init__(self, embed_dim: int, feedforward_dim: int, dropout: FloatLike):
2022
+ super(FeedforwardModule, self).__init__()
2023
+ self.in_proj = nn.Linear(embed_dim, feedforward_dim)
2024
+
2025
+ self.hidden_balancer = Balancer(
2026
+ feedforward_dim,
2027
+ channel_dim=-1,
2028
+ min_positive=0.3,
2029
+ max_positive=1.0,
2030
+ min_abs=0.75,
2031
+ max_abs=5.0,
2032
+ )
2033
+
2034
+ # shared_dim=0 means we share the dropout mask along the time axis
2035
+ self.out_proj = ActivationDropoutAndLinear(
2036
+ feedforward_dim,
2037
+ embed_dim,
2038
+ activation="SwooshL",
2039
+ dropout_p=dropout,
2040
+ dropout_shared_dim=0,
2041
+ bias=True,
2042
+ initial_scale=0.1,
2043
+ )
2044
+
2045
+ self.out_whiten = Whiten(
2046
+ num_groups=1,
2047
+ whitening_limit=_whitening_schedule(7.5),
2048
+ prob=(0.025, 0.25),
2049
+ grad_scale=0.01,
2050
+ )
2051
+
2052
+ def forward(self, x: Tensor):
2053
+ x = self.in_proj(x)
2054
+ x = self.hidden_balancer(x)
2055
+ # out_proj contains SwooshL activation, then dropout, then linear.
2056
+ x = self.out_proj(x)
2057
+ x = self.out_whiten(x)
2058
+ return x
2059
+
2060
+
2061
+ class NonlinAttention(nn.Module):
2062
+ """This is like the ConvolutionModule, but refactored so that we use multiplication by attention weights (borrowed
2063
+ from the attention module) in place of actual convolution. We also took out the second nonlinearity, the
2064
+ one after the attention mechanism.
2065
+
2066
+ Args:
2067
+ channels (int): The number of channels of conv layers.
2068
+ """
2069
+
2070
+ def __init__(
2071
+ self,
2072
+ channels: int,
2073
+ hidden_channels: int,
2074
+ ) -> None:
2075
+ super().__init__()
2076
+
2077
+ self.hidden_channels = hidden_channels
2078
+
2079
+ self.in_proj = nn.Linear(channels, hidden_channels * 3, bias=True)
2080
+
2081
+ # balancer that goes before the sigmoid. Have quite a large min_abs value, at 2.0,
2082
+ # because we noticed that well-trained instances of this module have abs-value before the sigmoid
2083
+ # starting from about 3, and poorly-trained instances of the module have smaller abs values
2084
+ # before the sigmoid.
2085
+ self.balancer = Balancer(
2086
+ hidden_channels,
2087
+ channel_dim=-1,
2088
+ min_positive=ScheduledFloat((0.0, 0.25), (20000.0, 0.05)),
2089
+ max_positive=ScheduledFloat((0.0, 0.75), (20000.0, 0.95)),
2090
+ min_abs=0.5,
2091
+ max_abs=5.0,
2092
+ )
2093
+ self.tanh = nn.Tanh()
2094
+
2095
+ self.identity1 = Identity() # for diagnostics.
2096
+ self.identity2 = Identity() # for diagnostics.
2097
+ self.identity3 = Identity() # for diagnostics.
2098
+
2099
+ self.out_proj = ScaledLinear(
2100
+ hidden_channels, channels, bias=True, initial_scale=0.05
2101
+ )
2102
+
2103
+ self.whiten1 = Whiten(
2104
+ num_groups=1,
2105
+ whitening_limit=_whitening_schedule(5.0),
2106
+ prob=(0.025, 0.25),
2107
+ grad_scale=0.01,
2108
+ )
2109
+
2110
+ self.whiten2 = Whiten(
2111
+ num_groups=1,
2112
+ whitening_limit=_whitening_schedule(5.0, ratio=3.0),
2113
+ prob=(0.025, 0.25),
2114
+ grad_scale=0.01,
2115
+ )
2116
+
2117
+ def forward(
2118
+ self,
2119
+ x: Tensor,
2120
+ attn_weights: Tensor,
2121
+ ) -> Tensor:
2122
+ """.
2123
+ Args:
2124
+ x: a Tensor of shape (seq_len, batch_size, num_channels)
2125
+ attn_weights: a Tensor of shape (num_heads, batch_size, seq_len, seq_len)
2126
+ Returns:
2127
+ a Tensor with the same shape as x
2128
+ """
2129
+ x = self.in_proj(x)
2130
+
2131
+ seq_len, batch_size, _ = x.shape
2132
+ hidden_channels = self.hidden_channels
2133
+
2134
+ s, x, y = x.chunk(3, dim=2)
2135
+
2136
+ # s will go through tanh.
2137
+
2138
+ s = self.balancer(s)
2139
+ s = self.tanh(s)
2140
+
2141
+ s = s.unsqueeze(-1).reshape(seq_len, batch_size, hidden_channels)
2142
+ x = self.whiten1(x)
2143
+ x = x * s
2144
+ x = self.identity1(x) # diagnostics only, it's the identity.
2145
+
2146
+ seq_len, batch_size, embed_dim = x.shape
2147
+ num_heads = attn_weights.shape[0]
2148
+ assert attn_weights.shape == (num_heads, batch_size, seq_len, seq_len)
2149
+
2150
+ x = x.reshape(seq_len, batch_size, num_heads, -1).permute(2, 1, 0, 3)
2151
+ # now x: (num_heads, batch_size, seq_len, head_dim)
2152
+ x = torch.matmul(attn_weights, x)
2153
+ # now x: (num_heads, batch_size, seq_len, head_dim)
2154
+ x = x.permute(2, 1, 0, 3).reshape(seq_len, batch_size, -1)
2155
+
2156
+ y = self.identity2(y)
2157
+ x = x * y
2158
+ x = self.identity3(x)
2159
+
2160
+ x = self.out_proj(x)
2161
+ x = self.whiten2(x)
2162
+ return x
2163
+
2164
+ def streaming_forward(
2165
+ self,
2166
+ x: Tensor,
2167
+ attn_weights: Tensor,
2168
+ cached_x: Tensor,
2169
+ left_context_len: int,
2170
+ ) -> Tuple[Tensor, Tensor]:
2171
+ """.
2172
+ Args:
2173
+ x: a Tensor of shape (seq_len, batch_size, num_channels)
2174
+ attn_weights: a Tensor of shape (num_heads, batch_size, seq_len, seq_len)
2175
+ cached_x: left context, a Tensor of shape
2176
+ (num_heads, batch_size, left_context_len, head_dim)
2177
+ left_context_len: number of left context frames.
2178
+ Returns:
2179
+ - a Tensor with the same shape as x
2180
+ - updated left context with same shape as cached_x
2181
+ """
2182
+ x = self.in_proj(x)
2183
+
2184
+ seq_len, batch_size, _ = x.shape
2185
+ hidden_channels = self.hidden_channels
2186
+
2187
+ s, x, y = x.chunk(3, dim=2)
2188
+
2189
+ # s will go through tanh.
2190
+ s = self.tanh(s)
2191
+
2192
+ s = s.unsqueeze(-1).reshape(seq_len, batch_size, hidden_channels)
2193
+ x = x * s
2194
+
2195
+ seq_len, batch_size, embed_dim = x.shape
2196
+ num_heads = attn_weights.shape[0]
2197
+ assert attn_weights.shape == (
2198
+ num_heads,
2199
+ batch_size,
2200
+ seq_len,
2201
+ left_context_len + seq_len,
2202
+ )
2203
+
2204
+ x = x.reshape(seq_len, batch_size, num_heads, -1).permute(2, 1, 0, 3)
2205
+ # now x: (num_heads, batch_size, seq_len, head_dim)
2206
+
2207
+ # Pad cached tensor
2208
+ assert cached_x.shape[2] == left_context_len, (
2209
+ cached_x.shape[2],
2210
+ left_context_len,
2211
+ )
2212
+ x_pad = torch.cat([cached_x, x], dim=2)
2213
+ # Update cached tensor
2214
+ cached_x = x_pad[:, :, -left_context_len:, :]
2215
+
2216
+ x = torch.matmul(attn_weights, x_pad)
2217
+ # now x: (num_heads, batch_size, seq_len, head_dim)
2218
+ x = x.permute(2, 1, 0, 3).reshape(seq_len, batch_size, -1)
2219
+
2220
+ x = x * y
2221
+
2222
+ x = self.out_proj(x)
2223
+ return x, cached_x
2224
+
2225
+
2226
+ class ConvolutionModule(nn.Module):
2227
+ """ConvolutionModule in Zipformer2 model.
2228
+ Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/zipformer/convolution.py
2229
+
2230
+ Args:
2231
+ channels (int): The number of channels of conv layers.
2232
+ kernel_size (int): Kernerl size of conv layers.
2233
+ bias (bool): Whether to use bias in conv layers (default=True).
2234
+
2235
+ """
2236
+
2237
+ def __init__(
2238
+ self,
2239
+ channels: int,
2240
+ kernel_size: int,
2241
+ causal: bool,
2242
+ ) -> None:
2243
+ """Construct a ConvolutionModule object."""
2244
+ super(ConvolutionModule, self).__init__()
2245
+ # kernerl_size should be a odd number for 'SAME' padding
2246
+ assert (kernel_size - 1) % 2 == 0
2247
+
2248
+ bottleneck_dim = channels
2249
+ self.causal = causal
2250
+
2251
+ self.in_proj = nn.Linear(
2252
+ channels,
2253
+ 2 * bottleneck_dim,
2254
+ )
2255
+ # the gradients on in_proj are a little noisy, likely to do with the
2256
+ # sigmoid in glu.
2257
+
2258
+ # after in_proj we put x through a gated linear unit (nn.functional.glu).
2259
+ # For most layers the normal rms value of channels of x seems to be in the range 1 to 4,
2260
+ # but sometimes, for some reason, for layer 0 the rms ends up being very large,
2261
+ # between 50 and 100 for different channels. This will cause very peaky and
2262
+ # sparse derivatives for the sigmoid gating function, which will tend to make
2263
+ # the loss function not learn effectively. (for most layers the average absolute values
2264
+ # are in the range 0.5..9.0, and the average p(x>0), i.e. positive proportion,
2265
+ # at the output of pointwise_conv1.output is around 0.35 to 0.45 for different
2266
+ # layers, which likely breaks down as 0.5 for the "linear" half and
2267
+ # 0.2 to 0.3 for the part that goes into the sigmoid. The idea is that if we
2268
+ # constrain the rms values to a reasonable range via a constraint of max_abs=10.0,
2269
+ # it will be in a better position to start learning something, i.e. to latch onto
2270
+ # the correct range.
2271
+ self.balancer1 = Balancer(
2272
+ bottleneck_dim,
2273
+ channel_dim=-1,
2274
+ min_positive=ScheduledFloat((0.0, 0.05), (8000.0, 0.025)),
2275
+ max_positive=1.0,
2276
+ min_abs=1.5,
2277
+ max_abs=ScheduledFloat((0.0, 5.0), (8000.0, 10.0), default=1.0),
2278
+ )
2279
+
2280
+ self.activation1 = Identity() # for diagnostics
2281
+
2282
+ self.sigmoid = nn.Sigmoid()
2283
+
2284
+ self.activation2 = Identity() # for diagnostics
2285
+
2286
+ assert kernel_size % 2 == 1
2287
+
2288
+ self.depthwise_conv = (
2289
+ ChunkCausalDepthwiseConv1d(channels=bottleneck_dim, kernel_size=kernel_size)
2290
+ if causal
2291
+ else nn.Conv1d(
2292
+ in_channels=bottleneck_dim,
2293
+ out_channels=bottleneck_dim,
2294
+ groups=bottleneck_dim,
2295
+ kernel_size=kernel_size,
2296
+ padding=kernel_size // 2,
2297
+ )
2298
+ )
2299
+
2300
+ self.balancer2 = Balancer(
2301
+ bottleneck_dim,
2302
+ channel_dim=1,
2303
+ min_positive=ScheduledFloat((0.0, 0.1), (8000.0, 0.05)),
2304
+ max_positive=1.0,
2305
+ min_abs=ScheduledFloat((0.0, 0.2), (20000.0, 0.5)),
2306
+ max_abs=10.0,
2307
+ )
2308
+
2309
+ self.whiten = Whiten(
2310
+ num_groups=1,
2311
+ whitening_limit=_whitening_schedule(7.5),
2312
+ prob=(0.025, 0.25),
2313
+ grad_scale=0.01,
2314
+ )
2315
+
2316
+ self.out_proj = ActivationDropoutAndLinear(
2317
+ bottleneck_dim,
2318
+ channels,
2319
+ activation="SwooshR",
2320
+ dropout_p=0.0,
2321
+ initial_scale=0.05,
2322
+ )
2323
+
2324
+ def forward(
2325
+ self,
2326
+ x: Tensor,
2327
+ src_key_padding_mask: Optional[Tensor] = None,
2328
+ chunk_size: int = -1,
2329
+ ) -> Tensor:
2330
+ """Compute convolution module.
2331
+
2332
+ Args:
2333
+ x: Input tensor (#time, batch, channels).
2334
+ src_key_padding_mask: the mask for the src keys per batch (optional):
2335
+ (batch, #time), contains True in masked positions.
2336
+
2337
+ Returns:
2338
+ Tensor: Output tensor (#time, batch, channels).
2339
+
2340
+ """
2341
+
2342
+ x = self.in_proj(x) # (time, batch, 2*channels)
2343
+
2344
+ x, s = x.chunk(2, dim=2)
2345
+ s = self.balancer1(s)
2346
+ s = self.sigmoid(s)
2347
+ x = self.activation1(x) # identity.
2348
+ x = x * s
2349
+ x = self.activation2(x) # identity
2350
+
2351
+ # (time, batch, channels)
2352
+
2353
+ # exchange the temporal dimension and the feature dimension
2354
+ x = x.permute(1, 2, 0) # (#batch, channels, time).
2355
+
2356
+ if src_key_padding_mask is not None:
2357
+ x = x.masked_fill(
2358
+ src_key_padding_mask.to(torch.bool).unsqueeze(1).expand_as(x), 0.0
2359
+ )
2360
+
2361
+ if (
2362
+ not torch.jit.is_scripting()
2363
+ and not torch.jit.is_tracing()
2364
+ and chunk_size >= 0
2365
+ ):
2366
+ # Not support exporting a model for simulated streaming decoding
2367
+ assert (
2368
+ self.causal
2369
+ ), "Must initialize model with causal=True if you use chunk_size"
2370
+ x = self.depthwise_conv(x, chunk_size=chunk_size)
2371
+ else:
2372
+ x = self.depthwise_conv(x)
2373
+
2374
+ x = self.balancer2(x)
2375
+ x = x.permute(2, 0, 1) # (time, batch, channels)
2376
+
2377
+ x = self.whiten(x) # (time, batch, channels)
2378
+ x = self.out_proj(x) # (time, batch, channels)
2379
+
2380
+ return x
2381
+
2382
+ def streaming_forward(
2383
+ self,
2384
+ x: Tensor,
2385
+ cache: Tensor,
2386
+ src_key_padding_mask: Tensor,
2387
+ ) -> Tuple[Tensor, Tensor]:
2388
+ """Compute convolution module in streaming forward mode.
2389
+
2390
+ Args:
2391
+ x: Input tensor (#time, batch, channels).
2392
+ cache: cached left context for depthwise_conv of shape
2393
+ (#batch, channels, left_pad)
2394
+ src_key_padding_mask: the mask for the src keys per batch (optional):
2395
+ (batch, #time), contains True in masked positions.
2396
+
2397
+ Returns:
2398
+ - Output tensor (#time, batch, channels).
2399
+ - Updated cache (#batch, channels, left_pad)
2400
+ """
2401
+
2402
+ x = self.in_proj(x) # (time, batch, 2*channels)
2403
+
2404
+ x, s = x.chunk(2, dim=2)
2405
+ s = self.sigmoid(s)
2406
+ x = x * s
2407
+ # (time, batch, channels)
2408
+
2409
+ # exchange the temporal dimension and the feature dimension
2410
+ x = x.permute(1, 2, 0) # (#batch, channels, time).
2411
+
2412
+ if src_key_padding_mask is not None:
2413
+ x = x.masked_fill(
2414
+ src_key_padding_mask.to(torch.bool).unsqueeze(1).expand_as(x), 0.0
2415
+ )
2416
+
2417
+ x, cache = self.depthwise_conv.streaming_forward(x, cache=cache)
2418
+
2419
+ x = x.permute(2, 0, 1) # (time, batch, channels)
2420
+
2421
+ x = self.out_proj(x) # (time, batch, channels)
2422
+
2423
+ return x, cache
2424
+
2425
+
2426
+ class ScalarMultiply(nn.Module):
2427
+ def __init__(self, scale: float):
2428
+ super().__init__()
2429
+ self.scale = scale
2430
+
2431
+ def forward(self, x):
2432
+ return x * self.scale
2433
+
2434
+
2435
+ def _test_zipformer_main(causal: bool = False):
2436
+ batch_size = 5
2437
+ seq_len = 20
2438
+ # Just make sure the forward pass runs.
2439
+
2440
+ c = Zipformer2(
2441
+ encoder_dim=(64, 96),
2442
+ encoder_unmasked_dim=(48, 64),
2443
+ num_heads=(4, 4),
2444
+ causal=causal,
2445
+ chunk_size=(4,) if causal else (-1,),
2446
+ left_context_frames=(64,),
2447
+ )
2448
+ batch_size = 5
2449
+ seq_len = 20
2450
+ # Just make sure the forward pass runs.
2451
+ f = c(
2452
+ torch.randn(seq_len, batch_size, 64),
2453
+ torch.full((batch_size,), seq_len, dtype=torch.int64),
2454
+ )
2455
+ f[0].sum().backward()
2456
+ c.eval()
2457
+ f = c(
2458
+ torch.randn(seq_len, batch_size, 64),
2459
+ torch.full((batch_size,), seq_len, dtype=torch.int64),
2460
+ )
2461
+ f # to remove flake8 warnings
2462
+
2463
+
2464
+ if __name__ == "__main__":
2465
+ logging.getLogger().setLevel(logging.INFO)
2466
+ torch.set_num_threads(1)
2467
+ torch.set_num_interop_threads(1)
2468
+ _test_zipformer_main(False)
2469
+ _test_zipformer_main(True)
wakeup_model/zipformer_encoder.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was developed by TCL Research Europe. For specific licensing terms, please refer to the
3
+ LICENSE file.
4
+
5
+ Zipformer utterance encoder — a drop-in alternative to the Whisper one.
6
+
7
+ Same contract as :class:`wakeup_model.encoder.UtteranceEncoder`: waveforms in,
8
+ one pooled vector per utterance out, with the same attention pooling on top so
9
+ everything downstream is unchanged.
10
+
11
+ Two things differ from Whisper and both matter here:
12
+
13
+ * **No fixed window.** Whisper pads every utterance to 30 s, so a 2 s turn costs
14
+ the same as a 30 s one and the pooling has to learn to ignore 28 s of silence.
15
+ Zipformer runs on the real length, which is a better fit for turn-level work.
16
+ * **Kaldi filterbank features**, not Whisper's log-mel — the pretrained ASR
17
+ weights expect them, so the frontend is part of the encoder rather than a
18
+ detail.
19
+
20
+ Pretrained weights come from the k2-fsa/icefall LibriSpeech recipes on the Hub.
21
+ The stack geometry is not stored with them, so each size is spelled out in
22
+ :data:`ZIPFORMER_SIZES`; a mismatch surfaces immediately as missing or
23
+ unexpected keys rather than as silently wrong numbers.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+
30
+ import torch
31
+ from torch import nn
32
+
33
+ from .config import WakeupModelConfig
34
+ from .encoder import AttentionPooling
35
+ from .zipformer import Conv2dSubsampling, Zipformer2, fbank
36
+
37
+ log = logging.getLogger(__name__)
38
+
39
+ #: Feature frontend, matching what the icefall recipes train with.
40
+ NUM_MEL_BINS = 80
41
+ FRAME_SHIFT_MS = 10.0
42
+ FRAME_LENGTH_MS = 25.0
43
+
44
+ #: Stack geometry per published size. `output_dim` is max(encoder_dim), which is
45
+ #: what Zipformer2 emits.
46
+ ZIPFORMER_SIZES = {
47
+ "small": {
48
+ "repo": "Zengwei/icefall-asr-librispeech-zipformer-small-cr-ctc-20241018",
49
+ "output_dim": 256,
50
+ "kwargs": {
51
+ "downsampling_factor": (1, 2, 4, 8, 4, 2),
52
+ "num_encoder_layers": (2, 2, 2, 2, 2, 2),
53
+ "encoder_dim": (192, 256, 256, 256, 256, 256),
54
+ "encoder_unmasked_dim": (192, 192, 192, 192, 192, 192),
55
+ "query_head_dim": (32,),
56
+ "pos_head_dim": (4,),
57
+ "value_head_dim": (12,),
58
+ "num_heads": (4, 4, 4, 8, 4, 4),
59
+ "feedforward_dim": (512, 768, 768, 768, 768, 768),
60
+ "cnn_module_kernel": (31, 31, 15, 15, 15, 31),
61
+ "pos_dim": 48,
62
+ },
63
+ "embed": {"layer1_channels": 8, "layer2_channels": 32, "layer3_channels": 128},
64
+ },
65
+ # Same geometry as "small", different pretraining: AudioSet tagging rather
66
+ # than LibriSpeech ASR. Device-directed detection mixes acoustic and
67
+ # semantic cues, so a general audio-event prior is a genuinely different
68
+ # starting point, not just another size.
69
+ "small-audioset": {
70
+ "repo": "marcoyang/icefall-audio-tagging-audioset-zipformer-small-2024-04-23",
71
+ "output_dim": 256,
72
+ "kwargs": {
73
+ "downsampling_factor": (1, 2, 4, 8, 4, 2),
74
+ "num_encoder_layers": (2, 2, 2, 2, 2, 2),
75
+ "encoder_dim": (192, 256, 256, 256, 256, 256),
76
+ "encoder_unmasked_dim": (192, 192, 192, 192, 192, 192),
77
+ "query_head_dim": (32,),
78
+ "pos_head_dim": (4,),
79
+ "value_head_dim": (12,),
80
+ "num_heads": (4, 4, 4, 8, 4, 4),
81
+ "feedforward_dim": (512, 768, 768, 768, 768, 768),
82
+ "cnn_module_kernel": (31, 31, 15, 15, 15, 31),
83
+ "pos_dim": 48,
84
+ },
85
+ "embed": {"layer1_channels": 8, "layer2_channels": 32, "layer3_channels": 128},
86
+ },
87
+ "medium": {
88
+ "repo": "Zengwei/icefall-asr-librispeech-zipformer-medium-cr-ctc-20241018",
89
+ "output_dim": 512,
90
+ "kwargs": {
91
+ "downsampling_factor": (1, 2, 4, 8, 4, 2),
92
+ "num_encoder_layers": (2, 2, 3, 4, 3, 2),
93
+ "encoder_dim": (192, 256, 384, 512, 384, 256),
94
+ "encoder_unmasked_dim": (192, 192, 256, 256, 256, 192),
95
+ "query_head_dim": (32,),
96
+ "pos_head_dim": (4,),
97
+ "value_head_dim": (12,),
98
+ "num_heads": (4, 4, 4, 8, 4, 4),
99
+ "feedforward_dim": (512, 768, 1024, 1536, 1024, 768),
100
+ "cnn_module_kernel": (31, 31, 15, 15, 15, 31),
101
+ "pos_dim": 48,
102
+ },
103
+ "embed": {"layer1_channels": 8, "layer2_channels": 32, "layer3_channels": 128},
104
+ },
105
+ }
106
+
107
+
108
+ class ZipformerUtteranceEncoder(nn.Module):
109
+ """Kaldi fbank → Conv2dSubsampling → Zipformer2 → attention pooling.
110
+
111
+ Args:
112
+ config: Model config; ``zipformer_size`` selects the stack and
113
+ ``encoder_output_dim`` must equal that stack's output width.
114
+
115
+ Raises:
116
+ ValueError: If the configured size is unknown, or the configured
117
+ output dim does not match it.
118
+ """
119
+
120
+ def __init__(self, config: WakeupModelConfig):
121
+ super().__init__()
122
+ size = config.zipformer_size
123
+ if size not in ZIPFORMER_SIZES:
124
+ raise ValueError(
125
+ f"zipformer_size={size!r}; known sizes: {sorted(ZIPFORMER_SIZES)}"
126
+ )
127
+ spec = ZIPFORMER_SIZES[size]
128
+ if config.encoder_output_dim != spec["output_dim"]:
129
+ raise ValueError(
130
+ f"zipformer-{size} emits {spec['output_dim']}-d, but "
131
+ f"model.encoder_output_dim is {config.encoder_output_dim}."
132
+ )
133
+
134
+ self.encoder_embed = Conv2dSubsampling(
135
+ in_channels=NUM_MEL_BINS,
136
+ out_channels=spec["kwargs"]["encoder_dim"][0],
137
+ **spec["embed"],
138
+ )
139
+ self.encoder = Zipformer2(
140
+ output_downsampling_factor=2, causal=False, **spec["kwargs"]
141
+ )
142
+ self.pooling = AttentionPooling(config.encoder_output_dim, config.pooling)
143
+ self.max_samples = int(config.max_utterance_seconds * 16000)
144
+ self.min_samples = int(config.min_utterance_seconds * 16000)
145
+
146
+ if config.zipformer_pretrained:
147
+ self._load_pretrained(spec["repo"])
148
+ self._apply_freeze(config.freeze_encoder, config.unfreeze_top_layers)
149
+
150
+ def _load_pretrained(self, repo: str) -> None:
151
+ """Load published ASR weights into the encoder.
152
+
153
+ Args:
154
+ repo: Hub repo holding ``exp/pretrained.pt``.
155
+
156
+ Returns:
157
+ None.
158
+
159
+ Raises:
160
+ RuntimeError: If the checkpoint does not match the stack geometry.
161
+ """
162
+ # pylint: disable=import-outside-toplevel
163
+ from huggingface_hub import hf_hub_download
164
+
165
+ path = hf_hub_download(repo, "exp/pretrained.pt")
166
+ state = torch.load(path, map_location="cpu", weights_only=False)["model"]
167
+ for prefix, module in (
168
+ ("encoder.", self.encoder),
169
+ ("encoder_embed.", self.encoder_embed),
170
+ ):
171
+ part = {
172
+ k[len(prefix) :]: v for k, v in state.items() if k.startswith(prefix)
173
+ }
174
+ missing, unexpected = module.load_state_dict(part, strict=False)
175
+ if missing or unexpected:
176
+ raise RuntimeError(
177
+ f"{repo} does not match this stack geometry under {prefix!r}: "
178
+ f"{len(missing)} missing, {len(unexpected)} unexpected "
179
+ f"(first: {(missing + unexpected)[:3]})"
180
+ )
181
+ log.info("Loaded pretrained Zipformer weights from %s", repo)
182
+
183
+ def _apply_freeze(self, freeze: bool, unfreeze_top: int) -> None:
184
+ """Freeze the encoder, optionally leaving the top layers trainable.
185
+
186
+ Args:
187
+ freeze: Whether to freeze at all.
188
+ unfreeze_top: How many of the last layers to leave trainable.
189
+
190
+ Returns:
191
+ None.
192
+ """
193
+ if not freeze:
194
+ return
195
+ for param in self.encoder.parameters():
196
+ param.requires_grad = False
197
+ for param in self.encoder_embed.parameters():
198
+ param.requires_grad = False
199
+ if unfreeze_top > 0:
200
+ self.unfreeze_top_layers(unfreeze_top)
201
+
202
+ def unfreeze_top_layers(self, n: int) -> None:
203
+ """Unfreeze the last ``n`` encoder layers.
204
+
205
+ Zipformer is a stack of stacks, so "the last n layers" is counted over
206
+ the flattened sequence of layers from the output end — the closest
207
+ equivalent to what this means for Whisper.
208
+
209
+ Args:
210
+ n: How many layers to unfreeze.
211
+
212
+ Returns:
213
+ None.
214
+ """
215
+ # Downsampled stacks wrap the real encoder one level down, so the
216
+ # layers have to be gathered rather than read off `.layers` directly.
217
+ layers = []
218
+ for stack in self.encoder.encoders:
219
+ inner = getattr(stack, "encoder", stack)
220
+ layers.extend(getattr(inner, "layers", []))
221
+ for layer in layers[-n:]:
222
+ for param in layer.parameters():
223
+ param.requires_grad = True
224
+
225
+ def forward( # pylint: disable=too-many-locals
226
+ self,
227
+ input_values: torch.Tensor, # (B, T_samples) 16 kHz
228
+ attention_mask: torch.Tensor = None, # (B, T_samples) bool, True = real
229
+ ) -> torch.Tensor: # (B, encoder_output_dim)
230
+ """Encode raw waveforms into one embedding each.
231
+
232
+ Args:
233
+ input_values: (B, T_samples) 16 kHz audio.
234
+ attention_mask: (B, T_samples) bool, True where a sample is real.
235
+ Used to give each utterance its true length, which is the point
236
+ of this encoder — unlike Whisper there is no fixed window.
237
+
238
+ Returns:
239
+ (B, encoder_output_dim) utterance embeddings.
240
+ """
241
+ device = input_values.device
242
+ lengths = (
243
+ attention_mask.sum(dim=1)
244
+ if attention_mask is not None
245
+ else torch.full(
246
+ (input_values.shape[0],), input_values.shape[1], device=device
247
+ )
248
+ )
249
+
250
+ # fbank is per-utterance: it takes (1, T) and Kaldi's framing is defined
251
+ # on a single signal, so batching here would mean framing the padding too.
252
+ feats = []
253
+ for wav, length in zip(input_values, lengths.tolist()):
254
+ # Truncate like Whisper does -- see config.max_utterance_seconds.
255
+ usable = wav[: min(int(length), self.max_samples)]
256
+ if usable.numel() < self.min_samples:
257
+ # Too short for the conv frontend, which would return zero
258
+ # frames -- see config.min_utterance_seconds.
259
+ usable = torch.nn.functional.pad(
260
+ usable, (0, self.min_samples - usable.numel())
261
+ )
262
+ usable = usable.unsqueeze(0).to(torch.float32)
263
+ feats.append(
264
+ fbank(
265
+ usable,
266
+ num_mel_bins=NUM_MEL_BINS,
267
+ frame_shift=FRAME_SHIFT_MS,
268
+ frame_length=FRAME_LENGTH_MS,
269
+ dither=0.0,
270
+ energy_floor=1e-10,
271
+ snip_edges=False,
272
+ sample_frequency=16000,
273
+ )
274
+ )
275
+
276
+ feat_lens = torch.tensor([f.shape[0] for f in feats], device=device)
277
+ padded = torch.zeros(
278
+ len(feats), int(feat_lens.max()), NUM_MEL_BINS, device=device
279
+ )
280
+ for i, f in enumerate(feats):
281
+ padded[i, : f.shape[0]] = f.to(device)
282
+
283
+ embedded, embedded_lens = self.encoder_embed(padded, feat_lens)
284
+ # Zipformer2 works time-first.
285
+ encoder_out, out_lens = self.encoder(
286
+ embedded.permute(1, 0, 2),
287
+ embedded_lens,
288
+ src_key_padding_mask=self._padding_mask(embedded_lens),
289
+ )
290
+ hidden = encoder_out.permute(1, 0, 2) # (B, T', D)
291
+
292
+ # AttentionPooling takes True == padding, so this is the complement of
293
+ # "valid frame".
294
+ frames = torch.arange(hidden.shape[1], device=device).unsqueeze(0)
295
+ return self.pooling(hidden, frames >= out_lens.unsqueeze(1))
296
+
297
+ @staticmethod
298
+ def _padding_mask(lengths: torch.Tensor) -> torch.Tensor:
299
+ """Build the True-is-padding mask Zipformer2 expects.
300
+
301
+ Args:
302
+ lengths: (B,) valid frame counts.
303
+
304
+ Returns:
305
+ (B, T) bool mask, True where a frame is padding.
306
+ """
307
+ frames = torch.arange(int(lengths.max()), device=lengths.device)
308
+ return frames.unsqueeze(0) >= lengths.unsqueeze(1)