SMS-Sajadi commited on
Commit
bae80e2
·
1 Parent(s): b51ffd7

First commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. README.md +38 -13
  3. app.py +992 -0
  4. asr_catalog.py +231 -0
  5. attention.py +243 -0
  6. conformer_hrbk.py +950 -0
  7. dashboard.py +676 -0
  8. dashboard_assets/CREDITS.md +17 -0
  9. dashboard_assets/FONT-LICENSE.txt +93 -0
  10. dashboard_assets/Vazirmatn.ttf +3 -0
  11. dashboard_assets/baradar_shahid.wav +3 -0
  12. dashboard_assets/contours.png +3 -0
  13. dashboard_assets/hotel.wav +3 -0
  14. dashboard_assets/polo.wav +3 -0
  15. dashboard_assets/studio.css +652 -0
  16. dashboard_assets/travel.wav +3 -0
  17. dashboard_assets/university_logo.png +3 -0
  18. icefall/__init__.py +77 -0
  19. icefall/ali.py +142 -0
  20. icefall/bpe_graph_compiler.py +94 -0
  21. icefall/byte_utils.py +312 -0
  22. icefall/char_graph_compiler.py +106 -0
  23. icefall/checkpoint.py +484 -0
  24. icefall/context_graph.py +599 -0
  25. icefall/ctc/.gitignore +2 -0
  26. icefall/ctc/README.md +17 -0
  27. icefall/ctc/__init__.py +7 -0
  28. icefall/ctc/prepare_lang.py +334 -0
  29. icefall/ctc/test_ctc_topo.py +140 -0
  30. icefall/ctc/test_prepare_lang.py +43 -0
  31. icefall/ctc/test_utils.py +87 -0
  32. icefall/ctc/topo.py +137 -0
  33. icefall/ctc/utils.py +52 -0
  34. icefall/dataset/__init__.py +0 -0
  35. icefall/dataset/datamodule.py +60 -0
  36. icefall/decode.py +2169 -0
  37. icefall/diagnostics.py +718 -0
  38. icefall/dist.py +68 -0
  39. icefall/env.py +120 -0
  40. icefall/err.py +47 -0
  41. icefall/graph_compiler.py +161 -0
  42. icefall/hooks.py +113 -0
  43. icefall/lexicon.py +270 -0
  44. icefall/lm_wrapper.py +254 -0
  45. icefall/mmi.py +222 -0
  46. icefall/mmi_graph_compiler.py +219 -0
  47. icefall/ngram_lm.py +171 -0
  48. icefall/otc_graph_compiler.py +246 -0
  49. icefall/otc_phone_graph_compiler.py +232 -0
  50. icefall/profiler.py +911 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.ttf filter=lfs diff=lfs merge=lfs -text
38
+ *.wav filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,38 @@
1
- ---
2
- title: ASR Platform
3
- emoji: 🏢
4
- colorFrom: purple
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.12'
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Persian ASR Test
3
+ emoji: 🚀
4
+ colorFrom: red
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 6.31.0
8
+ python_version: '3.12'
9
+ app_file: app.py
10
+ pinned: false
11
+ ---
12
+
13
+ # داشبورد بازشناسی گفتار فارسی
14
+
15
+ نسخهٔ بازطراحی‌شده بر پایهٔ [سورس Space](https://huggingface.co/spaces/SMS-Sajadi/Persian-ASR-Test/tree/b1c816d31bf1ea7c21413b52182cd65632bf3c47) است. برای استفاده در همان Space، محتوای پوشهٔ پروژه را در ریشهٔ مخزن قرار دهید تا `app.py` کنار همین README باشد. نسخهٔ SDK، وابستگی‌های پردازش صوت، فهرست مدل‌ها و سازوکار دریافت وزن از Google Drive از پروژهٔ موجود آمده‌اند. وزن مدل داخل بسته نیست.
16
+
17
+ ### پیش‌نمایش رابط بدون مدل
18
+
19
+ در یک محیط Python 3.12 و از پوشهٔ پروژه اجرا کنید.
20
+
21
+ ```sh
22
+ python -m pip install gradio==6.31.0
23
+ python preview.py
24
+ ```
25
+
26
+ نشانی محلی چاپ‌شده را باز کنید. در حالت **Demo** می‌توانید ضبط، بارگذاری، انتخاب نمونه، ویرایش و پخش صدا و باز کردن مشخصات فنی را بررسی کنید. دکمهٔ بازشناسی در این حالت غیرفعال است. برای ضبط مرورگر به مجوز میکروفون و نشانی localhost یا HTTPS نیاز دارد.
27
+
28
+ ### اجرای اصلی در Hugging Face Spaces
29
+
30
+ Space طبق تنظیمات بالای همین فایل، `app.py` را اجرا می‌کند. همانند نسخهٔ مبنا، در شروع برنامه و هنگام انتخاب مدل، فایل وزن در صورت نیاز دریافت و اعتبارسنجی می‌شود. دکمهٔ بازشناسی پس از آماده شدن صوت فعال است و تابع CPU پروژه را فراخوانی می‌کند. مسیر سازگاری ZeroGPU نیز ثبت می‌شود.
31
+
32
+ مدت صوت، زمان مدل و رمزگشایی، زمان پردازش کل، دو RTF، دستگاه، نرخ نمونه‌برداری و تعداد کانال از گزارش اجرای اصلی می‌آیند. «زمان پردازش کل» زمان فراخوانی pipeline روی سرور است. آماده‌سازی وزن، صف و زمان ارسال فایل در آن محاسبه نمی‌شوند. هر RTF نسبت زمان پردازش متناظر به مدت صوت پردازش‌شده است.
33
+
34
+ ### فایل‌های رابط
35
+
36
+ - `dashboard.py` چیدمان، رویدادهای سه تب و نمایش خروجی و عملکرد را تعریف می‌کند.
37
+ - `asr_catalog.py` فهرست مدل‌ها و تنظیمات مشترک اجرای اصلی و پیش‌نمایش را نگه می‌دارد. برای افزودن مدل، فهرست `MODELS` را در همین فایل ویرایش کنید.
38
+ - `dashboard_assets/` شامل سبک صفحه، فونت وزیرمتن، تصویر سربرگ و سه نمونهٔ واقعی گفتار فارسی است. منابع و مجوزها در [راهنمای دارایی‌ها](dashboard_assets/CREDITS.md) آمده‌اند.
app.py ADDED
@@ -0,0 +1,992 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #!/usr/bin/env python3
3
+ """Gradio app for private Hugging Face Hub-hosted Icefall Conformer CTC models."""
4
+
5
+ from __future__ import annotations
6
+
7
+ # Must be imported before torch/torchaudio for Hugging Face ZeroGPU.
8
+ import spaces
9
+
10
+ import gc
11
+ import logging
12
+ import os
13
+ import re
14
+ import threading
15
+ import time
16
+ from dataclasses import fields, replace
17
+ from pathlib import Path
18
+ from typing import Any, Optional, Sequence
19
+
20
+ import gradio as gr
21
+ import torch
22
+ import torchaudio
23
+
24
+ from pretrained_sms import ConformerPipeline
25
+
26
+
27
+ from asr_catalog import AppConfig, DEFAULT_MODEL_NAME, MODELS, MODEL_CACHE_DIR
28
+ from dashboard import build_dashboard, launch_dashboard
29
+
30
+ # =============================================================================
31
+ # 3. PRIVATE HUGGING FACE HUB DOWNLOADER
32
+ # =============================================================================
33
+
34
+
35
+ def get_huggingface_token() -> str:
36
+ """Read the Space secret without exposing it in logs or UI output.
37
+
38
+ Add a Space Secret named HF_TOKEN. A narrowly-scoped read token for the
39
+ private model repository is sufficient.
40
+ """
41
+ token = (
42
+ os.getenv("HF_TOKEN")
43
+ or os.getenv("HUGGINGFACE_HUB_TOKEN")
44
+ or os.getenv("HUGGING_FACE_HUB_TOKEN")
45
+ )
46
+ if not token:
47
+ raise RuntimeError(
48
+ "Hugging Face authentication token not found. Add a Space Secret "
49
+ "named HF_TOKEN containing a read-access token for your private "
50
+ "model repository, then restart the Space."
51
+ )
52
+ return token
53
+
54
+
55
+ def _safe_repo_filename(filename: str) -> str:
56
+ """Validate a repository-relative path; reject absolute paths/traversal."""
57
+ normalized = filename.replace("\\", "/").strip()
58
+ path = Path(normalized)
59
+ if not normalized or path.is_absolute() or ".." in path.parts:
60
+ raise ValueError(f"Invalid Hugging Face repository filename: {filename!r}")
61
+ return path.as_posix()
62
+
63
+
64
+ def download_huggingface_file(
65
+ repo_id: str,
66
+ filename: str,
67
+ local_dir: str | Path,
68
+ revision: str = "main",
69
+ force_download: bool = False,
70
+ ) -> Path:
71
+ """Download one file from a private Hugging Face model repository.
72
+
73
+ Hugging Face Hub handles file caching and revision metadata under local_dir.
74
+ The returned path is suitable for passing to the Icefall checkpoint loader.
75
+ """
76
+ if not repo_id or "/" not in repo_id:
77
+ raise ValueError(
78
+ "Each model in MODELS must have repo_id='owner/repository-name'."
79
+ )
80
+
81
+ filename = _safe_repo_filename(filename)
82
+ local_dir = Path(local_dir)
83
+ local_dir.mkdir(parents=True, exist_ok=True)
84
+
85
+ try:
86
+ from huggingface_hub import hf_hub_download
87
+ except ImportError as exc:
88
+ raise RuntimeError(
89
+ "huggingface_hub is not installed. Add it to requirements.txt."
90
+ ) from exc
91
+
92
+ token = get_huggingface_token()
93
+ logging.info(
94
+ "Fetching %s from private Hugging Face repo %s (revision=%s)",
95
+ filename,
96
+ repo_id,
97
+ revision,
98
+ )
99
+
100
+ try:
101
+ downloaded_path = hf_hub_download(
102
+ repo_id=repo_id,
103
+ filename=filename,
104
+ repo_type="model",
105
+ revision=revision,
106
+ token=token,
107
+ local_dir=str(local_dir),
108
+ force_download=force_download,
109
+ )
110
+ except Exception as exc:
111
+ # Do not include the token in the exception or logging output.
112
+ message = str(exc)
113
+ if "401" in message or "403" in message:
114
+ reason = (
115
+ "Access was denied. Check that HF_TOKEN is a valid read token "
116
+ "and that its fine-grained permissions include this private model repo."
117
+ )
118
+ elif "404" in message or "Repository Not Found" in message:
119
+ reason = (
120
+ "The model repository or requested file was not found. Check repo_id, "
121
+ "filename, revision, and access permissions. Private repos may also "
122
+ "appear as not found when the token lacks access."
123
+ )
124
+ else:
125
+ reason = f"Hugging Face Hub download failed: {message}"
126
+ raise RuntimeError(reason) from exc
127
+
128
+ downloaded_path = Path(downloaded_path)
129
+ if not downloaded_path.is_file() or downloaded_path.stat().st_size == 0:
130
+ raise RuntimeError(
131
+ f"Hugging Face Hub returned an invalid or empty file: {downloaded_path}"
132
+ )
133
+
134
+ logging.info(
135
+ "File available locally: %s (%.2f MB)",
136
+ downloaded_path,
137
+ downloaded_path.stat().st_size / (1024 * 1024),
138
+ )
139
+ return downloaded_path
140
+
141
+
142
+ # =============================================================================
143
+ # 4. AUDIO LOADING
144
+ # =============================================================================
145
+
146
+ def read_audio_files(
147
+ filenames: Sequence[str],
148
+ expected_sample_rate: int = 16000,
149
+ ) -> list[torch.Tensor]:
150
+
151
+ waves = []
152
+
153
+ for filename in filenames:
154
+
155
+ wave, sample_rate = torchaudio.load(str(filename))
156
+
157
+ # Convert stereo/multichannel to mono.
158
+ if wave.ndim == 2:
159
+ wave = wave.mean(dim=0)
160
+
161
+ elif wave.ndim != 1:
162
+ raise ValueError(
163
+ f"Unexpected audio shape: {wave.shape}"
164
+ )
165
+
166
+ # Resample if necessary.
167
+ if sample_rate != expected_sample_rate:
168
+ wave = torchaudio.functional.resample(
169
+ wave,
170
+ orig_freq=sample_rate,
171
+ new_freq=expected_sample_rate,
172
+ )
173
+
174
+ wave = wave.to(
175
+ dtype=torch.float32
176
+ ).contiguous()
177
+
178
+ if wave.numel() == 0:
179
+ raise ValueError(
180
+ f"Empty audio file: {filename}"
181
+ )
182
+
183
+ if not torch.isfinite(wave).all():
184
+ raise ValueError(
185
+ f"Audio contains NaN or Inf: {filename}"
186
+ )
187
+
188
+ waves.append(wave)
189
+
190
+ return waves
191
+
192
+
193
+ # =============================================================================
194
+ # 5. MODEL MANAGER AND INFERENCE
195
+ # =============================================================================
196
+
197
+ class ASRApplication:
198
+ """
199
+ Manages model downloads, initialization, model switching,
200
+ and transcription.
201
+
202
+ Only one model is kept in memory at a time.
203
+ Downloaded checkpoints are cached locally by Hugging Face Hub.
204
+ """
205
+
206
+ def __init__(
207
+ self,
208
+ base_config: AppConfig,
209
+ model_catalog: dict[str, dict[str, Any]],
210
+ ):
211
+
212
+ if not model_catalog:
213
+ raise ValueError(
214
+ "MODELS must contain at least one model."
215
+ )
216
+
217
+ self.base_config = base_config
218
+ self.model_catalog = model_catalog
219
+
220
+ self._lock = threading.RLock()
221
+
222
+ self.pipeline: Optional[ConformerPipeline] = None
223
+ self.config: Optional[AppConfig] = None
224
+
225
+ self.active_model_name: Optional[str] = None
226
+
227
+ self.device = "CPU (model not loaded)"
228
+ self.num_parameters = 0
229
+
230
+ # Exact (and estimated) parameter counts per model name, so the UI can
231
+ # show them before and after the pipeline is initialized.
232
+ self._param_counts: dict[str, int] = {}
233
+
234
+ if base_config.num_threads > 0:
235
+ torch.set_num_threads(base_config.num_threads)
236
+
237
+ @staticmethod
238
+ def _model_slug(model_name: str) -> str:
239
+ slug = re.sub(
240
+ r"[^a-zA-Z0-9._-]+",
241
+ "_",
242
+ model_name.strip(),
243
+ ).strip("_.")
244
+
245
+ return slug or "model"
246
+
247
+ def _model_local_dir(
248
+ self,
249
+ model_name: str,
250
+ ) -> Path:
251
+ return MODEL_CACHE_DIR / self._model_slug(model_name)
252
+
253
+ def _checkpoint_path(
254
+ self,
255
+ model_name: str,
256
+ entry: dict[str, Any],
257
+ ) -> Path:
258
+ filename = _safe_repo_filename(
259
+ str(entry.get("filename") or "checkpoint.pt")
260
+ )
261
+ return self._model_local_dir(model_name) / filename
262
+
263
+ def _download_model_assets(
264
+ self,
265
+ model_name: str,
266
+ entry: dict[str, Any],
267
+ ) -> tuple[
268
+ Path,
269
+ Optional[Path],
270
+ Optional[Path],
271
+ Optional[Path],
272
+ Optional[Path],
273
+ ]:
274
+ """Download checkpoint and optional decoding assets from one Hub repo.
275
+
276
+ Besides the checkpoint and tokens.txt, the optional HLG.pt, G.pt and
277
+ words.txt decoding assets (used when the decoding method is not
278
+ ctc-decoding) are fetched from the same repository when their
279
+ *_filename keys are present in the catalog entry.
280
+ """
281
+ repo_id = str(entry.get("repo_id", "")).strip()
282
+ revision = str(entry.get("revision", "main"))
283
+ local_dir = self._model_local_dir(model_name)
284
+
285
+ def _fetch_optional(filename_key: str) -> Optional[Path]:
286
+ filename = entry.get(filename_key)
287
+ if not filename:
288
+ return None
289
+ return download_huggingface_file(
290
+ repo_id=repo_id,
291
+ filename=str(filename),
292
+ local_dir=local_dir,
293
+ revision=revision,
294
+ )
295
+
296
+ checkpoint_path = download_huggingface_file(
297
+ repo_id=repo_id,
298
+ filename=str(entry.get("filename") or "checkpoint.pt"),
299
+ local_dir=local_dir,
300
+ revision=revision,
301
+ )
302
+
303
+ tokens_path = _fetch_optional("tokens_filename")
304
+ hlg_path = _fetch_optional("HLG_filename")
305
+ g_path = _fetch_optional("G_filename")
306
+ words_path = _fetch_optional("words_filename")
307
+
308
+ return (
309
+ checkpoint_path,
310
+ tokens_path,
311
+ hlg_path,
312
+ g_path,
313
+ words_path,
314
+ )
315
+
316
+ @staticmethod
317
+ def _estimate_parameter_count(checkpoint_path: Path) -> Optional[int]:
318
+ """Count parameters in a downloaded checkpoint without loading weights.
319
+
320
+ Tensor shapes are read on the meta device (or memory-mapped) so the
321
+ dashboard can display a parameter count before the pipeline exists.
322
+ The exact count measured on the loaded model replaces this value later.
323
+ Returns None when the checkpoint cannot be inspected.
324
+ """
325
+ try:
326
+ import torch
327
+ except ImportError:
328
+ return None
329
+
330
+ path = Path(checkpoint_path)
331
+ if not path.is_file():
332
+ return None
333
+
334
+ obj = None
335
+ for load_kwargs in (
336
+ dict(map_location="meta", weights_only=True),
337
+ dict(map_location="cpu", mmap=True, weights_only=True),
338
+ dict(map_location="cpu", weights_only=True),
339
+ dict(map_location="cpu"),
340
+ ):
341
+ try:
342
+ obj = torch.load(str(path), **load_kwargs)
343
+ break
344
+ except Exception:
345
+ continue
346
+
347
+ if obj is None:
348
+ return None
349
+
350
+ if isinstance(obj, dict):
351
+ for key in ("model", "state_dict", "weights", "model_state_dict"):
352
+ inner = obj.get(key)
353
+ if isinstance(inner, dict) and inner:
354
+ obj = inner
355
+ break
356
+
357
+ if not isinstance(obj, dict):
358
+ return None
359
+
360
+ total = 0
361
+ try:
362
+ for name, value in obj.items():
363
+ key_text = str(name).lower()
364
+ if any(token in key_text for token in (
365
+ "optimizer", "exp_avg", "exp_avg_sq", "scaler",
366
+ )):
367
+ continue
368
+ if torch.is_tensor(value):
369
+ total += value.numel()
370
+ except Exception:
371
+ return None
372
+
373
+ return total or None
374
+
375
+ def _model_config(
376
+ self,
377
+ model_name: str,
378
+ checkpoint_path: Path,
379
+ tokens_path: Optional[Path] = None,
380
+ hlg_path: Optional[Path] = None,
381
+ g_path: Optional[Path] = None,
382
+ words_path: Optional[Path] = None,
383
+ ) -> AppConfig:
384
+
385
+ entry = self.model_catalog[model_name]
386
+ overrides = dict(entry.get("config", {}))
387
+
388
+ valid_fields = {
389
+ field.name
390
+ for field in fields(AppConfig)
391
+ }
392
+
393
+ unknown = sorted(
394
+ set(overrides) - valid_fields
395
+ )
396
+
397
+ if unknown:
398
+ raise ValueError(
399
+ f"Unknown AppConfig overrides: {unknown}"
400
+ )
401
+
402
+ if "checkpoint" in overrides:
403
+ raise ValueError(
404
+ "Do not put checkpoint in model config."
405
+ )
406
+
407
+ if tokens_path is not None:
408
+ if "tokens" in overrides:
409
+ raise ValueError(
410
+ "Specify either config.tokens or tokens_filename, not both."
411
+ )
412
+ overrides["tokens"] = str(tokens_path)
413
+
414
+ if hlg_path is not None:
415
+ if "HLG" in overrides:
416
+ raise ValueError(
417
+ "Specify either config.HLG or HLG_filename, not both."
418
+ )
419
+ overrides["HLG"] = str(hlg_path)
420
+
421
+ if g_path is not None:
422
+ if "G" in overrides:
423
+ raise ValueError(
424
+ "Specify either config.G or G_filename, not both."
425
+ )
426
+ overrides["G"] = str(g_path)
427
+
428
+ if words_path is not None:
429
+ if "words_file" in overrides:
430
+ raise ValueError(
431
+ "Specify either config.words_file or words_filename, not both."
432
+ )
433
+ overrides["words_file"] = str(words_path)
434
+
435
+ config = replace(
436
+ self.base_config,
437
+ checkpoint=str(checkpoint_path),
438
+ **overrides,
439
+ )
440
+
441
+ config.validate_assets()
442
+
443
+ return config
444
+
445
+ def _release_active_pipeline(self):
446
+
447
+ old_pipeline = self.pipeline
448
+
449
+ self.pipeline = None
450
+ self.config = None
451
+ self.active_model_name = None
452
+
453
+ self.device = "CPU (model not loaded)"
454
+ self.num_parameters = 0
455
+
456
+ if old_pipeline is not None:
457
+ del old_pipeline
458
+
459
+ gc.collect()
460
+
461
+ # CPU-only inference does not require CUDA cache management.
462
+
463
+ def load_model(self, model_name: str) -> str:
464
+ """
465
+ Fetch and initialize the selected model from a private Hugging Face repo.
466
+
467
+ Hugging Face Hub manages the local cache and revision metadata.
468
+ """
469
+
470
+ with self._lock:
471
+
472
+ if model_name not in self.model_catalog:
473
+ raise ValueError(
474
+ f"Unknown model: {model_name}"
475
+ )
476
+
477
+ if (
478
+ self.active_model_name == model_name
479
+ and self.pipeline is not None
480
+ ):
481
+ return self.model_information()
482
+
483
+ entry = self.model_catalog[model_name]
484
+
485
+ (
486
+ checkpoint_path,
487
+ tokens_path,
488
+ hlg_path,
489
+ g_path,
490
+ words_path,
491
+ ) = self._download_model_assets(
492
+ model_name,
493
+ entry,
494
+ )
495
+
496
+ config = self._model_config(
497
+ model_name,
498
+ checkpoint_path,
499
+ tokens_path=tokens_path,
500
+ hlg_path=hlg_path,
501
+ g_path=g_path,
502
+ words_path=words_path,
503
+ )
504
+
505
+ params = config.pipeline_params()
506
+
507
+ # Keep only one model in memory.
508
+ self._release_active_pipeline()
509
+
510
+ logging.info(
511
+ "Loading model '%s' on %s",
512
+ model_name,
513
+ params.device,
514
+ )
515
+
516
+ try:
517
+ pipeline = ConformerPipeline(
518
+ sound_reader=lambda paths, sr=config.sample_rate:
519
+ read_audio_files(
520
+ paths,
521
+ expected_sample_rate=sr,
522
+ ),
523
+ model_path=params.checkpoint,
524
+ params=params,
525
+ )
526
+
527
+ except Exception:
528
+ logging.exception(
529
+ "Failed to initialize model '%s'",
530
+ model_name,
531
+ )
532
+ self._release_active_pipeline()
533
+ raise
534
+
535
+ self.pipeline = pipeline
536
+ self.config = config
537
+ self.active_model_name = model_name
538
+
539
+ self.device = str(pipeline.device)
540
+
541
+ self.num_parameters = sum(
542
+ parameter.numel()
543
+ for parameter in pipeline.model.parameters()
544
+ )
545
+
546
+ # Replace the checkpoint-based estimate with the exact count.
547
+ self._param_counts[model_name] = self.num_parameters
548
+
549
+ logging.info(
550
+ "Model '%s' ready: %.3f M parameters",
551
+ model_name,
552
+ self.num_parameters / 1e6,
553
+ )
554
+
555
+ return self.model_information()
556
+
557
+ def model_information(
558
+ self,
559
+ model_name: Optional[str] = None,
560
+ ) -> str:
561
+ """Describe the active model or a selected model before loading."""
562
+
563
+ if model_name is None:
564
+ model_name = self.active_model_name
565
+ cfg = self.config
566
+ loaded = (
567
+ self.pipeline is not None
568
+ and cfg is not None
569
+ )
570
+
571
+ else:
572
+ if model_name not in self.model_catalog:
573
+ return f"Unknown model: {model_name}"
574
+
575
+ entry = self.model_catalog[model_name]
576
+ checkpoint_path = self._checkpoint_path(
577
+ model_name,
578
+ entry,
579
+ )
580
+
581
+ overrides = dict(entry.get("config", {}))
582
+
583
+ cfg = replace(
584
+ self.base_config,
585
+ checkpoint=str(checkpoint_path),
586
+ **overrides,
587
+ )
588
+
589
+ loaded = (
590
+ self.active_model_name == model_name
591
+ and self.pipeline is not None
592
+ )
593
+
594
+ if model_name is None or cfg is None:
595
+ return "No model is currently loaded."
596
+
597
+ description = self.model_catalog[
598
+ model_name
599
+ ].get("description", "")
600
+
601
+ cached = self._param_counts.get(model_name)
602
+
603
+ if cached:
604
+ parameter_text = f"{cached / 1e6:.3f} M"
605
+ elif loaded:
606
+ parameter_text = f"{self.num_parameters / 1e6:.3f} M"
607
+ else:
608
+ parameter_text = "Calculated when the model is initialized"
609
+
610
+ device_text = self.device if loaded else "CPU"
611
+
612
+ lines = [
613
+ f"**Selected model:** {model_name}"
614
+ ]
615
+
616
+ if description:
617
+ lines.append(
618
+ f"**Description:** {description}"
619
+ )
620
+
621
+ lines.extend([
622
+ f"**Parameters:** {parameter_text}",
623
+ f"**Encoder dimension:** {cfg.encoder_dim}",
624
+ f"**Attention heads:** {cfg.nhead}",
625
+ f"**Recurrent encoder:** {'Yes' if cfg.use_recurrence else 'No'}",
626
+ ])
627
+
628
+ if cfg.use_recurrence:
629
+ loops = (
630
+ cfg.max_loops
631
+ if cfg.max_loops > 0
632
+ else cfg.num_loops
633
+ )
634
+
635
+ lines.append(
636
+ f"**Loops:** {loops}"
637
+ )
638
+
639
+ lines.extend([
640
+ f"**CTC feedback:** {'Yes' if cfg.use_ctc_feedback else 'No'}",
641
+ f"**Decoder:** k2 ({cfg.method})",
642
+ f"**Device:** {device_text}",
643
+ ])
644
+
645
+ return "\n\n".join(lines)
646
+
647
+ def select_model(self, model_name: str):
648
+ """Download and validate the selected Hub checkpoint without loading the model."""
649
+
650
+ try:
651
+
652
+ if model_name not in self.model_catalog:
653
+ raise ValueError(
654
+ f"Unknown model: {model_name}"
655
+ )
656
+
657
+ entry = self.model_catalog[model_name]
658
+
659
+ (
660
+ checkpoint_path,
661
+ tokens_path,
662
+ hlg_path,
663
+ g_path,
664
+ words_path,
665
+ ) = self._download_model_assets(
666
+ model_name,
667
+ entry,
668
+ )
669
+
670
+ self._model_config(
671
+ model_name,
672
+ checkpoint_path,
673
+ tokens_path=tokens_path,
674
+ hlg_path=hlg_path,
675
+ g_path=g_path,
676
+ words_path=words_path,
677
+ )
678
+
679
+ # Make the parameter count visible in the UI before the model is
680
+ # ever initialized: shapes are read straight from the checkpoint.
681
+ if model_name not in self._param_counts:
682
+ estimated = self._estimate_parameter_count(checkpoint_path)
683
+ if estimated:
684
+ self._param_counts[model_name] = estimated
685
+ logging.info(
686
+ "Estimated %.3f M parameters for '%s'",
687
+ estimated / 1e6,
688
+ model_name,
689
+ )
690
+
691
+ already_loaded = (
692
+ self.active_model_name == model_name
693
+ and self.pipeline is not None
694
+ )
695
+
696
+ if already_loaded:
697
+ status = f"Model ready: **{model_name}**"
698
+ else:
699
+ status = (
700
+ f"Model files cached for **{model_name}**. "
701
+ "It will be initialized when you run recognition."
702
+ )
703
+
704
+ return status, self.model_information(model_name)
705
+
706
+ except Exception as exc:
707
+ logging.exception(
708
+ "Could not select model '%s'",
709
+ model_name,
710
+ )
711
+
712
+ return (
713
+ f"**Model selection failed:** {exc}",
714
+ self.model_information(),
715
+ )
716
+
717
+ def _validate_audio(
718
+ self,
719
+ audio_path: str,
720
+ ) -> tuple[float, int, int]:
721
+
722
+ if (
723
+ not audio_path
724
+ or not Path(audio_path).is_file()
725
+ ):
726
+ raise gr.Error(
727
+ "Please upload an audio file or record your voice."
728
+ )
729
+
730
+ # SoundFile first, torchaudio fallback.
731
+ try:
732
+ import soundfile as sf
733
+
734
+ info = sf.info(audio_path)
735
+
736
+ sample_rate = int(info.samplerate)
737
+ num_frames = int(info.frames)
738
+ num_channels = int(info.channels)
739
+
740
+ except Exception as soundfile_error:
741
+ logging.debug(
742
+ "SoundFile metadata read failed: %s",
743
+ soundfile_error,
744
+ )
745
+
746
+ try:
747
+ waveform, sample_rate = torchaudio.load(
748
+ audio_path
749
+ )
750
+
751
+ sample_rate = int(sample_rate)
752
+
753
+ if waveform.ndim == 1:
754
+ num_channels = 1
755
+ num_frames = int(waveform.shape[0])
756
+
757
+ elif waveform.ndim == 2:
758
+ num_channels = int(waveform.shape[0])
759
+ num_frames = int(waveform.shape[1])
760
+
761
+ else:
762
+ raise ValueError(
763
+ f"Unexpected audio shape: {tuple(waveform.shape)}"
764
+ )
765
+
766
+ del waveform
767
+
768
+ except Exception as audio_error:
769
+ raise gr.Error(
770
+ "Unable to read audio. "
771
+ f"SoundFile: {soundfile_error}; "
772
+ f"torchaudio: {audio_error}"
773
+ ) from audio_error
774
+
775
+ if (
776
+ sample_rate <= 0
777
+ or num_frames <= 0
778
+ or num_channels <= 0
779
+ ):
780
+ raise gr.Error(
781
+ "The audio file is empty or invalid."
782
+ )
783
+
784
+ duration = num_frames / sample_rate
785
+
786
+ if duration > self.config.max_audio_seconds:
787
+ raise gr.Error(
788
+ f"Audio duration is {duration:.1f} seconds. "
789
+ f"Maximum allowed duration is "
790
+ f"{self.config.max_audio_seconds:.0f} seconds."
791
+ )
792
+
793
+ return duration, sample_rate, num_channels
794
+
795
+ def transcribe(
796
+ self,
797
+ audio_path: Optional[str],
798
+ model_name: str,
799
+ ):
800
+
801
+ if audio_path is None:
802
+ raise gr.Error(
803
+ "Upload an audio file or record your voice first."
804
+ )
805
+
806
+ with self._lock:
807
+ try:
808
+
809
+ if (
810
+ self.active_model_name != model_name
811
+ or self.pipeline is None
812
+ ):
813
+ self.load_model(model_name)
814
+
815
+ if (
816
+ self.pipeline is None
817
+ or self.config is None
818
+ ):
819
+ raise RuntimeError(
820
+ "The selected model is not loaded."
821
+ )
822
+
823
+ (
824
+ audio_duration,
825
+ original_sr,
826
+ channels,
827
+ ) = self._validate_audio(audio_path)
828
+
829
+ previous_duration = (
830
+ self.pipeline.total_audio_duration
831
+ )
832
+
833
+ wall_start = time.perf_counter()
834
+
835
+ hypotheses = self.pipeline(
836
+ [audio_path]
837
+ )
838
+
839
+ wall_elapsed = (
840
+ time.perf_counter() - wall_start
841
+ )
842
+
843
+ measured_audio_duration = (
844
+ self.pipeline.total_audio_duration
845
+ - previous_duration
846
+ )
847
+
848
+ except gr.Error:
849
+ raise
850
+
851
+ except Exception as exc:
852
+ logging.exception("Transcription failed")
853
+
854
+ raise gr.Error(
855
+ f"Transcription failed: {exc}"
856
+ ) from exc
857
+
858
+ transcription = (
859
+ hypotheses[0] if hypotheses else ""
860
+ )
861
+
862
+ duration_for_rtf = (
863
+ measured_audio_duration or audio_duration
864
+ )
865
+
866
+ end_to_end_rtf = (
867
+ wall_elapsed / max(duration_for_rtf, 1e-8)
868
+ )
869
+
870
+ performance = (
871
+ f"Model: {model_name}\n"
872
+ f"Audio duration: {audio_duration:.2f} s\n"
873
+ f"Original sample rate: {original_sr} Hz\n"
874
+ f"Channels: {channels}\n"
875
+ f"End-to-end processing: {wall_elapsed:.3f} s\n"
876
+ f"End-to-end RTF: {end_to_end_rtf:.4f}\n"
877
+ f"Device: {self.device}"
878
+ )
879
+
880
+ return transcription, performance
881
+
882
+
883
+ # =============================================================================
884
+ # 6. SHARED AND SEPARATE INFERENCE HANDLERS
885
+ # =============================================================================
886
+
887
+ ASR_APP: Optional[ASRApplication] = None
888
+
889
+
890
+ def _run_transcription(
891
+ audio_path: Optional[str],
892
+ model_name: str,
893
+ ):
894
+ """Shared implementation for CPU and GPU entry points."""
895
+
896
+ if ASR_APP is None:
897
+ raise gr.Error(
898
+ "The ASR application has not been initialized."
899
+ )
900
+
901
+ return ASR_APP.transcribe(
902
+ audio_path,
903
+ model_name,
904
+ )
905
+
906
+
907
+ def transcribe_cpu_handler(
908
+ audio_path: Optional[str],
909
+ model_name: str,
910
+ ):
911
+ """Actual inference handler. Runs exclusively on CPU."""
912
+
913
+ return _run_transcription(
914
+ audio_path,
915
+ model_name,
916
+ )
917
+
918
+
919
+ @spaces.GPU(duration=60)
920
+ def transcribe_gpu_handler(
921
+ audio_path: Optional[str],
922
+ model_name: str,
923
+ ):
924
+ """GPU-decorated entry point retained for ZeroGPU compatibility."""
925
+
926
+ return _run_transcription(
927
+ audio_path,
928
+ model_name,
929
+ )
930
+
931
+
932
+ # =============================================================================
933
+ # 7. GRADIO INTERFACE
934
+ # =============================================================================
935
+
936
+ def build_demo(asr: ASRApplication) -> gr.Blocks:
937
+ return build_dashboard(
938
+ asr.model_catalog,
939
+ asr.base_config,
940
+ select_model=asr.select_model,
941
+ model_info=asr.model_information,
942
+ transcribe=transcribe_cpu_handler,
943
+ gpu_handler=transcribe_gpu_handler,
944
+ )
945
+
946
+
947
+ # =============================================================================
948
+ # 8. ENTRY POINT
949
+ # =============================================================================
950
+
951
+ def main():
952
+
953
+ global ASR_APP
954
+
955
+ logging.basicConfig(
956
+ level=logging.INFO,
957
+ format=(
958
+ "%(asctime)s %(levelname)s "
959
+ "[%(filename)s:%(lineno)d] %(message)s"
960
+ ),
961
+ )
962
+
963
+ base_config = AppConfig()
964
+
965
+ ASR_APP = ASRApplication(
966
+ base_config=base_config,
967
+ model_catalog=MODELS,
968
+ )
969
+
970
+ logging.info(
971
+ "Preparing default model: %s",
972
+ DEFAULT_MODEL_NAME,
973
+ )
974
+
975
+ # Download and validate the checkpoint at startup.
976
+ # Actual CPU model initialization is deferred until transcription.
977
+ status, _ = ASR_APP.select_model(
978
+ DEFAULT_MODEL_NAME
979
+ )
980
+
981
+ logging.info(
982
+ "Default model setup: %s",
983
+ status,
984
+ )
985
+
986
+ demo = build_demo(ASR_APP)
987
+
988
+ launch_dashboard(demo)
989
+
990
+
991
+ if __name__ == "__main__":
992
+ main()
asr_catalog.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private Hugging Face Hub model catalogue and shared ASR configuration."""
2
+ from __future__ import annotations
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ from typing import Any
7
+
8
+ # =============================================================================
9
+ # 1. MODEL CATALOG -- EDIT THIS SECTION
10
+ # =============================================================================
11
+
12
+ MODELS: dict[str, dict[str, Any]] = {
13
+ "Conformer CTC": {
14
+ "repo_id": "SMS-Sajadi/Conformer-CTC",
15
+ "revision": "main",
16
+ "filename": "epoch-50.pt",
17
+ # Optional: place tokens.txt in the same private model repo and uncomment.
18
+ # "tokens_filename": "tokens.txt",
19
+ # Optional HLG decoding assets. These are only used when config.method
20
+ # is NOT "ctc-decoding". Upload HLG.pt / G.pt / words.txt into the same
21
+ # private model repository, then uncomment and adjust the paths
22
+ # (repo-relative paths such as "data/lang/HLG.pt" are also allowed).
23
+ "HLG_filename": "HLG.pt",
24
+ "G_filename": "G.pt",
25
+ "words_filename": "words.txt",
26
+ "description": "Conformer CTC",
27
+ "config": {
28
+ "encoder_dim": 512,
29
+ "nhead": 8,
30
+ "dim_feedforward": 2048,
31
+ "num_encoder_layers": 24,
32
+ "num_decoder_layers": 0,
33
+ "cnn_module_kernel": 15,
34
+ },
35
+ },
36
+
37
+ # Add additional models here.
38
+ #
39
+ # "Another Conformer": {
40
+ # "repo_id": "YOUR_USERNAME/YOUR_PRIVATE_MODEL_REPO",
41
+ # "revision": "main",
42
+ # "filename": "another_model.pt",
43
+ # "description": "Another CTC model",
44
+ # "config": {
45
+ # "encoder_dim": 256,
46
+ # "nhead": 8,
47
+ # "use_recurrence": False,
48
+ # "num_encoder_layers": 12,
49
+ # },
50
+ # },
51
+ }
52
+
53
+ DEFAULT_MODEL_NAME = next(iter(MODELS))
54
+
55
+ MODEL_CACHE_DIR = Path(__file__).resolve().parent / "models"
56
+
57
+
58
+ # =============================================================================
59
+ # 2. CONFIGURATION
60
+ # =============================================================================
61
+
62
+ def _project_path(value: str | Path) -> str:
63
+ path = Path(value).expanduser()
64
+
65
+ if not path.is_absolute():
66
+ path = Path(__file__).resolve().parent / path
67
+
68
+ return str(path.resolve())
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class AppConfig:
73
+
74
+ checkpoint: str = ""
75
+ bpe_model: str = "./model_tokens/bpe.model"
76
+ tokens: str = "./model_tokens/tokens.txt"
77
+
78
+ # k2 HLG decoding assets. Leave empty for "ctc-decoding". When the
79
+ # decoding method uses HLG, these files are downloaded from the model
80
+ # repository and their local paths are filled in automatically, so the
81
+ # names match what ConformerPipeline expects in params.
82
+ HLG: str = ""
83
+ G: str = ""
84
+ words_file: str = ""
85
+
86
+ # Runtime -- CPU ONLY
87
+ device: str = "cpu"
88
+ num_threads: int = 2
89
+ max_audio_seconds: float = 60.0
90
+
91
+ # Acoustic frontend
92
+ sample_rate: int = 16000
93
+ feature_dim: int = 80
94
+ subsampling_factor: int = 4
95
+
96
+ # Model architecture
97
+ num_classes: int = 500
98
+ encoder_dim: int = 256
99
+ nhead: int = 8
100
+ dim_feedforward: int = 2048
101
+ num_encoder_layers: int = 12
102
+ num_decoder_layers: int = 0
103
+ cnn_module_kernel: int = 15
104
+
105
+ # Recurrent Conformer
106
+ use_recurrence: bool = False
107
+ num_loops: int = 4
108
+ num_core_layers: int = 2
109
+ num_prelude_layers: int = 2
110
+ num_coda_layers: int = 2
111
+ use_loop_embed: bool = True
112
+ debug_shapes: bool = False
113
+
114
+ # CTC feedback
115
+ use_ctc_feedback: bool = False
116
+ ctc_feedback_init: str = "learned-randn"
117
+ ctc_feedback_init_std: float = 0.02
118
+ ctc_feedback_detach: bool = True
119
+ ctc_feedback_scale: float = 1.0
120
+ ctc_feedback_fusion_mode: str = "full"
121
+
122
+ use_aux_ctc: bool = False
123
+ use_coda_for_intermediate_loops: bool = False
124
+ max_loops: int = 0
125
+
126
+ # CTC decoding
127
+ # method: str = "ctc-decoding"
128
+ method: str = "whole-lattice-rescoring"
129
+ search_beam: float = 20.0
130
+ output_beam: float = 8.0
131
+ min_active_states: int = 30
132
+ max_active_states: int = 10000
133
+ use_double_scores: bool = True
134
+ use_supervision: bool = True
135
+
136
+ # HLG / n-gram LM decoding hyper-parameters
137
+ # (defaults mirror the argparse defaults in pretrained_sms.py)
138
+ ngram_lm_scale: float = 1.3
139
+ # -0.2,0.4,0.6,0.8,1.0,1.2,1.5,2.0
140
+
141
+
142
+ def pipeline_params(self) -> SimpleNamespace:
143
+ values = dict(vars(self))
144
+
145
+ values["checkpoint"] = _project_path(self.checkpoint)
146
+ values["bpe_model"] = _project_path(self.bpe_model)
147
+ values["tokens"] = _project_path(self.tokens)
148
+
149
+ # Optional HLG decoding assets: an empty string means "not provided".
150
+ values["HLG"] = _project_path(self.HLG) if self.HLG else ""
151
+ values["G"] = _project_path(self.G) if self.G else ""
152
+ values["words_file"] = (
153
+ _project_path(self.words_file) if self.words_file else ""
154
+ )
155
+
156
+ # Always force CPU, even if a model config specifies CUDA.
157
+ values["device"] = "cpu"
158
+
159
+ return SimpleNamespace(**values)
160
+
161
+ def validate_assets(self):
162
+ checkpoint_path = Path(_project_path(self.checkpoint))
163
+ bpe_model_path = Path(_project_path(self.bpe_model))
164
+ tokens_path = Path(_project_path(self.tokens))
165
+
166
+ if not checkpoint_path.is_file():
167
+ raise FileNotFoundError(
168
+ f"Checkpoint not found: {checkpoint_path}"
169
+ )
170
+
171
+ if not bpe_model_path.is_file():
172
+ raise FileNotFoundError(
173
+ f"bpe model not found: {bpe_model_path}"
174
+ )
175
+
176
+ if not tokens_path.is_file():
177
+ raise FileNotFoundError(
178
+ f"Token table not found: {tokens_path}"
179
+ )
180
+
181
+ # Optional HLG decoding assets: validate them when configured, and
182
+ # require them when the selected decoding method needs them.
183
+ hlg_path = Path(_project_path(self.HLG)) if self.HLG else None
184
+ g_path = Path(_project_path(self.G)) if self.G else None
185
+ words_path = (
186
+ Path(_project_path(self.words_file)) if self.words_file else None
187
+ )
188
+
189
+ if hlg_path is not None and not hlg_path.is_file():
190
+ raise FileNotFoundError(
191
+ f"HLG graph not found: {hlg_path}"
192
+ )
193
+
194
+ if g_path is not None and not g_path.is_file():
195
+ raise FileNotFoundError(
196
+ f"G (LM) graph not found: {g_path}"
197
+ )
198
+
199
+ if words_path is not None and not words_path.is_file():
200
+ raise FileNotFoundError(
201
+ f"Word symbol table not found: {words_path}"
202
+ )
203
+
204
+ if self.method != "ctc-decoding":
205
+ missing = []
206
+
207
+ if hlg_path is None:
208
+ missing.append(
209
+ "HLG.pt (set HLG_filename in the model entry)"
210
+ )
211
+
212
+ if words_path is None:
213
+ missing.append(
214
+ "words.txt (set words_filename in the model entry)"
215
+ )
216
+
217
+ if (
218
+ self.method in ("whole-lattice-rescoring", "attention-decoder")
219
+ and g_path is None
220
+ ):
221
+ missing.append(
222
+ "G.pt (set G_filename in the model entry)"
223
+ )
224
+
225
+ if missing:
226
+ raise FileNotFoundError(
227
+ f"Decoding method '{self.method}' is missing assets: "
228
+ + ", ".join(missing)
229
+ )
230
+
231
+
attention.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Xiaomi Corp. (author: Quandong Wang)
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 Optional, Tuple
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from scaling import ScaledLinear
22
+ from torch import Tensor
23
+ from torch.nn.init import xavier_normal_
24
+
25
+
26
+ class MultiheadAttention(nn.Module):
27
+ r"""Allows the model to jointly attend to information
28
+ from different representation subspaces.
29
+ See `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
30
+
31
+ .. math::
32
+ \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
33
+
34
+ where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
35
+
36
+ Args:
37
+ embed_dim: Total dimension of the model.
38
+ num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
39
+ across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
40
+ dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
41
+ bias: If specified, adds bias to input / output projection layers. Default: ``True``.
42
+ add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
43
+ add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
44
+ Default: ``False``.
45
+ kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
46
+ vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
47
+ batch_first: If ``True``, then the input and output tensors are provided
48
+ as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
49
+
50
+ Examples::
51
+
52
+ >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
53
+ >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
54
+ """
55
+ __constants__ = ["batch_first"]
56
+ bias_k: Optional[torch.Tensor]
57
+ bias_v: Optional[torch.Tensor]
58
+
59
+ def __init__(
60
+ self,
61
+ embed_dim,
62
+ num_heads,
63
+ dropout=0.0,
64
+ bias=True,
65
+ add_bias_kv=False,
66
+ add_zero_attn=False,
67
+ kdim=None,
68
+ vdim=None,
69
+ batch_first=False,
70
+ device=None,
71
+ dtype=None,
72
+ ) -> None:
73
+ factory_kwargs = {"device": device, "dtype": dtype}
74
+ super(MultiheadAttention, self).__init__()
75
+ self.embed_dim = embed_dim
76
+ self.kdim = kdim if kdim is not None else embed_dim
77
+ self.vdim = vdim if vdim is not None else embed_dim
78
+ self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
79
+
80
+ self.num_heads = num_heads
81
+ self.dropout = dropout
82
+ self.batch_first = batch_first
83
+ self.head_dim = embed_dim // num_heads
84
+ assert (
85
+ self.head_dim * num_heads == self.embed_dim
86
+ ), "embed_dim must be divisible by num_heads"
87
+
88
+ if self._qkv_same_embed_dim is False:
89
+ self.q_proj_weight = ScaledLinear(embed_dim, embed_dim, bias=bias)
90
+ self.k_proj_weight = ScaledLinear(self.kdim, embed_dim, bias=bias)
91
+ self.v_proj_weight = ScaledLinear(self.vdim, embed_dim, bias=bias)
92
+ self.register_parameter("in_proj_weight", None)
93
+ else:
94
+ self.in_proj_weight = ScaledLinear(embed_dim, 3 * embed_dim, bias=bias)
95
+ self.register_parameter("q_proj_weight", None)
96
+ self.register_parameter("k_proj_weight", None)
97
+ self.register_parameter("v_proj_weight", None)
98
+
99
+ if not bias:
100
+ self.register_parameter("in_proj_bias", None)
101
+
102
+ self.out_proj = ScaledLinear(embed_dim, embed_dim, bias=bias)
103
+
104
+ if add_bias_kv:
105
+ self.bias_k = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
106
+ self.bias_v = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
107
+ else:
108
+ self.bias_k = self.bias_v = None
109
+
110
+ self.add_zero_attn = add_zero_attn
111
+
112
+ self._reset_parameters()
113
+
114
+ def _reset_parameters(self):
115
+ if self.bias_k is not None:
116
+ xavier_normal_(self.bias_k)
117
+ if self.bias_v is not None:
118
+ xavier_normal_(self.bias_v)
119
+
120
+ def __setstate__(self, state):
121
+ # Support loading old MultiheadAttention checkpoints generated by v1.1.0
122
+ if "_qkv_same_embed_dim" not in state:
123
+ state["_qkv_same_embed_dim"] = True
124
+
125
+ super(MultiheadAttention, self).__setstate__(state)
126
+
127
+ def forward(
128
+ self,
129
+ query: Tensor,
130
+ key: Tensor,
131
+ value: Tensor,
132
+ key_padding_mask: Optional[Tensor] = None,
133
+ need_weights: bool = True,
134
+ attn_mask: Optional[Tensor] = None,
135
+ ) -> Tuple[Tensor, Optional[Tensor]]:
136
+ r"""
137
+ Args:
138
+ query: Query embeddings of shape :math:`(L, N, E_q)` when ``batch_first=False`` or :math:`(N, L, E_q)`
139
+ when ``batch_first=True``, where :math:`L` is the target sequence length, :math:`N` is the batch size,
140
+ and :math:`E_q` is the query embedding dimension ``embed_dim``. Queries are compared against
141
+ key-value pairs to produce the output. See "Attention Is All You Need" for more details.
142
+ key: Key embeddings of shape :math:`(S, N, E_k)` when ``batch_first=False`` or :math:`(N, S, E_k)` when
143
+ ``batch_first=True``, where :math:`S` is the source sequence length, :math:`N` is the batch size, and
144
+ :math:`E_k` is the key embedding dimension ``kdim``. See "Attention Is All You Need" for more details.
145
+ value: Value embeddings of shape :math:`(S, N, E_v)` when ``batch_first=False`` or :math:`(N, S, E_v)` when
146
+ ``batch_first=True``, where :math:`S` is the source sequence length, :math:`N` is the batch size, and
147
+ :math:`E_v` is the value embedding dimension ``vdim``. See "Attention Is All You Need" for more details.
148
+ key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
149
+ to ignore for the purpose of attention (i.e. treat as "padding"). Binary and byte masks are supported.
150
+ For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
151
+ the purpose of attention. For a byte mask, a non-zero value indicates that the corresponding ``key``
152
+ value will be ignored.
153
+ need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
154
+ Default: ``True``.
155
+ attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
156
+ :math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
157
+ :math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
158
+ broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
159
+ Binary, byte, and float masks are supported. For a binary mask, a ``True`` value indicates that the
160
+ corresponding position is not allowed to attend. For a byte mask, a non-zero value indicates that the
161
+ corresponding position is not allowed to attend. For a float mask, the mask values will be added to
162
+ the attention weight.
163
+
164
+ Outputs:
165
+ - **attn_output** - Attention outputs of shape :math:`(L, N, E)` when ``batch_first=False`` or
166
+ :math:`(N, L, E)` when ``batch_first=True``, where :math:`L` is the target sequence length, :math:`N` is
167
+ the batch size, and :math:`E` is the embedding dimension ``embed_dim``.
168
+ - **attn_output_weights** - Attention output weights of shape :math:`(N, L, S)`, where :math:`N` is the batch
169
+ size, :math:`L` is the target sequence length, and :math:`S` is the source sequence length. Only returned
170
+ when ``need_weights=True``.
171
+ """
172
+ if self.batch_first:
173
+ query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
174
+
175
+ if not self._qkv_same_embed_dim:
176
+ q_proj_weight = (
177
+ self.q_proj_weight.get_weight()
178
+ if self.q_proj_weight is not None
179
+ else None
180
+ )
181
+ k_proj_weight = (
182
+ self.k_proj_weight.get_weight()
183
+ if self.k_proj_weight is not None
184
+ else None
185
+ )
186
+ v_proj_weight = (
187
+ self.v_proj_weight.get_weight()
188
+ if self.v_proj_weight is not None
189
+ else None
190
+ )
191
+ (
192
+ attn_output,
193
+ attn_output_weights,
194
+ ) = nn.functional.multi_head_attention_forward(
195
+ query,
196
+ key,
197
+ value,
198
+ self.embed_dim,
199
+ self.num_heads,
200
+ self.in_proj_weight.get_weight(),
201
+ self.in_proj_weight.get_bias(),
202
+ self.bias_k,
203
+ self.bias_v,
204
+ self.add_zero_attn,
205
+ self.dropout,
206
+ self.out_proj.get_weight(),
207
+ self.out_proj.get_bias(),
208
+ training=self.training,
209
+ key_padding_mask=key_padding_mask,
210
+ need_weights=need_weights,
211
+ attn_mask=attn_mask,
212
+ use_separate_proj_weight=True,
213
+ q_proj_weight=q_proj_weight,
214
+ k_proj_weight=k_proj_weight,
215
+ v_proj_weight=v_proj_weight,
216
+ )
217
+ else:
218
+ (
219
+ attn_output,
220
+ attn_output_weights,
221
+ ) = nn.functional.multi_head_attention_forward(
222
+ query,
223
+ key,
224
+ value,
225
+ self.embed_dim,
226
+ self.num_heads,
227
+ self.in_proj_weight.get_weight(),
228
+ self.in_proj_weight.get_bias(),
229
+ self.bias_k,
230
+ self.bias_v,
231
+ self.add_zero_attn,
232
+ self.dropout,
233
+ self.out_proj.get_weight(),
234
+ self.out_proj.get_bias(),
235
+ training=self.training,
236
+ key_padding_mask=key_padding_mask,
237
+ need_weights=need_weights,
238
+ attn_mask=attn_mask,
239
+ )
240
+ if self.batch_first:
241
+ return attn_output.transpose(1, 0), attn_output_weights
242
+ else:
243
+ return attn_output, attn_output_weights
conformer_hrbk.py ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) 2021 University of Chinese Academy of Sciences (author: Han Zhu)
3
+ # 2022 Xiaomi Corp. (author: Quandong Wang)
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 math
21
+ import warnings
22
+ from typing import Optional, Tuple
23
+
24
+ import torch
25
+ from scaling import (
26
+ ActivationBalancer,
27
+ BasicNorm,
28
+ DoubleSwish,
29
+ ScaledConv1d,
30
+ ScaledLinear,
31
+ )
32
+ from subsampling import Conv2dSubsampling
33
+ from torch import Tensor, nn
34
+ from transformer import Supervisions, Transformer, encoder_padding_mask
35
+ ## from transformer_hrbk import Supervisions, Transformer, encoder_padding_mask ## hrbk added
36
+
37
+
38
+ class Conformer(Transformer):
39
+ """
40
+ Args:
41
+ num_features (int): Number of input features
42
+ num_classes (int): Number of output classes
43
+ subsampling_factor (int): subsampling factor of encoder (the convolution layers before transformers)
44
+ d_model (int): attention dimension, also the output dimension
45
+ nhead (int): number of head
46
+ dim_feedforward (int): feedforward dimension
47
+ num_encoder_layers (int): number of encoder layers
48
+ num_decoder_layers (int): number of decoder layers
49
+ dropout (float): dropout rate
50
+ layer_dropout (float): layer-dropout rate.
51
+ cnn_module_kernel (int): Kernel size of convolution module
52
+ vgg_frontend (bool): whether to use vgg frontend.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ num_features: int,
58
+ num_classes: int,
59
+ subsampling_factor: int = 4,
60
+ d_model: int = 128,
61
+ nhead: int = 4,
62
+ dim_feedforward: int = 1024,
63
+ num_encoder_layers: int = 12,
64
+ num_decoder_layers: int = 0,
65
+ dropout: float = 0.1,
66
+ layer_dropout: float = 0.075,
67
+ cnn_module_kernel: int = 31,
68
+ ) -> None:
69
+ super(Conformer, self).__init__(
70
+ num_features=num_features,
71
+ num_classes=num_classes,
72
+ subsampling_factor=subsampling_factor,
73
+ d_model=d_model,
74
+ nhead=nhead,
75
+ dim_feedforward=dim_feedforward,
76
+ num_encoder_layers=num_encoder_layers,
77
+ num_decoder_layers=num_decoder_layers,
78
+ dropout=dropout,
79
+ layer_dropout=layer_dropout,
80
+ )
81
+
82
+ self.num_features = num_features
83
+ self.subsampling_factor = subsampling_factor
84
+ if subsampling_factor != 4:
85
+ raise NotImplementedError("Support only 'subsampling_factor=4'.")
86
+
87
+ # self.encoder_embed converts the input of shape (N, T, num_features)
88
+ # to the shape (N, T//subsampling_factor, d_model).
89
+ # That is, it does two things simultaneously:
90
+ # (1) subsampling: T -> T//subsampling_factor
91
+ # (2) embedding: num_features -> d_model
92
+ self.encoder_embed = Conv2dSubsampling(num_features, d_model)
93
+
94
+ self.encoder_pos = RelPositionalEncoding(d_model, dropout)
95
+
96
+ encoder_layer = ConformerEncoderLayer(
97
+ d_model,
98
+ nhead,
99
+ dim_feedforward,
100
+ dropout,
101
+ layer_dropout,
102
+ cnn_module_kernel,
103
+ )
104
+ self.encoder = ConformerEncoder(encoder_layer, num_encoder_layers)
105
+
106
+ def run_encoder(
107
+ self,
108
+ x: torch.Tensor,
109
+ supervisions: Optional[Supervisions] = None,
110
+ warmup: float = 1.0,
111
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
112
+ """
113
+ Args:
114
+ x:
115
+ The input tensor. Its shape is (batch_size, seq_len, feature_dim).
116
+ supervisions:
117
+ Supervision in lhotse format.
118
+ See https://github.com/lhotse-speech/lhotse/blob/master/lhotse/dataset/speech_recognition.py#L32 # noqa
119
+ CAUTION: It contains length information, i.e., start and number of
120
+ frames, before subsampling
121
+ It is read directly from the batch, without any sorting. It is used
122
+ to compute encoder padding mask, which is used as memory key padding
123
+ mask for the decoder.
124
+ warmup:
125
+ A floating point value that gradually increases from 0 throughout
126
+ training; when it is >= 1.0 we are "fully warmed up". It is used
127
+ to turn modules on sequentially.
128
+ Returns:
129
+ Tensor: Predictor tensor of dimension (input_length, batch_size, d_model).
130
+ Tensor: Mask tensor of dimension (batch_size, input_length)
131
+ """
132
+ x = self.encoder_embed(x)
133
+ x, pos_emb = self.encoder_pos(x)
134
+ x = x.permute(1, 0, 2) # (N, T, C) -> (T, N, C)
135
+ mask = encoder_padding_mask(x.size(0), supervisions)
136
+ if mask is not None:
137
+ mask = mask.to(x.device)
138
+
139
+ # Caution: We assume the subsampling factor is 4!
140
+
141
+ x = self.encoder(
142
+ x, pos_emb, src_key_padding_mask=mask, warmup=warmup
143
+ ) # (T, N, C)
144
+
145
+ # x = x.permute(1, 0, 2) # (T, N, C) ->(N, T, C)
146
+
147
+ # return x, lengths
148
+ return x, mask
149
+ ## return x, mask, middle_x
150
+
151
+
152
+ class ConformerEncoderLayer(nn.Module):
153
+ """
154
+ ConformerEncoderLayer is made up of self-attn, feedforward and convolution networks.
155
+ See: "Conformer: Convolution-augmented Transformer for Speech Recognition"
156
+
157
+ Args:
158
+ d_model: the number of expected features in the input (required).
159
+ nhead: the number of heads in the multiheadattention models (required).
160
+ dim_feedforward: the dimension of the feedforward network model (default=2048).
161
+ dropout: the dropout value (default=0.1).
162
+ cnn_module_kernel (int): Kernel size of convolution module.
163
+
164
+ Examples::
165
+ >>> encoder_layer = ConformerEncoderLayer(d_model=512, nhead=8)
166
+ >>> src = torch.rand(10, 32, 512)
167
+ >>> pos_emb = torch.rand(32, 19, 512)
168
+ >>> out = encoder_layer(src, pos_emb)
169
+ """
170
+
171
+ def __init__(
172
+ self,
173
+ d_model: int,
174
+ nhead: int,
175
+ dim_feedforward: int = 2048,
176
+ dropout: float = 0.1,
177
+ layer_dropout: float = 0.075,
178
+ cnn_module_kernel: int = 31,
179
+ ) -> None:
180
+ super(ConformerEncoderLayer, self).__init__()
181
+
182
+ self.layer_dropout = layer_dropout
183
+
184
+ self.d_model = d_model
185
+
186
+ self.self_attn = RelPositionMultiheadAttention(d_model, nhead, dropout=0.0)
187
+
188
+ self.feed_forward = nn.Sequential(
189
+ ScaledLinear(d_model, dim_feedforward),
190
+ ActivationBalancer(channel_dim=-1),
191
+ DoubleSwish(),
192
+ nn.Dropout(dropout),
193
+ ScaledLinear(dim_feedforward, d_model, initial_scale=0.25),
194
+ )
195
+
196
+ self.feed_forward_macaron = nn.Sequential(
197
+ ScaledLinear(d_model, dim_feedforward),
198
+ ActivationBalancer(channel_dim=-1),
199
+ DoubleSwish(),
200
+ nn.Dropout(dropout),
201
+ ScaledLinear(dim_feedforward, d_model, initial_scale=0.25),
202
+ )
203
+
204
+ self.conv_module = ConvolutionModule(d_model, cnn_module_kernel)
205
+
206
+ self.norm_final = BasicNorm(d_model)
207
+
208
+ # try to ensure the output is close to zero-mean (or at least, zero-median).
209
+ self.balancer = ActivationBalancer(
210
+ channel_dim=-1, min_positive=0.45, max_positive=0.55, max_abs=6.0
211
+ )
212
+
213
+ self.dropout = nn.Dropout(dropout)
214
+
215
+ def forward(
216
+ self,
217
+ src: Tensor,
218
+ pos_emb: Tensor,
219
+ src_mask: Optional[Tensor] = None,
220
+ src_key_padding_mask: Optional[Tensor] = None,
221
+ warmup: float = 1.0,
222
+ ) -> Tensor:
223
+ """
224
+ Pass the input through the encoder layer.
225
+
226
+ Args:
227
+ src: the sequence to the encoder layer (required).
228
+ pos_emb: Positional embedding tensor (required).
229
+ src_mask: the mask for the src sequence (optional).
230
+ src_key_padding_mask: the mask for the src keys per batch (optional).
231
+ warmup: controls selective bypass of of layers; if < 1.0, we will
232
+ bypass layers more frequently.
233
+
234
+ Shape:
235
+ src: (S, N, E).
236
+ pos_emb: (N, 2*S-1, E)
237
+ src_mask: (S, S).
238
+ src_key_padding_mask: (N, S).
239
+ S is the source sequence length, N is the batch size, E is the feature number
240
+ """
241
+ src_orig = src
242
+
243
+ warmup_scale = min(0.1 + warmup, 1.0)
244
+ # alpha = 1.0 means fully use this encoder layer, 0.0 would mean
245
+ # completely bypass it.
246
+ if self.training:
247
+ alpha = (
248
+ warmup_scale
249
+ if torch.rand(()).item() <= (1.0 - self.layer_dropout)
250
+ else 0.1
251
+ )
252
+ else:
253
+ alpha = 1.0
254
+
255
+ # macaron style feed forward module
256
+ src = src + self.dropout(self.feed_forward_macaron(src))
257
+
258
+ # multi-headed self-attention module
259
+ src_att = self.self_attn(
260
+ src,
261
+ src,
262
+ src,
263
+ pos_emb=pos_emb,
264
+ attn_mask=src_mask,
265
+ key_padding_mask=src_key_padding_mask,
266
+ )[0]
267
+ src = src + self.dropout(src_att)
268
+
269
+ # convolution module
270
+ src = src + self.dropout(
271
+ self.conv_module(src, src_key_padding_mask=src_key_padding_mask)
272
+ )
273
+
274
+ # feed forward module
275
+ src = src + self.dropout(self.feed_forward(src))
276
+
277
+ src = self.norm_final(self.balancer(src))
278
+
279
+ if alpha != 1.0:
280
+ src = alpha * src + (1 - alpha) * src_orig
281
+
282
+ return src
283
+
284
+
285
+ class ConformerEncoder(nn.Module):
286
+ r"""ConformerEncoder is a stack of N encoder layers
287
+
288
+ Args:
289
+ encoder_layer: an instance of the ConformerEncoderLayer() class (required).
290
+ num_layers: the number of sub-encoder-layers in the encoder (required).
291
+
292
+ Examples::
293
+ >>> encoder_layer = ConformerEncoderLayer(d_model=512, nhead=8)
294
+ >>> conformer_encoder = ConformerEncoder(encoder_layer, num_layers=6)
295
+ >>> src = torch.rand(10, 32, 512)
296
+ >>> pos_emb = torch.rand(32, 19, 512)
297
+ >>> out = conformer_encoder(src, pos_emb)
298
+ """
299
+
300
+ def __init__(self, encoder_layer: nn.Module, num_layers: int) -> None:
301
+ super().__init__()
302
+ self.layers = nn.ModuleList(
303
+ [copy.deepcopy(encoder_layer) for i in range(num_layers)]
304
+ )
305
+ self.num_layers = num_layers
306
+
307
+ def forward(
308
+ self,
309
+ src: Tensor,
310
+ pos_emb: Tensor,
311
+ mask: Optional[Tensor] = None,
312
+ src_key_padding_mask: Optional[Tensor] = None,
313
+ warmup: float = 1.0,
314
+ ) -> Tensor:
315
+ r"""Pass the input through the encoder layers in turn.
316
+
317
+ Args:
318
+ src: the sequence to the encoder (required).
319
+ pos_emb: Positional embedding tensor (required).
320
+ mask: the mask for the src sequence (optional).
321
+ src_key_padding_mask: the mask for the src keys per batch (optional).
322
+
323
+ Shape:
324
+ src: (S, N, E).
325
+ pos_emb: (N, 2*S-1, E)
326
+ mask: (S, S).
327
+ src_key_padding_mask: (N, S).
328
+ S is the source sequence length, T is the target sequence length, N is the batch size, E is the feature number
329
+
330
+ """
331
+ output = src
332
+ middle_outputs = [] ## hrbk added
333
+
334
+ for i, mod in enumerate(self.layers):
335
+ output = mod(
336
+ output,
337
+ pos_emb,
338
+ src_mask=mask,
339
+ src_key_padding_mask=src_key_padding_mask,
340
+ warmup=warmup,
341
+ )
342
+ middle_outputs.append(output) ## hrbk added
343
+
344
+ return output
345
+ ## return output, middle_outputs
346
+
347
+
348
+ class RelPositionalEncoding(torch.nn.Module):
349
+ """Relative positional encoding module.
350
+
351
+ See : Appendix B in "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
352
+ Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/embedding.py
353
+
354
+ Args:
355
+ d_model: Embedding dimension.
356
+ dropout_rate: Dropout rate.
357
+ max_len: Maximum input length.
358
+
359
+ """
360
+
361
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000) -> None:
362
+ """Construct an PositionalEncoding object."""
363
+ super(RelPositionalEncoding, self).__init__()
364
+ self.d_model = d_model
365
+ self.dropout = torch.nn.Dropout(p=dropout_rate)
366
+ self.pe = None
367
+ self.extend_pe(torch.tensor(0.0).expand(1, max_len))
368
+
369
+ def extend_pe(self, x: Tensor) -> None:
370
+ """Reset the positional encodings."""
371
+ if self.pe is not None:
372
+ # self.pe contains both positive and negative parts
373
+ # the length of self.pe is 2 * input_len - 1
374
+ if self.pe.size(1) >= x.size(1) * 2 - 1:
375
+ # Note: TorchScript doesn't implement operator== for torch.Device
376
+ if self.pe.dtype != x.dtype or str(self.pe.device) != str(x.device):
377
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
378
+ return
379
+ # Suppose `i` means to the position of query vecotr and `j` means the
380
+ # position of key vector. We use position relative positions when keys
381
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
382
+ pe_positive = torch.zeros(x.size(1), self.d_model)
383
+ pe_negative = torch.zeros(x.size(1), self.d_model)
384
+ position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
385
+ div_term = torch.exp(
386
+ torch.arange(0, self.d_model, 2, dtype=torch.float32)
387
+ * -(math.log(10000.0) / self.d_model)
388
+ )
389
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
390
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
391
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
392
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
393
+
394
+ # Reserve the order of positive indices and concat both positive and
395
+ # negative indices. This is used to support the shifting trick
396
+ # as in "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
397
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
398
+ pe_negative = pe_negative[1:].unsqueeze(0)
399
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
400
+ self.pe = pe.to(device=x.device, dtype=x.dtype)
401
+
402
+ def forward(self, x: torch.Tensor) -> Tuple[Tensor, Tensor]:
403
+ """Add positional encoding.
404
+
405
+ Args:
406
+ x (torch.Tensor): Input tensor (batch, time, `*`).
407
+
408
+ Returns:
409
+ torch.Tensor: Encoded tensor (batch, time, `*`).
410
+ torch.Tensor: Encoded tensor (batch, 2*time-1, `*`).
411
+
412
+ """
413
+ self.extend_pe(x)
414
+ pos_emb = self.pe[
415
+ :,
416
+ self.pe.size(1) // 2
417
+ - x.size(1)
418
+ + 1 : self.pe.size(1) // 2 # noqa E203
419
+ + x.size(1),
420
+ ]
421
+ return self.dropout(x), self.dropout(pos_emb)
422
+
423
+
424
+ class RelPositionMultiheadAttention(nn.Module):
425
+ r"""Multi-Head Attention layer with relative position encoding
426
+
427
+ See reference: "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
428
+
429
+ Args:
430
+ embed_dim: total dimension of the model.
431
+ num_heads: parallel attention heads.
432
+ dropout: a Dropout layer on attn_output_weights. Default: 0.0.
433
+
434
+ Examples::
435
+
436
+ >>> rel_pos_multihead_attn = RelPositionMultiheadAttention(embed_dim, num_heads)
437
+ >>> attn_output, attn_output_weights = multihead_attn(query, key, value, pos_emb)
438
+ """
439
+
440
+ def __init__(
441
+ self,
442
+ embed_dim: int,
443
+ num_heads: int,
444
+ dropout: float = 0.0,
445
+ ) -> None:
446
+ super(RelPositionMultiheadAttention, self).__init__()
447
+ self.embed_dim = embed_dim
448
+ self.num_heads = num_heads
449
+ self.dropout = dropout
450
+ self.head_dim = embed_dim // num_heads
451
+ assert (
452
+ self.head_dim * num_heads == self.embed_dim
453
+ ), "embed_dim must be divisible by num_heads"
454
+
455
+ self.in_proj = ScaledLinear(embed_dim, 3 * embed_dim, bias=True)
456
+ self.out_proj = ScaledLinear(
457
+ embed_dim, embed_dim, bias=True, initial_scale=0.25
458
+ )
459
+
460
+ # linear transformation for positional encoding.
461
+ self.linear_pos = ScaledLinear(embed_dim, embed_dim, bias=False)
462
+ # these two learnable bias are used in matrix c and matrix d
463
+ # as described in "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context" Section 3.3
464
+ self.pos_bias_u = nn.Parameter(torch.Tensor(num_heads, self.head_dim))
465
+ self.pos_bias_v = nn.Parameter(torch.Tensor(num_heads, self.head_dim))
466
+ self.pos_bias_u_scale = nn.Parameter(torch.zeros(()).detach())
467
+ self.pos_bias_v_scale = nn.Parameter(torch.zeros(()).detach())
468
+ self._reset_parameters()
469
+
470
+ def _pos_bias_u(self):
471
+ return self.pos_bias_u * self.pos_bias_u_scale.exp()
472
+
473
+ def _pos_bias_v(self):
474
+ return self.pos_bias_v * self.pos_bias_v_scale.exp()
475
+
476
+ def _reset_parameters(self) -> None:
477
+ nn.init.normal_(self.pos_bias_u, std=0.01)
478
+ nn.init.normal_(self.pos_bias_v, std=0.01)
479
+
480
+ def forward(
481
+ self,
482
+ query: Tensor,
483
+ key: Tensor,
484
+ value: Tensor,
485
+ pos_emb: Tensor,
486
+ key_padding_mask: Optional[Tensor] = None,
487
+ need_weights: bool = True,
488
+ attn_mask: Optional[Tensor] = None,
489
+ ) -> Tuple[Tensor, Optional[Tensor]]:
490
+ r"""
491
+ Args:
492
+ query, key, value: map a query and a set of key-value pairs to an output.
493
+ pos_emb: Positional embedding tensor
494
+ key_padding_mask: if provided, specified padding elements in the key will
495
+ be ignored by the attention. When given a binary mask and a value is True,
496
+ the corresponding value on the attention layer will be ignored. When given
497
+ a byte mask and a value is non-zero, the corresponding value on the attention
498
+ layer will be ignored
499
+ need_weights: output attn_output_weights.
500
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
501
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
502
+
503
+ Shape:
504
+ - Inputs:
505
+ - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
506
+ the embedding dimension.
507
+ - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
508
+ the embedding dimension.
509
+ - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
510
+ the embedding dimension.
511
+ - pos_emb: :math:`(N, 2*L-1, E)` where L is the target sequence length, N is the batch size, E is
512
+ the embedding dimension.
513
+ - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
514
+ If a ByteTensor is provided, the non-zero positions will be ignored while the position
515
+ with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the
516
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
517
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
518
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
519
+ S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
520
+ positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
521
+ while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
522
+ is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
523
+ is provided, it will be added to the attention weight.
524
+
525
+ - Outputs:
526
+ - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
527
+ E is the embedding dimension.
528
+ - attn_output_weights: :math:`(N, L, S)` where N is the batch size,
529
+ L is the target sequence length, S is the source sequence length.
530
+ """
531
+ return self.multi_head_attention_forward(
532
+ query,
533
+ key,
534
+ value,
535
+ pos_emb,
536
+ self.embed_dim,
537
+ self.num_heads,
538
+ self.in_proj.get_weight(),
539
+ self.in_proj.get_bias(),
540
+ self.dropout,
541
+ self.out_proj.get_weight(),
542
+ self.out_proj.get_bias(),
543
+ training=self.training,
544
+ key_padding_mask=key_padding_mask,
545
+ need_weights=need_weights,
546
+ attn_mask=attn_mask,
547
+ )
548
+
549
+ def rel_shift(self, x: Tensor) -> Tensor:
550
+ """Compute relative positional encoding.
551
+
552
+ Args:
553
+ x: Input tensor (batch, head, time1, 2*time1-1).
554
+ time1 means the length of query vector.
555
+
556
+ Returns:
557
+ Tensor: tensor of shape (batch, head, time1, time2)
558
+ (note: time2 has the same value as time1, but it is for
559
+ the key, while time1 is for the query).
560
+ """
561
+ (batch_size, num_heads, time1, n) = x.shape
562
+ assert n == 2 * time1 - 1
563
+ # Note: TorchScript requires explicit arg for stride()
564
+ batch_stride = x.stride(0)
565
+ head_stride = x.stride(1)
566
+ time1_stride = x.stride(2)
567
+ n_stride = x.stride(3)
568
+ return x.as_strided(
569
+ (batch_size, num_heads, time1, time1),
570
+ (batch_stride, head_stride, time1_stride - n_stride, n_stride),
571
+ storage_offset=n_stride * (time1 - 1),
572
+ )
573
+
574
+ def multi_head_attention_forward(
575
+ self,
576
+ query: Tensor,
577
+ key: Tensor,
578
+ value: Tensor,
579
+ pos_emb: Tensor,
580
+ embed_dim_to_check: int,
581
+ num_heads: int,
582
+ in_proj_weight: Tensor,
583
+ in_proj_bias: Tensor,
584
+ dropout_p: float,
585
+ out_proj_weight: Tensor,
586
+ out_proj_bias: Tensor,
587
+ training: bool = True,
588
+ key_padding_mask: Optional[Tensor] = None,
589
+ need_weights: bool = True,
590
+ attn_mask: Optional[Tensor] = None,
591
+ ) -> Tuple[Tensor, Optional[Tensor]]:
592
+ r"""
593
+ Args:
594
+ query, key, value: map a query and a set of key-value pairs to an output.
595
+ pos_emb: Positional embedding tensor
596
+ embed_dim_to_check: total dimension of the model.
597
+ num_heads: parallel attention heads.
598
+ in_proj_weight, in_proj_bias: input projection weight and bias.
599
+ dropout_p: probability of an element to be zeroed.
600
+ out_proj_weight, out_proj_bias: the output projection weight and bias.
601
+ training: apply dropout if is ``True``.
602
+ key_padding_mask: if provided, specified padding elements in the key will
603
+ be ignored by the attention. This is an binary mask. When the value is True,
604
+ the corresponding value on the attention layer will be filled with -inf.
605
+ need_weights: output attn_output_weights.
606
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
607
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
608
+
609
+ Shape:
610
+ Inputs:
611
+ - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
612
+ the embedding dimension.
613
+ - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
614
+ the embedding dimension.
615
+ - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
616
+ the embedding dimension.
617
+ - pos_emb: :math:`(N, 2*L-1, E)` or :math:`(1, 2*L-1, E)` where L is the target sequence
618
+ length, N is the batch size, E is the embedding dimension.
619
+ - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
620
+ If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions
621
+ will be unchanged. If a BoolTensor is provided, the positions with the
622
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
623
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
624
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
625
+ S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
626
+ positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
627
+ while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
628
+ are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
629
+ is provided, it will be added to the attention weight.
630
+
631
+ Outputs:
632
+ - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
633
+ E is the embedding dimension.
634
+ - attn_output_weights: :math:`(N, L, S)` where N is the batch size,
635
+ L is the target sequence length, S is the source sequence length.
636
+ """
637
+
638
+ tgt_len, bsz, embed_dim = query.size()
639
+ assert embed_dim == embed_dim_to_check
640
+ assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
641
+
642
+ head_dim = embed_dim // num_heads
643
+ assert (
644
+ head_dim * num_heads == embed_dim
645
+ ), "embed_dim must be divisible by num_heads"
646
+
647
+ scaling = float(head_dim) ** -0.5
648
+
649
+ if torch.equal(query, key) and torch.equal(key, value):
650
+ # self-attention
651
+ q, k, v = nn.functional.linear(query, in_proj_weight, in_proj_bias).chunk(
652
+ 3, dim=-1
653
+ )
654
+
655
+ elif torch.equal(key, value):
656
+ # encoder-decoder attention
657
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
658
+ _b = in_proj_bias
659
+ _start = 0
660
+ _end = embed_dim
661
+ _w = in_proj_weight[_start:_end, :]
662
+ if _b is not None:
663
+ _b = _b[_start:_end]
664
+ q = nn.functional.linear(query, _w, _b)
665
+
666
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
667
+ _b = in_proj_bias
668
+ _start = embed_dim
669
+ _end = None
670
+ _w = in_proj_weight[_start:, :]
671
+ if _b is not None:
672
+ _b = _b[_start:]
673
+ k, v = nn.functional.linear(key, _w, _b).chunk(2, dim=-1)
674
+
675
+ else:
676
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
677
+ _b = in_proj_bias
678
+ _start = 0
679
+ _end = embed_dim
680
+ _w = in_proj_weight[_start:_end, :]
681
+ if _b is not None:
682
+ _b = _b[_start:_end]
683
+ q = nn.functional.linear(query, _w, _b)
684
+
685
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
686
+ _b = in_proj_bias
687
+ _start = embed_dim
688
+ _end = embed_dim * 2
689
+ _w = in_proj_weight[_start:_end, :]
690
+ if _b is not None:
691
+ _b = _b[_start:_end]
692
+ k = nn.functional.linear(key, _w, _b)
693
+
694
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
695
+ _b = in_proj_bias
696
+ _start = embed_dim * 2
697
+ _end = None
698
+ _w = in_proj_weight[_start:, :]
699
+ if _b is not None:
700
+ _b = _b[_start:]
701
+ v = nn.functional.linear(value, _w, _b)
702
+
703
+ if attn_mask is not None:
704
+ assert (
705
+ attn_mask.dtype == torch.float32
706
+ or attn_mask.dtype == torch.float64
707
+ or attn_mask.dtype == torch.float16
708
+ or attn_mask.dtype == torch.uint8
709
+ or attn_mask.dtype == torch.bool
710
+ ), "Only float, byte, and bool types are supported for attn_mask, not {}".format(
711
+ attn_mask.dtype
712
+ )
713
+ if attn_mask.dtype == torch.uint8:
714
+ warnings.warn(
715
+ "Byte tensor for attn_mask is deprecated. Use bool tensor instead."
716
+ )
717
+ attn_mask = attn_mask.to(torch.bool)
718
+
719
+ if attn_mask.dim() == 2:
720
+ attn_mask = attn_mask.unsqueeze(0)
721
+ if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
722
+ raise RuntimeError("The size of the 2D attn_mask is not correct.")
723
+ elif attn_mask.dim() == 3:
724
+ if list(attn_mask.size()) != [
725
+ bsz * num_heads,
726
+ query.size(0),
727
+ key.size(0),
728
+ ]:
729
+ raise RuntimeError("The size of the 3D attn_mask is not correct.")
730
+ else:
731
+ raise RuntimeError(
732
+ "attn_mask's dimension {} is not supported".format(attn_mask.dim())
733
+ )
734
+ # attn_mask's dim is 3 now.
735
+
736
+ # convert ByteTensor key_padding_mask to bool
737
+ if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
738
+ warnings.warn(
739
+ "Byte tensor for key_padding_mask is deprecated. Use bool tensor instead."
740
+ )
741
+ key_padding_mask = key_padding_mask.to(torch.bool)
742
+
743
+ q = (q * scaling).contiguous().view(tgt_len, bsz, num_heads, head_dim)
744
+ k = k.contiguous().view(-1, bsz, num_heads, head_dim)
745
+ v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
746
+
747
+ src_len = k.size(0)
748
+
749
+ if key_padding_mask is not None:
750
+ assert key_padding_mask.size(0) == bsz, "{} == {}".format(
751
+ key_padding_mask.size(0), bsz
752
+ )
753
+ assert key_padding_mask.size(1) == src_len, "{} == {}".format(
754
+ key_padding_mask.size(1), src_len
755
+ )
756
+
757
+ q = q.transpose(0, 1) # (batch, time1, head, d_k)
758
+
759
+ pos_emb_bsz = pos_emb.size(0)
760
+ assert pos_emb_bsz in (1, bsz) # actually it is 1
761
+ p = self.linear_pos(pos_emb).view(pos_emb_bsz, -1, num_heads, head_dim)
762
+ p = p.transpose(1, 2) # (batch, head, 2*time1-1, d_k)
763
+
764
+ q_with_bias_u = (q + self._pos_bias_u()).transpose(
765
+ 1, 2
766
+ ) # (batch, head, time1, d_k)
767
+
768
+ q_with_bias_v = (q + self._pos_bias_v()).transpose(
769
+ 1, 2
770
+ ) # (batch, head, time1, d_k)
771
+
772
+ # compute attention score
773
+ # first compute matrix a and matrix c
774
+ # as described in "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context" Section 3.3
775
+ k = k.permute(1, 2, 3, 0) # (batch, head, d_k, time2)
776
+ matrix_ac = torch.matmul(q_with_bias_u, k) # (batch, head, time1, time2)
777
+
778
+ # compute matrix b and matrix d
779
+ matrix_bd = torch.matmul(
780
+ q_with_bias_v, p.transpose(-2, -1)
781
+ ) # (batch, head, time1, 2*time1-1)
782
+ matrix_bd = self.rel_shift(matrix_bd)
783
+
784
+ attn_output_weights = matrix_ac + matrix_bd # (batch, head, time1, time2)
785
+
786
+ attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, -1)
787
+
788
+ assert list(attn_output_weights.size()) == [
789
+ bsz * num_heads,
790
+ tgt_len,
791
+ src_len,
792
+ ]
793
+
794
+ if attn_mask is not None:
795
+ if attn_mask.dtype == torch.bool:
796
+ attn_output_weights.masked_fill_(attn_mask, float("-inf"))
797
+ else:
798
+ attn_output_weights += attn_mask
799
+
800
+ if key_padding_mask is not None:
801
+ attn_output_weights = attn_output_weights.view(
802
+ bsz, num_heads, tgt_len, src_len
803
+ )
804
+ attn_output_weights = attn_output_weights.masked_fill(
805
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
806
+ float("-inf"),
807
+ )
808
+ attn_output_weights = attn_output_weights.view(
809
+ bsz * num_heads, tgt_len, src_len
810
+ )
811
+
812
+ attn_output_weights = nn.functional.softmax(attn_output_weights, dim=-1)
813
+ attn_output_weights = nn.functional.dropout(
814
+ attn_output_weights, p=dropout_p, training=training
815
+ )
816
+
817
+ attn_output = torch.bmm(attn_output_weights, v)
818
+ assert list(attn_output.size()) == [bsz * num_heads, tgt_len, head_dim]
819
+ attn_output = (
820
+ attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
821
+ )
822
+ attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias)
823
+
824
+ if need_weights:
825
+ # average attention weights over heads
826
+ attn_output_weights = attn_output_weights.view(
827
+ bsz, num_heads, tgt_len, src_len
828
+ )
829
+ return attn_output, attn_output_weights.sum(dim=1) / num_heads
830
+ else:
831
+ return attn_output, None
832
+
833
+
834
+ class ConvolutionModule(nn.Module):
835
+ """ConvolutionModule in Conformer model.
836
+ Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/conformer/convolution.py
837
+
838
+ Args:
839
+ channels (int): The number of channels of conv layers.
840
+ kernel_size (int): Kernerl size of conv layers.
841
+ bias (bool): Whether to use bias in conv layers (default=True).
842
+
843
+ """
844
+
845
+ def __init__(self, channels: int, kernel_size: int, bias: bool = True) -> None:
846
+ """Construct an ConvolutionModule object."""
847
+ super(ConvolutionModule, self).__init__()
848
+ # kernerl_size should be a odd number for 'SAME' padding
849
+ assert (kernel_size - 1) % 2 == 0
850
+
851
+ self.pointwise_conv1 = ScaledConv1d(
852
+ channels,
853
+ 2 * channels,
854
+ kernel_size=1,
855
+ stride=1,
856
+ padding=0,
857
+ bias=bias,
858
+ )
859
+
860
+ # after pointwise_conv1 we put x through a gated linear unit (nn.functional.glu).
861
+ # For most layers the normal rms value of channels of x seems to be in the range 1 to 4,
862
+ # but sometimes, for some reason, for layer 0 the rms ends up being very large,
863
+ # between 50 and 100 for different channels. This will cause very peaky and
864
+ # sparse derivatives for the sigmoid gating function, which will tend to make
865
+ # the loss function not learn effectively. (for most layers the average absolute values
866
+ # are in the range 0.5..9.0, and the average p(x>0), i.e. positive proportion,
867
+ # at the output of pointwise_conv1.output is around 0.35 to 0.45 for different
868
+ # layers, which likely breaks down as 0.5 for the "linear" half and
869
+ # 0.2 to 0.3 for the part that goes into the sigmoid. The idea is that if we
870
+ # constrain the rms values to a reasonable range via a constraint of max_abs=10.0,
871
+ # it will be in a better position to start learning something, i.e. to latch onto
872
+ # the correct range.
873
+ self.deriv_balancer1 = ActivationBalancer(
874
+ channel_dim=1, max_abs=10.0, min_positive=0.05, max_positive=1.0
875
+ )
876
+
877
+ self.depthwise_conv = ScaledConv1d(
878
+ channels,
879
+ channels,
880
+ kernel_size,
881
+ stride=1,
882
+ padding=(kernel_size - 1) // 2,
883
+ groups=channels,
884
+ bias=bias,
885
+ )
886
+
887
+ self.deriv_balancer2 = ActivationBalancer(
888
+ channel_dim=1, min_positive=0.05, max_positive=1.0
889
+ )
890
+
891
+ self.activation = DoubleSwish()
892
+
893
+ self.pointwise_conv2 = ScaledConv1d(
894
+ channels,
895
+ channels,
896
+ kernel_size=1,
897
+ stride=1,
898
+ padding=0,
899
+ bias=bias,
900
+ initial_scale=0.25,
901
+ )
902
+
903
+ def forward(
904
+ self,
905
+ x: Tensor,
906
+ src_key_padding_mask: Optional[Tensor] = None,
907
+ ) -> Tensor:
908
+ """Compute convolution module.
909
+
910
+ Args:
911
+ x: Input tensor (#time, batch, channels).
912
+ src_key_padding_mask: the mask for the src keys per batch (optional).
913
+
914
+ Returns:
915
+ Tensor: Output tensor (#time, batch, channels).
916
+
917
+ """
918
+ # exchange the temporal dimension and the feature dimension
919
+ x = x.permute(1, 2, 0) # (#batch, channels, time).
920
+
921
+ # GLU mechanism
922
+ x = self.pointwise_conv1(x) # (batch, 2*channels, time)
923
+
924
+ x = self.deriv_balancer1(x)
925
+ x = nn.functional.glu(x, dim=1) # (batch, channels, time)
926
+
927
+ # 1D Depthwise Conv
928
+ if src_key_padding_mask is not None:
929
+ x.masked_fill_(src_key_padding_mask.unsqueeze(1).expand_as(x), 0.0)
930
+ x = self.depthwise_conv(x)
931
+
932
+ x = self.deriv_balancer2(x)
933
+ x = self.activation(x)
934
+
935
+ x = self.pointwise_conv2(x) # (batch, channel, time)
936
+
937
+ return x.permute(2, 0, 1)
938
+
939
+
940
+ if __name__ == "__main__":
941
+ feature_dim = 50
942
+ c = Conformer(num_features=feature_dim, d_model=128, nhead=4)
943
+ batch_size = 5
944
+ seq_len = 20
945
+ # Just make sure the forward pass runs.
946
+ f = c(
947
+ torch.randn(batch_size, seq_len, feature_dim),
948
+ torch.full((batch_size,), seq_len, dtype=torch.int64),
949
+ warmup=0.5,
950
+ )
dashboard.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persian Gradio frontend. Importing this module never imports the ASR runtime."""
2
+
3
+ from base64 import b64encode
4
+ from dataclasses import replace
5
+ from html import escape
6
+ from pathlib import Path
7
+ import inspect
8
+ import re
9
+ import wave
10
+ from uuid import uuid4
11
+
12
+ import gradio as gr
13
+
14
+ # Gradio 6.0 moved the on-load JS from the Blocks constructor to launch();
15
+ # older releases only accept it on Blocks. Detect once and use the right one.
16
+ LAUNCH_ACCEPTS_JS = "js" in inspect.signature(gr.Blocks.launch).parameters
17
+
18
+ ASSETS = Path(__file__).resolve().parent / "dashboard_assets"
19
+
20
+ # Samples shown in the "نمونه‌های آماده" tab: (title, filename, dataset).
21
+ # A sample is listed only while its audio file actually exists inside
22
+ # dashboard_assets, so a new sample appears automatically as soon as its file
23
+ # is dropped into that folder. The dataset is deliberately kept out of the
24
+ # radio label; it is shown in the caption under the list once a clip is
25
+ # selected (see sample_note). To enable the PDID entry, add the clip as
26
+ # dashboard_assets/pdid-sample.wav (or edit the filename below); wav, flac and
27
+ # mp3 all work — without a duration only when the format is not plain wav.
28
+ SAMPLES = [
29
+ ("مسابقهٔ چوگان", "polo.wav", "FLEURS"),
30
+ ("قدرت و نفوذ", "travel.wav", "FLEURS"),
31
+ ("رزرو هتل", "hotel.wav", "FLEURS"),
32
+ ("خانواده شهید", "baradar_shahid.wav", "صامتی (PDID)"),
33
+ ]
34
+
35
+ ICONS = {
36
+ "input": '<path d="M4 10v4m4-8v12m4-16v20m4-16v12m4-8v4"/>',
37
+ "text": '<path d="M5 4h14v16H5zM8 8h8M8 12h8M11 16h5"/>',
38
+ "performance": '<path d="M4 4v16h16M7 15l4-5 3 2 5-7"/>',
39
+ "model": '<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4m6-4v4M9 18v4m6-4v4M2 9h4m-4 6h4m12-6h4m-4 6h4"/><rect x="10" y="10" width="4" height="4"/>',
40
+ "sun": '<circle cx="12" cy="12" r="4"/><path d="M12 2.6v2.5m0 13.8v2.5M2.6 12h2.5m13.8 0h2.5M5.1 5.1l1.8 1.8m10.2 10.2 1.8 1.8m0-13.8-1.8 1.8M6.9 17.1l-1.8 1.8"/>',
41
+ "moon": '<path d="M20.3 13.3A8.3 8.3 0 1 1 10.7 3.7a6.6 6.6 0 0 0 9.6 9.6Z"/>',
42
+ }
43
+
44
+ # Contact email on the درباره ما page; clicking it copies the address to the
45
+ # clipboard (handler wired in THEME_JS below).
46
+ CONTACT_EMAIL = "hrb.kashani@eng.ui.ac.ir"
47
+
48
+ COPY_ICON = ('<svg class="ic-copy" aria-hidden="true" viewBox="0 0 24 24" fill="none" '
49
+ 'stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" '
50
+ 'stroke-linecap="round"><rect x="9" y="9" width="11" height="11" rx="2"/>'
51
+ '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>')
52
+ CHECK_ICON = ('<svg class="ic-check" aria-hidden="true" viewBox="0 0 24 24" fill="none" '
53
+ 'stroke="currentColor" stroke-width="2" stroke-linejoin="round" '
54
+ 'stroke-linecap="round"><path d="M20 6 9 17l-5-5"/></svg>')
55
+
56
+ # The University of Isfahan logo is read straight from dashboard_assets. The
57
+ # common filenames are tried first, then any single other image in the folder
58
+ # (besides the masthead contours), so the page works whatever the file is
59
+ # called. If no image exists at all the logo block simply hides itself.
60
+ LOGO_CANDIDATES = (
61
+ "university-logo.png", "university_logo.png", "ui-logo.png", "ui_logo.png",
62
+ "isfahan-university-logo.png", "isfahan-logo.png", "university-logo.jpg",
63
+ "university-logo.jpeg", "university-logo.svg", "logo.png", "ui.png",
64
+ )
65
+ LOGO_MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
66
+ ".webp": "image/webp", ".svg": "image/svg+xml", ".gif": "image/gif"}
67
+
68
+ # Runs once on page load (gr.Blocks js). Restores the saved theme or follows
69
+ # the browser theme at first paint, wires the light/dark toggles, shows upload
70
+ # indicators for both file uploads and microphone recordings, and copies the
71
+ # team email when its pill is clicked.
72
+ THEME_JS = """() => {
73
+ const root = document.documentElement;
74
+ const KEY = 'asr-theme';
75
+ let stored = null;
76
+ try { stored = localStorage.getItem(KEY); } catch (error) { stored = null; }
77
+ const systemDark = !!(window.matchMedia &&
78
+ window.matchMedia('(prefers-color-scheme: dark)').matches);
79
+ const apply = (theme, persist) => {
80
+ root.dataset.theme = theme;
81
+ const studio = document.getElementById('studio');
82
+ if (studio) studio.dataset.theme = theme;
83
+ if (persist) {
84
+ try { localStorage.setItem(KEY, theme); } catch (error) {}
85
+ }
86
+ };
87
+ // Follow the browser theme on every load; persist only explicit toggles.
88
+ apply((stored === 'light' || stored === 'dark')
89
+ ? stored : (systemDark ? 'dark' : 'light'), false);
90
+ document.addEventListener('click', (event) => {
91
+ const button = event.target && event.target.closest
92
+ ? event.target.closest('.theme-toggle') : null;
93
+ if (!button) return;
94
+ apply(root.dataset.theme === 'dark' ? 'light' : 'dark', true);
95
+ });
96
+ // Click-to-copy for the email pill on the درباره ما page: async clipboard
97
+ // API first, execCommand fallback for non-secure contexts, and if both are
98
+ // blocked the address is selected with a "متن انتخاب شد" hint instead.
99
+ const legacyCopy = (text) => {
100
+ try {
101
+ const helper = document.createElement('textarea');
102
+ helper.value = text;
103
+ helper.setAttribute('readonly', '');
104
+ helper.style.position = 'fixed';
105
+ helper.style.opacity = '0';
106
+ document.body.appendChild(helper);
107
+ helper.select();
108
+ const ok = document.execCommand('copy');
109
+ document.body.removeChild(helper);
110
+ return ok;
111
+ } catch (error) { return false; }
112
+ };
113
+ const selectText = (node) => {
114
+ try {
115
+ const range = document.createRange();
116
+ range.selectNodeContents(node);
117
+ const selection = window.getSelection();
118
+ selection.removeAllRanges();
119
+ selection.addRange(range);
120
+ return true;
121
+ } catch (error) { return false; }
122
+ };
123
+ document.addEventListener('click', (event) => {
124
+ const button = event.target && event.target.closest
125
+ ? event.target.closest('.copy-email') : null;
126
+ if (!button) return;
127
+ const email = button.getAttribute('data-email') || '';
128
+ const done = () => {
129
+ button.classList.add('copied');
130
+ window.setTimeout(() => button.classList.remove('copied'), 1800);
131
+ };
132
+ const fallback = () => {
133
+ if (legacyCopy(email)) { done(); return; }
134
+ const node = button.querySelector('bdi');
135
+ if (node) selectText(node);
136
+ button.classList.add('copy-failed');
137
+ window.setTimeout(() => button.classList.remove('copy-failed'), 2400);
138
+ };
139
+ if (navigator.clipboard && navigator.clipboard.writeText) {
140
+ navigator.clipboard.writeText(email).then(done).catch(fallback);
141
+ } else {
142
+ fallback();
143
+ }
144
+ });
145
+ const statusBox = () => document.getElementById('upload-status-box');
146
+ const micStatusBox = () => document.getElementById('mic-upload-status-box');
147
+
148
+ // File picker: show immediately after the user chooses a file, then let
149
+ // the existing file-preview observer hide it once Gradio finishes upload.
150
+ document.addEventListener('change', (event) => {
151
+ const input = event.target;
152
+ if (input && input.type === 'file' && input.closest &&
153
+ input.closest('#upload-audio')) {
154
+ const box = statusBox();
155
+ if (box) box.removeAttribute('hidden');
156
+ }
157
+ });
158
+
159
+ const hideWhenUploaded = () => {
160
+ const box = statusBox();
161
+ const zone = document.getElementById('upload-audio');
162
+ if (!box || !zone) return;
163
+ if (zone.querySelector('[data-testid="file"], .file-preview, .uploaded-file')) {
164
+ box.setAttribute('hidden', '');
165
+ }
166
+ };
167
+
168
+ // Microphone: show the status when the user stops recording. The Python
169
+ // completion callback returns fresh hidden HTML after Gradio has delivered
170
+ // the uploaded filepath; the data-cycle nonce forces a DOM replacement.
171
+ let micIsRecording = false;
172
+ document.addEventListener('click', (event) => {
173
+ const button = event.target && event.target.closest
174
+ ? event.target.closest('#record-audio button') : null;
175
+ if (!button) return;
176
+
177
+ const label = [
178
+ button.getAttribute('aria-label') || '',
179
+ button.getAttribute('title') || '',
180
+ button.getAttribute('data-testid') || '',
181
+ button.className || '',
182
+ button.textContent || ''
183
+ ].join(' ').toLowerCase();
184
+
185
+ const isStart = button.classList.contains('record-button') ||
186
+ label.includes('start recording') || label.includes('record audio');
187
+ const isStop = button.classList.contains('stop-button') ||
188
+ label.includes('stop recording');
189
+
190
+ if (isStart) {
191
+ micIsRecording = true;
192
+ const box = micStatusBox();
193
+ if (box) box.setAttribute('hidden', '');
194
+ return;
195
+ }
196
+
197
+ if (isStop && micIsRecording) {
198
+ micIsRecording = false;
199
+ const box = micStatusBox();
200
+ if (box) box.removeAttribute('hidden');
201
+ }
202
+ }, true);
203
+
204
+ const attach = () => {
205
+ const zone = document.getElementById('upload-audio');
206
+ if (!zone) {
207
+ const studio = document.getElementById('studio');
208
+ if (studio && studio.dataset.theme !== root.dataset.theme) {
209
+ studio.dataset.theme = root.dataset.theme;
210
+ }
211
+ window.setTimeout(attach, 400);
212
+ return;
213
+ }
214
+ new MutationObserver(hideWhenUploaded)
215
+ .observe(zone, { childList: true, subtree: true });
216
+ };
217
+ attach();
218
+ }"""
219
+
220
+ UPLOAD_STATUS_HIDDEN = (
221
+ '<div class="upload-status" id="upload-status-box" hidden>'
222
+ '<span class="dot" aria-hidden="true"></span>'
223
+ '<span>د�� حال آپلود فایل…</span>'
224
+ '</div>'
225
+ )
226
+
227
+ MIC_UPLOAD_STATUS_HIDDEN = (
228
+ '<div class="upload-status" id="mic-upload-status-box" hidden>'
229
+ '<span class="dot" aria-hidden="true"></span>'
230
+ '<span>در حال آماده‌سازی و آپلود صدای ضبط‌شده…</span>'
231
+ '</div>'
232
+ )
233
+
234
+
235
+ def hidden_status_markup(element_id: str, message: str) -> str:
236
+ """Return a fresh hidden status element.
237
+
238
+ The unique data-cycle value is intentional: JavaScript may show the current
239
+ element by removing its `hidden` attribute. Returning the original static
240
+ HTML string can be treated by Gradio as an unchanged component value, so
241
+ React may leave the manually-shown DOM element visible. A fresh value forces
242
+ Gradio to render a new hidden element after each completed upload.
243
+ """
244
+ return (
245
+ f'<div class="upload-status" id="{element_id}" '
246
+ f'data-cycle="{uuid4().hex}" hidden>'
247
+ '<span class="dot" aria-hidden="true"></span>'
248
+ f'<span>{escape(message)}</span>'
249
+ '</div>'
250
+ )
251
+
252
+
253
+ def icon(key, cls=""):
254
+ cls_attr = f' class="{cls}"' if cls else ""
255
+ return (
256
+ '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" '
257
+ f'stroke-width="1.55" stroke-linejoin="round" stroke-linecap="round"{cls_attr}>'
258
+ f'{ICONS[key]}</svg>'
259
+ )
260
+
261
+
262
+ def heading(key, title):
263
+ return f'<div class="section-title"><span>{icon(key)}</span><h2>{title}</h2></div>'
264
+
265
+
266
+ def theme_button():
267
+ return (
268
+ '<button class="theme-toggle" type="button" '
269
+ 'aria-label="تغییر حالت روشن و تاریک" title="تغییر حالت روشن و تاریک">'
270
+ f'{icon("moon", "icon-moon")}{icon("sun", "icon-sun")}'
271
+ '</button>'
272
+ )
273
+
274
+
275
+ def data_url(filename, mime):
276
+ encoded = b64encode((ASSETS / filename).read_bytes()).decode("ascii")
277
+ return f"data:{mime};base64,{encoded}"
278
+
279
+
280
+ def university_logo_url():
281
+ if ASSETS.is_dir():
282
+ for name in LOGO_CANDIDATES:
283
+ path = ASSETS / name
284
+ if path.is_file():
285
+ return data_url(name, LOGO_MIME.get(path.suffix.lower(), "image/png"))
286
+ others = [p for p in ASSETS.iterdir()
287
+ if p.is_file() and p.suffix.lower() in LOGO_MIME and p.name != "contours.png"]
288
+ if len(others) == 1:
289
+ return data_url(others[0].name, LOGO_MIME[others[0].suffix.lower()])
290
+ return ""
291
+
292
+
293
+ def email_button():
294
+ return (
295
+ f'<button type="button" class="copy-email" data-email="{CONTACT_EMAIL}" '
296
+ 'title="برای رونوشت ایمیل کلیک کنید">'
297
+ f'{COPY_ICON}{CHECK_ICON}'
298
+ f'<bdi dir="ltr">{CONTACT_EMAIL}</bdi>'
299
+ '<span class="copy-msg msg-ok">کپی شد</span>'
300
+ '<span class="copy-msg msg-fail">متن انتخاب شد</span>'
301
+ '</button>'
302
+ )
303
+
304
+
305
+ def about_page():
306
+ logo = university_logo_url()
307
+ logo_html = f'<img class="univ-logo" src="{logo}" alt="نشان دانشگاه اصفهان">' if logo else ""
308
+ return f'''<div class="about-wrap" lang="fa" dir="rtl">
309
+ <div class="about-topbar">
310
+ {theme_button()}
311
+ </div>
312
+ <p class="about-lead">این سامانهٔ بازشناسی گفتار فارسی در دانشگاه اصفهان توسعه یافته است.</p>
313
+ <div class="about-grid">
314
+ <section class="about-card">
315
+ <h3>مجری طرح</h3>
316
+ <p class="person">دکتر حمیدرضا برادران</p>
317
+ <p class="affiliation">دانشگاه اصفهان</p>
318
+ {email_button()}
319
+ </section>
320
+ <section class="about-card">
321
+ <h3>همکار</h3>
322
+ <p class="person">پروفسور علیرضا درویشی</p>
323
+ <p class="affiliation">دانشگاه اصفهان</p>
324
+ </section>
325
+ <section class="about-card">
326
+ <h3>اعضای تیم</h3>
327
+ <ul class="team-list">
328
+ <li>هاجر مظاهری</li>
329
+ <li>سیدمحمدسروش سجادی</li>
330
+ <li>آیدا سرابی</li>
331
+ </ul>
332
+ </section>
333
+ </div>
334
+ <div class="univ-block">
335
+ {logo_html}
336
+ <p class="univ-name">دانشگاه اصفهان</p>
337
+ </div>
338
+ <footer class="about-footer">
339
+ <p>© تمامی حقوق محفوظ است · <bdi dir="ltr">All rights reserved.</bdi></p>
340
+ </footer>
341
+ </div>'''
342
+
343
+
344
+ def header(preview):
345
+ badge = '<span class="demo-label" lang="en">Demo</span>' if preview else ""
346
+ return f'''<header class="masthead" lang="fa" dir="rtl">
347
+ {theme_button()}
348
+ <div class="intro">
349
+ <div class="brand"><i></i><bdi>Persian Conformer ASR</bdi>{badge}</div>
350
+ <h1>بازشناسی گفتار فارسی</h1>
351
+ <p>صدا را انتخاب کنید، متن بازشناسی‌شده را بخوانید و عملکرد مدل را بررسی کنید.</p>
352
+ </div>
353
+ <img alt="" class="contours" src="{data_url("contours.png", "image/png")}">
354
+ </header>'''
355
+
356
+
357
+ def entries(items, css="facts"):
358
+ return '<dl class="' + css + '">' + "".join(
359
+ '<div><dt>' + escape(label) + '</dt><dd><bdi>' + escape(str(value)) +
360
+ '</bdi></dd></div>' for label, value in items
361
+ ) + '</dl>'
362
+
363
+
364
+ def sample_files():
365
+ return {title: filename for title, filename, _ in SAMPLES if (ASSETS / filename).is_file()}
366
+
367
+
368
+ def sample_choices():
369
+ # Radio choices with duration when the file is a plain wav (mp3/flac still
370
+ # play fine, they just lack a duration). The dataset name is intentionally
371
+ # left out of the label; sample_note() reports it after a clip is chosen.
372
+ choices = []
373
+ for title, filename, _ in SAMPLES:
374
+ path = ASSETS / filename
375
+ if not path.is_file():
376
+ continue
377
+ try:
378
+ with wave.open(str(path)) as audio:
379
+ seconds = audio.getnframes() / audio.getframerate()
380
+ choices.append((f"{title} · {seconds:.1f} ثانیه", title))
381
+ except Exception:
382
+ choices.append((title, title))
383
+ return choices
384
+
385
+
386
+ def sample_note(selected=None):
387
+ # Caption under the sample list: a neutral line until a clip is chosen,
388
+ # then the dataset the selected clip comes from. Bound to sample.change so
389
+ # programmatic resets (tab switches, پاک کردن, player.clear) restore it too.
390
+ datasets = {title: dataset for title, _, dataset in SAMPLES}
391
+ dataset = datasets.get(selected)
392
+ if dataset:
393
+ return f'<p class="note">این گفتار از مجموعهٔ <bdi>{escape(dataset)}</bdi> است</p>'
394
+ return '<p class="note">گفتارهای فارسی آمادهٔ انتخاب</p>'
395
+
396
+
397
+ def model_details(catalog, config, name, model_info):
398
+ cfg = replace(config, **catalog[name].get("config", {}))
399
+ # Keep native English API metadata intact, including measured parameter count.
400
+ raw = model_info(name) if model_info else ""
401
+ param = re.search(r"\*\*Parameters:\*\* ([\d.]+ M)", raw)
402
+ items = [
403
+ ("معماری", catalog[name].get("description") or name),
404
+ ("پارامترها", param.group(1) if param else "پس از بارگیری مدل"),
405
+ ("بُعد رمزگذار", cfg.encoder_dim), ("سرهای توجه", cfg.nhead),
406
+ ("رمزگذار بازگشتی", "بله" if cfg.use_recurrence else "خیر"),
407
+ ]
408
+ if cfg.use_recurrence:
409
+ items.append(("تعداد تکرار", cfg.max_loops if cfg.max_loops > 0 else cfg.num_loops))
410
+ items.extend([
411
+ ("بازخورد CTC", "فعال" if cfg.use_ctc_feedback else "غیرفعال"),
412
+ ("رمزگشا", f"k2 · {cfg.method}"), ("پردازندهٔ پیکربندی‌شده", "CPU"),
413
+ ])
414
+ return entries(items)
415
+
416
+
417
+ def performance(report=""):
418
+ fields = dict(line.split(": ", 1) for line in (report or "").splitlines() if ": " in line)
419
+ # Only the total numbers: input duration, total processing time and RTF.
420
+ metrics = [
421
+ ("مدت صوت", "Audio duration"),
422
+ ("زمان پردازش کل", "End-to-end processing"),
423
+ ("RTF کل", "End-to-end RTF"),
424
+ ]
425
+ html = entries([(label, fields.get(key, "—")) for label, key in metrics], "metrics")
426
+ if fields:
427
+ secondary = [
428
+ ("مدل", "Model"), ("پردازنده", "Device"),
429
+ ("نرخ نمونه‌برداری ورودی", "Original sample rate"), ("تعداد کانال", "Channels"),
430
+ ]
431
+ html += entries([(label, fields[key]) for label, key in secondary if key in fields])
432
+ else:
433
+ html += '<p class="note">مقادیر پس از اجرای موفق بازشناسی نمایش داده می‌شوند.</p>'
434
+ return html
435
+
436
+
437
+ def build_dashboard(catalog, config, *, select_model=None, model_info=None,
438
+ transcribe=None, gpu_handler=None):
439
+ preview = transcribe is None
440
+ default = next(iter(catalog))
441
+ empty_report = performance()
442
+ selection_hint = "مدل هنگام اجرای بازشناسی در حافظه بارگیری می‌شود."
443
+ if preview:
444
+ selection_hint = "پیش‌نمایش Demo فعال است. می‌توانید ورودی و پخش صدا را بررسی کنید."
445
+ empty_hint = '<p class="player-empty">برای پخش، ابتدا یک صدا انتخاب یا ضبط کنید.</p>'
446
+
447
+ blocks_kwargs = {} if LAUNCH_ACCEPTS_JS else {"js": THEME_JS}
448
+ with gr.Blocks(title="بازشناسی گفتار فارسی · Persian Conformer ASR",
449
+ **blocks_kwargs) as demo:
450
+ with gr.Column(elem_id="studio"):
451
+ with gr.Tabs(elem_id="main-tabs"):
452
+ with gr.Tab("خانه", elem_id="tab-home"):
453
+ gr.HTML(header(preview), container=False)
454
+ with gr.Column(elem_classes=["surface", "settings"]):
455
+ with gr.Row(elem_classes=["model-row"]):
456
+ with gr.Column(min_width=220):
457
+ gr.HTML(heading("model", "مدل بازشناسی"), container=False)
458
+ status = gr.Markdown(selection_hint, elem_classes=["model-note"])
459
+ model = gr.Dropdown(list(catalog), value=default, label="انتخاب مدل", interactive=True,
460
+ filterable=False, elem_id="model-select", min_width=210)
461
+ with gr.Accordion("مشخصات فنی مدل", open=False, elem_id="technical"):
462
+ info = gr.HTML(model_details(catalog, config, default, model_info), container=False)
463
+
464
+ with gr.Row(elem_id="desk", equal_height=False):
465
+ with gr.Column(scale=11, min_width=320, elem_classes=["surface", "source-card"]):
466
+ gr.HTML(heading("input", "ورودی صوتی"), container=False)
467
+ source_tabs_kwargs = {"elem_id": "sources"}
468
+ if "overflow_behavior" in inspect.signature(gr.Tabs.__init__).parameters:
469
+ source_tabs_kwargs["overflow_behavior"] = "wrap"
470
+ with gr.Tabs(**source_tabs_kwargs):
471
+ with gr.Tab("بارگذاری فایل") as upload_tab:
472
+ uploaded = gr.File(file_types=["audio"], type="filepath", label="انتخاب فایل صوتی",
473
+ show_label=False, height=118, elem_id="upload-audio")
474
+ upload_status = gr.HTML(UPLOAD_STATUS_HIDDEN, container=False,
475
+ elem_id="upload-status")
476
+ with gr.Tab("ضبط صدا") as mic_tab:
477
+ recorded = gr.Audio(sources=["microphone"], type="filepath", label="ضبط با میکروفون",
478
+ show_label=False, interactive=True, elem_id="record-audio")
479
+ mic_upload_status = gr.HTML(MIC_UPLOAD_STATUS_HIDDEN, container=False,
480
+ elem_id="mic-upload-status")
481
+ with gr.Tab("نمونه‌های آماده") as examples_tab:
482
+ gr.HTML('<p class="radio-head">انتخاب گفتار فارسی</p>', container=False)
483
+ sample = gr.Radio(choices=sample_choices(), label="انتخاب گفتار فارسی",
484
+ show_label=False, value=None, elem_id="sample-list")
485
+ sample_caption = gr.HTML(sample_note(), container=False)
486
+ def limit_text(name):
487
+ cfg = replace(config, **catalog[name].get("config", {}))
488
+ return f'<p class="note">حداکثر مدت ورودی این مدل: {cfg.max_audio_seconds:g} ثانیه</p>'
489
+ limit = gr.HTML(limit_text(default), container=False)
490
+ gr.HTML('<h3 class="subhead">پخش و بازشناسی</h3>', container=False)
491
+ placeholder = gr.HTML(empty_hint, container=False)
492
+ # Automatically show the selected audio in the player.
493
+ # The original server filepath is also kept in gr.State
494
+ # and passed directly to inference (no browser re-upload).
495
+ player = gr.Audio(type="filepath", sources=[], label="صدای انتخاب‌شده",
496
+ show_label=False, interactive=False, visible=False,
497
+ elem_id="shared-player")
498
+ with gr.Row(elem_classes=["actions"]):
499
+ run = gr.Button("اجرای بازشناسی", variant="primary", interactive=False, scale=3)
500
+ clear = gr.Button("پاک کردن", interactive=False, scale=1)
501
+ with gr.Column(scale=10, min_width=310, elem_id="results"):
502
+ with gr.Column(elem_classes=["surface"]):
503
+ gr.HTML(heading("text", "متن بازشناسی‌شده"), container=False)
504
+ text = gr.Textbox(lines=3, rtl=True, label="متن بازشناسی‌شده", show_label=False,
505
+ interactive=False, elem_id="transcript",
506
+ placeholder="متن فارسی پس از بازشناسی اینجا نمایش داده می‌شود.")
507
+ with gr.Column(elem_classes=["surface"]):
508
+ gr.HTML(heading("performance", "عملکرد مدل"), container=False)
509
+ report = gr.HTML(empty_report, container=False)
510
+
511
+ with gr.Tab("درباره ما", elem_id="tab-about"):
512
+ gr.HTML(about_page(), container=False)
513
+
514
+ audio_state = gr.State(None)
515
+ last_tab = gr.State(None)
516
+
517
+ # Transcription stays on the single serial queue; light UI updates run
518
+ # without queueing so the input menus never freeze behind a running job.
519
+ events = dict(concurrency_id="asr-dashboard", concurrency_limit=1, api_visibility="private",
520
+ show_progress="hidden")
521
+ ui_events = dict(api_visibility="private", show_progress="hidden", queue=False)
522
+ outputs = [player, placeholder, run, clear, text, report, audio_state]
523
+
524
+ def choose_audio(path):
525
+ ready = bool(path)
526
+ # Always populate the player when a file is ready, while retaining
527
+ # the original server filepath in gr.State for direct inference.
528
+ return (gr.update(value=path, visible=ready), gr.update(visible=not ready),
529
+ gr.update(interactive=ready and not preview),
530
+ gr.update(interactive=ready), "", empty_report, path)
531
+
532
+ def choose_sample(title):
533
+ files = sample_files()
534
+ return choose_audio(str(ASSETS / files[title]) if title in files else None)
535
+
536
+ def on_upload(path):
537
+ # Gradio calls this after the uploaded file has reached the server.
538
+ # Return a fresh hidden status markup so a prior JS visibility change
539
+ # cannot leave the uploading message stuck on screen.
540
+ return (*choose_audio(path), gr.update(value=None),
541
+ gr.update(value=hidden_status_markup(
542
+ "upload-status-box", "در حال آپلود فایل…")))
543
+
544
+ def on_record(path):
545
+ # stop_recording supplies the completed server-side filepath. The
546
+ # fresh hidden markup forces the microphone status to disappear.
547
+ return (*choose_audio(path), gr.update(value=None),
548
+ gr.update(value=hidden_status_markup(
549
+ "mic-upload-status-box", "در حال آماده‌سازی و آپلود صدای ضبط‌شده…")))
550
+
551
+ uploaded.upload(on_upload, uploaded, outputs + [uploaded, upload_status], **ui_events)
552
+ recorded.stop_recording(
553
+ on_record, recorded, outputs + [recorded, mic_upload_status], **ui_events
554
+ )
555
+
556
+ def hide_mic_status_when_value_arrives(path):
557
+ # Some Gradio/browser combinations update the Audio value in a
558
+ # separate input event after stop_recording. Only hide the status
559
+ # when a real filepath has arrived; ignore empty/reset events.
560
+ if path:
561
+ return gr.update(value=hidden_status_markup(
562
+ "mic-upload-status-box",
563
+ "در حال آماده‌سازی و آپلود صدای ضبط‌شده…",
564
+ ))
565
+ return gr.skip()
566
+
567
+ recorded.input(
568
+ hide_mic_status_when_value_arrives,
569
+ recorded,
570
+ mic_upload_status,
571
+ **ui_events,
572
+ )
573
+
574
+ sample.input(choose_sample, sample, outputs, **ui_events)
575
+ # .change (not .input) so the caption also resets when the selection is
576
+ # cleared programmatically by the tab switches and the reset flows.
577
+ sample.change(sample_note, sample, sample_caption, **ui_events)
578
+
579
+ def make_tab_switch(name):
580
+ def switch(last):
581
+ if last == name:
582
+ # Clicking the already-active tab keeps the current selection.
583
+ return [gr.skip()] * len(outputs) + [gr.update()] * 6
584
+ # Switching tabs clears the selected audio, results and both
585
+ # upload indicators to avoid leaving a stale status visible.
586
+ return (*choose_audio(None), gr.update(value=None), gr.update(value=None),
587
+ gr.update(value=None), name,
588
+ gr.update(value=hidden_status_markup(
589
+ "upload-status-box", "در حال آپلود فایل…")),
590
+ gr.update(value=hidden_status_markup(
591
+ "mic-upload-status-box", "در حال آماده‌سازی و آپلود صدای ضبط‌شده…")))
592
+ return switch
593
+
594
+ for tab, name in ((upload_tab, "upload"), (mic_tab, "record"), (examples_tab, "samples")):
595
+ tab.select(
596
+ make_tab_switch(name), last_tab,
597
+ outputs + [uploaded, recorded, sample, last_tab, upload_status, mic_upload_status],
598
+ **ui_events,
599
+ )
600
+
601
+ def reset():
602
+ return (*choose_audio(None), None, None, None,
603
+ gr.update(value=hidden_status_markup(
604
+ "upload-status-box", "در حال آپلود فایل…")),
605
+ gr.update(value=hidden_status_markup(
606
+ "mic-upload-status-box", "در حال آماده‌سازی و آپلود صدای ضبط‌شده…")))
607
+
608
+ clear.click(
609
+ reset, None,
610
+ outputs + [uploaded, recorded, sample, upload_status, mic_upload_status],
611
+ **ui_events,
612
+ )
613
+ recorded.clear(
614
+ reset, None,
615
+ outputs + [uploaded, recorded, sample, upload_status, mic_upload_status],
616
+ **ui_events,
617
+ )
618
+
619
+ def change_model(name):
620
+ # Instant, local-only refresh: the hub download happens lazily on the
621
+ # first transcription, so switching models never blocks the interface.
622
+ if preview:
623
+ message = selection_hint
624
+ else:
625
+ message = f"مدل «{name}» انتخاب شد؛ در اولین اجرای بازشناسی بارگیری می‌شود."
626
+ return message, model_details(catalog, config, name, model_info), limit_text(name), "", empty_report
627
+
628
+ model.input(change_model, model, [status, info, limit, text, report], **ui_events)
629
+
630
+ if not preview:
631
+ def recognize(path, name):
632
+ yield "", empty_report, gr.skip(), gr.skip()
633
+ words, stats = transcribe(path, name)
634
+ yield (words, performance(stats), model_details(catalog, config, name, model_info),
635
+ "مدل انتخاب‌شده در حافظه آمادهٔ بازشناسی است.")
636
+
637
+ run.click(recognize, [audio_state, model], [text, report, info, status],
638
+ **{**events, "show_progress": "minimal"})
639
+
640
+ # Preserve the original Gradio client endpoints and their two string outputs.
641
+ api_text = gr.Textbox(visible=False)
642
+ api_report = gr.Textbox(visible=False)
643
+ for handler in (transcribe, gpu_handler):
644
+ if handler:
645
+ gr.Button(visible=False).click(handler, [audio_state, model], [api_text, api_report],
646
+ api_name=handler.__name__, concurrency_id="asr-dashboard", concurrency_limit=1)
647
+ gr.Button(visible=False).click(select_model, model, [api_text, api_report],
648
+ api_name="select_model", concurrency_id="asr-dashboard", concurrency_limit=1)
649
+ return demo.queue(default_concurrency_limit=1)
650
+
651
+
652
+ def launch_dashboard(demo, **kwargs):
653
+ css = (ASSETS / "studio.css").read_text("utf-8").replace(
654
+ "__FONT__", data_url("Vazirmatn.ttf", "font/ttf"))
655
+ # Use Gradio Font objects for every fallback. Some Gradio versions compare
656
+ # custom themes against built-in themes during launch; mixing Font objects
657
+ # and plain strings in the internal font lists can raise
658
+ # AttributeError: 'str' object has no attribute 'name'.
659
+ # The actual Vazirmatn font is still supplied by studio.css via __FONT__.
660
+ theme = gr.themes.Base(
661
+ primary_hue="teal",
662
+ neutral_hue="slate",
663
+ font=[
664
+ gr.themes.Font("Vazirmatn"),
665
+ gr.themes.Font("Tahoma"),
666
+ gr.themes.Font("sans-serif"),
667
+ ],
668
+ font_mono=[
669
+ gr.themes.Font("Consolas"),
670
+ gr.themes.Font("monospace"),
671
+ ],
672
+ )
673
+ if LAUNCH_ACCEPTS_JS:
674
+ demo.launch(theme=theme, css=css, allowed_paths=[str(ASSETS)], js=THEME_JS, **kwargs)
675
+ else:
676
+ demo.launch(theme=theme, css=css, allowed_paths=[str(ASSETS)], **kwargs)
dashboard_assets/CREDITS.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Audio samples
2
+
3
+ Three Persian recordings from FLEURS, Google and the FLEURS contributors, Persian (fa_ir), development split. Dataset release by Conneau et al., 2022. Distributed under the [Creative Commons Attribution 4.0 International license](https://creativecommons.org/licenses/by/4.0/).
4
+
5
+ The clips are complete utterances. The dashboard files were converted from 32-bit float WAV to 16-bit PCM WAV, retaining the original 16 kHz mono sampling and duration. The Persian labels in the selector describe the topics.
6
+
7
+ | Dashboard file | Original recording | Sentence ID |
8
+ | --- | --- | --- |
9
+ | polo.wav | 10049006222377318397.wav | 1567 |
10
+ | travel.wav | 10097326041910827097.wav | 1645 |
11
+ | hotel.wav | 10242821013991758239.wav | 1657 |
12
+
13
+ [Dataset card](https://huggingface.co/datasets/google/fleurs/blob/70bb2e84b976b7e960aa89f1c648e09c59f894dd/README.md) · [Audio and metadata](https://huggingface.co/datasets/google/fleurs/tree/70bb2e84b976b7e960aa89f1c648e09c59f894dd/data/fa_ir)
14
+
15
+ # Typeface
16
+
17
+ Vazirmatn by the Vazirmatn project authors, distributed under the SIL Open Font License 1.1. The original license is included in FONT-LICENSE.txt. [Vazirmatn](https://github.com/rastikerdar/vazirmatn)
dashboard_assets/FONT-LICENSE.txt ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2015 The Vazirmatn Project Authors (https://github.com/rastikerdar/vazirmatn)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
dashboard_assets/Vazirmatn.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:696249a2c74b39ffdef55de4df2809c5b639d3ff80d618d8160a095d2fd49dca
3
+ size 241328
dashboard_assets/baradar_shahid.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94dbbcac1e0fb86a10ea516a6d7c2c14ff48b3bc640c24e7596bc705f7cfe3c7
3
+ size 543824
dashboard_assets/contours.png ADDED

Git LFS Details

  • SHA256: 40eca25602c16b0d497a600c5774996ee328736d6a283ce08e0ffb41f5ac3f61
  • Pointer size: 131 Bytes
  • Size of remote file: 343 kB
dashboard_assets/hotel.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:debb513b816ad696c4749ed2a0cf4b7e99965a2b2c9ce1f1dcb64226fb5abfff
3
+ size 472364
dashboard_assets/polo.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52c5974e7fb5c42df36618c66f2138480a6f766f5f444beab3f2bdeb0b4d5816
3
+ size 305358
dashboard_assets/studio.css ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @font-face {
2
+ font-family: Vazirmatn;
3
+ src: url("__FONT__") format("truetype");
4
+ font-weight: 100 900;
5
+ font-display: swap;
6
+ }
7
+
8
+ /* ---------------------------------------------------------------------------
9
+ Theme variables. The theme lives on <html data-theme="light|dark"> and is
10
+ mirrored onto #studio by THEME_JS (dashboard.py): the toggle initialises it
11
+ from localStorage or the browser theme at first paint. The custom-property
12
+ blocks below are kept declaration-only because Gradio 6 scopes any other
13
+ rule under .gradio-container, which would break html-level selectors.
14
+ --------------------------------------------------------------------------- */
15
+ :root {
16
+ --page-bg: #f3f6f6;
17
+ --text: #183738;
18
+ --muted: #536e70;
19
+ --surface: #ffffff;
20
+ --surface-2: #f3f7f6;
21
+ --surface-border: #d7e2df;
22
+ --accent: #0d7069;
23
+ --accent-strong: #105e54;
24
+ --accent-soft: #e2f2ee;
25
+ --input-bg: #ffffff;
26
+ --input-border: #bccfca;
27
+ --btn-primary-bg: #126b62;
28
+ --btn-primary-bg-hover: #0c534e;
29
+ --btn-primary-text: #ffffff;
30
+ --btn-secondary-bg: #f2f6f4;
31
+ --btn-secondary-text: #355754;
32
+ --icon-bg: #eef7f3;
33
+ --icon-border: #cce4dc;
34
+ --icon-color: #126c60;
35
+ --heading: #173936;
36
+ --note: #536c66;
37
+ --accordion: #345753;
38
+ --combo-bg: #f4f8f6;
39
+ --combo-border: #c2d8d1;
40
+ --popup-bg: #ffffff;
41
+ --popup-border: #d7e2dd;
42
+ --option-hover: #eef6f2;
43
+ --tablist-bg: #edf3f0;
44
+ --tab-text: #506963;
45
+ --tab-active-text: #105e54;
46
+ --tab-active-bg: #ffffff;
47
+ --upload-border: #a5c5bb;
48
+ --upload-bg: #f8fbfa;
49
+ --status-bg: #e2f2ee;
50
+ --status-border: #bfe0d4;
51
+ --status-text: #0c4f48;
52
+ --chip-border: #dce8e3;
53
+ --chip-bg: #ffffff;
54
+ --chip-hover-bg: #eef6f2;
55
+ --chip-hover-border: #9ecdbc;
56
+ --chip-active-bg: #e2f2ee;
57
+ --chip-active-border: #126c60;
58
+ --chip-text: #284b45;
59
+ --chip-active-text: #0b453f;
60
+ --subhead: #1c4039;
61
+ --subhead-border: #e2eae7;
62
+ --empty-bg: #f3f7f5;
63
+ --empty-text: #567069;
64
+ --transcript-bg: #f9fbfa;
65
+ --transcript-border: #dde7e2;
66
+ --transcript-text: #183e35;
67
+ --placeholder: #677e77;
68
+ --card-border: #e1eae6;
69
+ --card-bg: #f7faf8;
70
+ --dt: #526b63;
71
+ --dd: #193e35;
72
+ --facts-border: #e3ebe8;
73
+ --focus: #137e71;
74
+ --shadow-soft: 0 2px 5px #16372d06;
75
+ --shadow-popup: 0 10px 30px #16372d1f;
76
+ --masthead-bg: linear-gradient(105deg, #164e53, #103b40 52%, #0b2e32);
77
+ --masthead-dot: #c4eeec38;
78
+ --masthead-text-muted: #d6e7e3;
79
+ --brand-text: #f2f9f7;
80
+ --brand-line: #76d9c1;
81
+ --brand-muted: #b3e7dc;
82
+ --demo-border: #75a59d;
83
+ --demo-text: #d4eee9;
84
+ --toggle-focus: #7fe6cc;
85
+ --contour-filter: none;
86
+ }
87
+
88
+ html[data-theme="dark"] {
89
+ --page-bg: #0a1120;
90
+ --text: #d8e2f2;
91
+ --muted: #95a8c6;
92
+ --surface: #121f36;
93
+ --surface-2: #0e1728;
94
+ --surface-border: #25395c;
95
+ --accent: #5b8def;
96
+ --accent-strong: #85b1ff;
97
+ --accent-soft: #16263f;
98
+ --input-bg: #0e1a2e;
99
+ --input-border: #2c4265;
100
+ --btn-primary-bg: #2563eb;
101
+ --btn-primary-bg-hover: #1d4ed8;
102
+ --btn-primary-text: #eaf2ff;
103
+ --btn-secondary-bg: #152238;
104
+ --btn-secondary-text: #b9cbe8;
105
+ --icon-bg: #14233c;
106
+ --icon-border: #2b4a75;
107
+ --icon-color: #6ea3ff;
108
+ --heading: #e2ebf8;
109
+ --note: #9db0ca;
110
+ --accordion: #a7bad6;
111
+ --combo-bg: #101d33;
112
+ --combo-border: #2c4265;
113
+ --popup-bg: #121f36;
114
+ --popup-border: #2c4265;
115
+ --option-hover: #1a2c4c;
116
+ --tablist-bg: #101d33;
117
+ --tab-text: #95a8c6;
118
+ --tab-active-text: #8ab5ff;
119
+ --tab-active-bg: #1a2c4c;
120
+ --upload-border: #35517e;
121
+ --upload-bg: #0e1a2e;
122
+ --status-bg: #16263f;
123
+ --status-border: #2b4a75;
124
+ --status-text: #9cc2ff;
125
+ --chip-border: #25395c;
126
+ --chip-bg: #101d33;
127
+ --chip-hover-bg: #142640;
128
+ --chip-hover-border: #3a63a3;
129
+ --chip-active-bg: #16263f;
130
+ --chip-active-border: #4179e6;
131
+ --chip-text: #c1d2ec;
132
+ --chip-active-text: #a6c8ff;
133
+ --subhead: #d2dff0;
134
+ --subhead-border: #1f3255;
135
+ --empty-bg: #101d33;
136
+ --empty-text: #9db0ca;
137
+ --transcript-bg: #0e1a2e;
138
+ --transcript-border: #23385c;
139
+ --transcript-text: #e0eafa;
140
+ --placeholder: #8296b4;
141
+ --card-border: #1f3255;
142
+ --card-bg: #101d33;
143
+ --dt: #95a8c6;
144
+ --dd: #e3ecf9;
145
+ --facts-border: #1f3255;
146
+ --focus: #6ea3ff;
147
+ --shadow-soft: 0 2px 5px #00000052;
148
+ --shadow-popup: 0 12px 32px #00000066;
149
+ --masthead-bg: linear-gradient(105deg, #17375e, #112a4c 52%, #0b1d38);
150
+ --masthead-dot: #c9dcf738;
151
+ --masthead-text-muted: #c9d8ef;
152
+ --brand-text: #dbe7fb;
153
+ --brand-line: #8fb4ee;
154
+ --brand-muted: #c7d8f2;
155
+ --demo-border: #6c8cba;
156
+ --demo-text: #dbe6f8;
157
+ --toggle-focus: #9dbdf2;
158
+ --contour-filter: hue-rotate(42deg) saturate(.85);
159
+ }
160
+
161
+ @media (prefers-color-scheme: dark) {
162
+ html:not([data-theme]) { color-scheme: dark; }
163
+ html:not([data-theme]) {
164
+ --page-bg: #0a1120;
165
+ --text: #d8e2f2;
166
+ --muted: #95a8c6;
167
+ --surface: #121f36;
168
+ --surface-2: #0e1728;
169
+ --surface-border: #25395c;
170
+ --accent: #5b8def;
171
+ --accent-strong: #85b1ff;
172
+ --accent-soft: #16263f;
173
+ --input-bg: #0e1a2e;
174
+ --input-border: #2c4265;
175
+ --btn-primary-bg: #2563eb;
176
+ --btn-primary-bg-hover: #1d4ed8;
177
+ --btn-primary-text: #eaf2ff;
178
+ --btn-secondary-bg: #152238;
179
+ --btn-secondary-text: #b9cbe8;
180
+ --icon-bg: #14233c;
181
+ --icon-border: #2b4a75;
182
+ --icon-color: #6ea3ff;
183
+ --heading: #e2ebf8;
184
+ --note: #9db0ca;
185
+ --accordion: #a7bad6;
186
+ --combo-bg: #101d33;
187
+ --combo-border: #2c4265;
188
+ --popup-bg: #121f36;
189
+ --popup-border: #2c4265;
190
+ --option-hover: #1a2c4c;
191
+ --tablist-bg: #101d33;
192
+ --tab-text: #95a8c6;
193
+ --tab-active-text: #8ab5ff;
194
+ --tab-active-bg: #1a2c4c;
195
+ --upload-border: #35517e;
196
+ --upload-bg: #0e1a2e;
197
+ --status-bg: #16263f;
198
+ --status-border: #2b4a75;
199
+ --status-text: #9cc2ff;
200
+ --chip-border: #25395c;
201
+ --chip-bg: #101d33;
202
+ --chip-hover-bg: #142640;
203
+ --chip-hover-border: #3a63a3;
204
+ --chip-active-bg: #16263f;
205
+ --chip-active-border: #4179e6;
206
+ --chip-text: #c1d2ec;
207
+ --chip-active-text: #a6c8ff;
208
+ --subhead: #d2dff0;
209
+ --subhead-border: #1f3255;
210
+ --empty-bg: #101d33;
211
+ --empty-text: #9db0ca;
212
+ --transcript-bg: #0e1a2e;
213
+ --transcript-border: #23385c;
214
+ --transcript-text: #e0eafa;
215
+ --placeholder: #8296b4;
216
+ --card-border: #1f3255;
217
+ --card-bg: #101d33;
218
+ --dt: #95a8c6;
219
+ --dd: #e3ecf9;
220
+ --facts-border: #1f3255;
221
+ --focus: #6ea3ff;
222
+ --shadow-soft: 0 2px 5px #00000052;
223
+ --shadow-popup: 0 12px 32px #00000066;
224
+ --masthead-bg: linear-gradient(105deg, #17375e, #112a4c 52%, #0b1d38);
225
+ --masthead-dot: #c9dcf738;
226
+ --masthead-text-muted: #c9d8ef;
227
+ --brand-text: #dbe7fb;
228
+ --brand-line: #8fb4ee;
229
+ --brand-muted: #c7d8f2;
230
+ --demo-border: #6c8cba;
231
+ --demo-text: #dbe6f8;
232
+ --toggle-focus: #9dbdf2;
233
+ --contour-filter: hue-rotate(42deg) saturate(.85);
234
+ }
235
+ }
236
+
237
+ /* Gradio theme variables for elements rendered outside #studio (toasts). */
238
+ html[data-theme="dark"] {
239
+ --background-fill-primary: #121f36 !important;
240
+ --background-fill-secondary: #0e1728 !important;
241
+ --body-background-fill: #0a1120 !important;
242
+ --body-text-color: #d8e2f2 !important;
243
+ --block-background-fill: #121f36 !important;
244
+ --block-border-color: #25395c !important;
245
+ --border-color-primary: #25395c !important;
246
+ --input-background-fill: #0e1a2e !important;
247
+ --input-border-color: #2c4265 !important;
248
+ --block-label-text-color: #95a8c6 !important;
249
+ --block-title-text-color: #95a8c6 !important;
250
+ --color-accent: #5b8def !important;
251
+ --color-accent-soft: #16263f !important;
252
+ --button-primary-background-fill: #2563eb !important;
253
+ --button-primary-background-fill-hover: #1d4ed8 !important;
254
+ --button-primary-text-color: #eaf2ff !important;
255
+ --button-secondary-background-fill: #152238 !important;
256
+ --button-secondary-background-fill-hover: #1a2c4c !important;
257
+ --button-secondary-text-color: #b9cbe8 !important;
258
+ --panel-background-fill: #121f36 !important;
259
+ --loader-color: #5b8def !important;
260
+ }
261
+ @media (prefers-color-scheme: dark) {
262
+ html:not([data-theme]) {
263
+ --background-fill-primary: #121f36 !important;
264
+ --background-fill-secondary: #0e1728 !important;
265
+ --body-background-fill: #0a1120 !important;
266
+ --body-text-color: #d8e2f2 !important;
267
+ --block-background-fill: #121f36 !important;
268
+ --block-border-color: #25395c !important;
269
+ --border-color-primary: #25395c !important;
270
+ --input-background-fill: #0e1a2e !important;
271
+ --input-border-color: #2c4265 !important;
272
+ --block-label-text-color: #95a8c6 !important;
273
+ --block-title-text-color: #95a8c6 !important;
274
+ --color-accent: #5b8def !important;
275
+ --color-accent-soft: #16263f !important;
276
+ --button-primary-background-fill: #2563eb !important;
277
+ --button-primary-background-fill-hover: #1d4ed8 !important;
278
+ --button-primary-text-color: #eaf2ff !important;
279
+ --button-secondary-background-fill: #152238 !important;
280
+ --button-secondary-background-fill-hover: #1a2c4c !important;
281
+ --button-secondary-text-color: #b9cbe8 !important;
282
+ --panel-background-fill: #121f36 !important;
283
+ --loader-color: #5b8def !important;
284
+ }
285
+ }
286
+
287
+ :root, body, gradio-app, .gradio-container { background: var(--page-bg) !important; }
288
+ .gradio-container { width:100% !important; max-width: 1260px !important; margin-inline:auto !important; padding: 28px clamp(12px, 3vw, 44px) !important; }
289
+ .gradio-container .main.fillable { padding:0; }
290
+
291
+ #studio {
292
+ --body-text-color: var(--text);
293
+ --body-text-color-subdued: var(--muted);
294
+ --background-fill-primary: var(--surface);
295
+ --background-fill-secondary: var(--surface-2);
296
+ --block-background-fill: var(--surface);
297
+ --input-background-fill: var(--input-bg);
298
+ --input-border-color: var(--input-border);
299
+ --block-border-color: var(--surface-border);
300
+ --border-color-primary: var(--surface-border);
301
+ --color-accent: var(--accent);
302
+ --color-accent-soft: var(--accent-soft);
303
+ --block-label-text-color: var(--muted);
304
+ --block-title-text-color: var(--muted);
305
+ --button-primary-background-fill: var(--btn-primary-bg);
306
+ --button-primary-background-fill-hover: var(--btn-primary-bg-hover);
307
+ --button-primary-text-color: var(--btn-primary-text);
308
+ --button-secondary-background-fill: var(--btn-secondary-bg);
309
+ --button-secondary-background-fill-hover: var(--chip-hover-bg);
310
+ --button-secondary-text-color: var(--btn-secondary-text);
311
+ --button-secondary-border-color: transparent;
312
+ --panel-background-fill: var(--popup-bg);
313
+ --loader-color: var(--accent);
314
+ --waveform-options-background: var(--surface-2);
315
+ --waveform-options-waveform-color: var(--accent);
316
+ --waveform-options-playback-cursor-color: var(--accent);
317
+ --waveform-options-slider-color: var(--accent);
318
+ direction: rtl;
319
+ gap: 16px;
320
+ color: var(--text);
321
+ font-family: Vazirmatn, Tahoma, sans-serif;
322
+ transition: color .2s ease;
323
+ }
324
+ #studio *, #studio *::before, #studio *::after { box-sizing: border-box; }
325
+ #studio .html-container { padding:0; }
326
+ #studio .html-container, #studio .html-container > div, #studio .prose,
327
+ #studio .model-note, #studio #technical > button, #studio .section-title,
328
+ #studio .facts, #studio .metrics, #studio .note, #studio .player-empty,
329
+ #studio .subhead { direction:rtl; text-align:right; }
330
+
331
+ /* Masthead stays dark teal in both themes. */
332
+ #studio .masthead {
333
+ position: relative;
334
+ isolation: isolate;
335
+ overflow: hidden;
336
+ display: flex;
337
+ align-items: center;
338
+ min-height: 174px;
339
+ padding: 25px clamp(20px, 3.7vw, 52px);
340
+ background: var(--masthead-bg);
341
+ border-radius: 18px;
342
+ color: #fff;
343
+ }
344
+ #studio .masthead::before {
345
+ content:"";
346
+ position:absolute; inset:0; z-index:-2;
347
+ background-image: radial-gradient(var(--masthead-dot) .7px, transparent .9px);
348
+ background-size: 12px 12px;
349
+ mask-image: linear-gradient(90deg, black, transparent 64%);
350
+ }
351
+ #studio .intro { max-width: 64%; }
352
+ #studio .brand {
353
+ display: flex; align-items: center; gap: 10px; width: fit-content;
354
+ font: 600 12px/1.7 "Segoe UI", Arial, sans-serif; letter-spacing: .075em;
355
+ color: var(--brand-muted);
356
+ }
357
+ /* Explicit bdi rule: Gradio's own bdi color rule would otherwise override the
358
+ inherited brand color and render the English title dark in light mode. */
359
+ #studio .brand bdi { color: var(--brand-text); }
360
+ #studio .brand i { width: 17px; height: 2px; background:var(--brand-line); border-radius:2px; }
361
+ #studio .demo-label { border: 1px solid var(--demo-border); border-radius: 4px; padding: 0 5px; font-size: 10px; letter-spacing:.02em; color:var(--demo-text); }
362
+ #studio .masthead h1 { color:#fff; font: 750 clamp(29px, 3.5vw, 46px)/1.45 Vazirmatn,Tahoma,sans-serif; margin:6px 0 2px; }
363
+ #studio .masthead p { margin:0; color:var(--masthead-text-muted); line-height:1.9; font-size:14px; }
364
+ #studio .contours { position:absolute; left:-2.4%; top:50%; transform:translateY(-50%); width:44%; height:auto; z-index:-1; opacity:.9; mask-image:linear-gradient(90deg, transparent, black 12% 76%, transparent); filter: var(--contour-filter); }
365
+
366
+ /* Light/dark toggle in the masthead and on the درباره ما page: square tile
367
+ with the icon exactly centered. The data-theme attribute is mirrored onto
368
+ #studio by the on-load JS, so the icon swap works inside Gradio's scoped
369
+ CSS pipeline. */
370
+ #studio .theme-toggle {
371
+ position:absolute; z-index:5; left:16px; top:16px;
372
+ width:42px; height:42px; flex:none;
373
+ display:grid; place-items:center; cursor:pointer;
374
+ padding:0; margin:0; line-height:0;
375
+ border-radius:9px;
376
+ border:1px solid #ffffff2e; background:#ffffff14; color:#eef4f9;
377
+ transition: background .2s ease, transform .2s ease;
378
+ }
379
+ #studio .theme-toggle:hover { background:#ffffff28; transform:scale(1.06); }
380
+ #studio .theme-toggle:focus-visible { outline:3px solid var(--toggle-focus); outline-offset:2px; }
381
+ #studio .theme-toggle svg { width:21px; height:21px; display:block; }
382
+ #studio .theme-toggle .icon-sun { display:none; }
383
+ #studio[data-theme="dark"] .theme-toggle .icon-sun { display:block; }
384
+ #studio[data-theme="dark"] .theme-toggle .icon-moon { display:none; }
385
+ #studio[data-theme="dark"] { color-scheme: dark; }
386
+
387
+ #studio .surface {
388
+ padding: 20px 22px;
389
+ border: 1px solid var(--surface-border);
390
+ border-radius: 16px;
391
+ background: var(--surface);
392
+ box-shadow: var(--shadow-soft);
393
+ gap:14px;
394
+ min-width:0 !important;
395
+ }
396
+ #studio .section-title { display:flex; align-items:center; gap:10px; }
397
+ #studio .section-title span {
398
+ width:33px; height:33px; flex:none; display:grid; place-items:center;
399
+ color:var(--icon-color); border:1px solid var(--icon-border); border-radius:10px; background:var(--icon-bg);
400
+ }
401
+ #studio .section-title svg { width:19px; height:19px; }
402
+ #studio h2 { font: 730 19px/1.65 Vazirmatn,Tahoma,sans-serif; color:var(--heading); margin:0; }
403
+ #studio .model-row { align-items:center; gap:14px; }
404
+ #studio .model-row > div:first-child { gap:4px; }
405
+ #studio .model-row .form { background:transparent; border:0; box-shadow:none; }
406
+ #studio .model-note p, #studio .note { color:var(--note); font-size:12px; line-height:1.9; margin:0; }
407
+ #studio .model-note p { padding-inline-start:43px; }
408
+
409
+ /* Rounded model dropdown: pill field + rounded options menu. The wrapper
410
+ Gradio paints behind the pill (background + 4px radius) is made transparent
411
+ so the pill is the only visible background in both themes. */
412
+ #studio #model-select { width:100%; direction:rtl; border:0; background:transparent; box-shadow:none; }
413
+ #studio #model-select .wrap { background: transparent !important; border-radius: 999px; box-shadow: none !important; }
414
+ #studio #model-select input { direction:ltr; text-align:left; }
415
+ #studio #model-select [role="combobox"], #studio #model-select input {
416
+ background: var(--combo-bg) !important;
417
+ border: 1px solid var(--combo-border) !important;
418
+ border-radius: 999px !important;
419
+ padding: 8px 20px !important;
420
+ min-height: 44px;
421
+ box-shadow: none !important;
422
+ color: var(--text) !important;
423
+ font-weight: 600;
424
+ transition: border-color .18s ease, box-shadow .18s ease;
425
+ }
426
+ #studio #model-select [role="combobox"]:hover, #studio #model-select input:hover { border-color: var(--accent) !important; }
427
+ #studio #model-select [role="combobox"]:focus, #studio #model-select input:focus {
428
+ border-color: var(--accent) !important;
429
+ box-shadow: 0 0 0 3px var(--accent-soft) !important;
430
+ }
431
+ #studio #model-select ul[role="listbox"],
432
+ #studio #model-select .dropdown-options,
433
+ #studio #model-select .options {
434
+ border-radius: 16px !important;
435
+ border: 1px solid var(--popup-border) !important;
436
+ background: var(--popup-bg) !important;
437
+ box-shadow: var(--shadow-popup) !important;
438
+ overflow: hidden;
439
+ padding: 6px !important;
440
+ }
441
+ #studio #model-select li[role="option"], #studio #model-select .dropdown-option {
442
+ border-radius: 14px !important;
443
+ padding: 9px 16px !important;
444
+ margin: 1px 0 !important;
445
+ color: var(--text) !important;
446
+ }
447
+ #studio #model-select li[role="option"]:hover,
448
+ #studio #model-select .dropdown-option:hover,
449
+ #studio #model-select li[role="option"][aria-selected="true"] {
450
+ background: var(--option-hover) !important;
451
+ color: var(--accent-strong) !important;
452
+ }
453
+
454
+ #studio #technical { box-shadow:none; border:0; border-block-start:1px solid var(--subhead-border); border-radius:0; background:transparent; }
455
+ #studio #technical > button { padding:10px 2px 0; color:var(--accordion); }
456
+ #studio .settings { padding-top:16px; padding-bottom:12px; gap:10px; }
457
+ #studio #desk, #studio #results { gap:16px; }
458
+ #studio #desk { display:grid; grid-template-columns: minmax(0,1.12fr) minmax(0,1fr); align-items:start; }
459
+ #studio #results { min-width:0 !important; }
460
+
461
+ /* Main page tabs: خانه (rightmost under RTL, with the house icon to the right
462
+ of the text) and درباره ما to its left. Same pill group style as the
463
+ source tabs, driven by the shared tab variables. */
464
+ #studio #main-tabs { border:0; box-shadow:none; background:transparent; gap:0; }
465
+ #studio #main-tabs [role=tablist] {
466
+ display:flex; flex-wrap:nowrap; gap:4px; padding:5px; width:fit-content; max-width:100%;
467
+ background:var(--tablist-bg); border-radius:12px; border:0;
468
+ }
469
+ #studio #main-tabs [role=tab] {
470
+ display:inline-flex; align-items:center; gap:8px; flex:0 0 auto; cursor:pointer;
471
+ border:0; background:transparent; color:var(--tab-text);
472
+ font:600 14px/1.8 Vazirmatn,Tahoma,sans-serif;
473
+ padding:7px 18px; margin:0; border-radius:9px; white-space:nowrap;
474
+ transition: background .15s ease, color .15s ease;
475
+ }
476
+ #studio #main-tabs [role=tab]:hover { color:var(--tab-active-text); }
477
+ #studio #main-tabs [role=tab][aria-selected=true] {
478
+ background:var(--tab-active-bg); color:var(--tab-active-text);
479
+ box-shadow:0 1px 4px #183e3126;
480
+ }
481
+ /* House icon: first flex item, so it lands on the right of the label in RTL. */
482
+ #studio #main-tabs [role=tab]:first-of-type::before {
483
+ content:""; width:16px; height:16px; flex:none; background:currentColor;
484
+ -webkit-mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.9 10.6 12 3.9l8.1 6.7'/%3E%3Cpath d='M6 9.4V20h12V9.4'/%3E%3Cpath d='M10 20v-5.4h4V20'/%3E%3C/svg%3E") no-repeat center / contain;
485
+ mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.9 10.6 12 3.9l8.1 6.7'/%3E%3Cpath d='M6 9.4V20h12V9.4'/%3E%3Cpath d='M10 20v-5.4h4V20'/%3E%3C/svg%3E") no-repeat center / contain;
486
+ }
487
+ #studio #main-tabs [role=tabpanel] { border:0; background:transparent; padding:16px 0 0; }
488
+
489
+ /* درباره ما page: lead line, rounded info cards, click-to-copy email pill,
490
+ university logo block and the copyright footer under a divider. */
491
+ #studio .about-wrap { display:flex; flex-direction:column; gap:16px; width:100%; max-width:880px; margin-inline:auto; }
492
+ #studio .about-topbar { display:flex; justify-content:flex-start; }
493
+ #studio .about-topbar .theme-toggle {
494
+ position:static; border-color:var(--surface-border);
495
+ background:var(--surface-2); color:var(--text);
496
+ }
497
+ #studio .about-topbar .theme-toggle:hover { background:var(--accent-soft); transform:none; }
498
+ #studio .about-lead { margin:0; color:var(--note); font-size:13px; line-height:1.9; }
499
+ #studio .about-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap:14px; }
500
+ #studio .about-card {
501
+ display:flex; flex-direction:column; gap:6px; min-width:0;
502
+ padding:18px 20px;
503
+ border:1px solid var(--surface-border); border-radius:16px;
504
+ background:var(--surface); box-shadow:var(--shadow-soft);
505
+ }
506
+ #studio .about-card h3 { margin:0 0 6px; font:700 16px/1.8 Vazirmatn,Tahoma,sans-serif; color:var(--heading); }
507
+ #studio .about-card .person { margin:0; font:650 15px/1.9 Vazirmatn,Tahoma,sans-serif; color:var(--text); }
508
+ #studio .about-card .affiliation { margin:0; color:var(--note); font-size:13px; line-height:1.9; }
509
+ #studio .team-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:7px; }
510
+ #studio .team-list li { display:flex; align-items:center; gap:9px; color:var(--text); font-size:14px; line-height:1.9; }
511
+ #studio .team-list li::before { content:""; width:7px; height:7px; flex:none; border-radius:50%; background:var(--accent); }
512
+ #studio .copy-email {
513
+ align-self:flex-start; margin-top:8px; cursor:pointer;
514
+ display:inline-flex; align-items:center; gap:8px; direction:ltr;
515
+ padding:7px 14px; border-radius:999px;
516
+ border:1px solid var(--combo-border); background:var(--combo-bg); color:var(--accent-strong);
517
+ font:600 13px/1.6 Vazirmatn,Tahoma,sans-serif;
518
+ transition:border-color .15s ease, background .15s ease;
519
+ }
520
+ #studio .copy-email:hover { border-color:var(--accent); background:var(--option-hover); }
521
+ #studio .copy-email svg { width:15px; height:15px; flex:none; }
522
+ #studio .copy-email .ic-check { display:none; }
523
+ #studio .copy-email.copied { border-color:var(--accent); background:var(--accent-soft); }
524
+ #studio .copy-email.copied .ic-copy { display:none; }
525
+ #studio .copy-email.copied .ic-check { display:block; }
526
+ #studio .copy-email .copy-msg { opacity:0; margin-inline-start:2px; font-size:11.5px; color:var(--accent-strong); transition:opacity .18s ease; }
527
+ #studio .copy-email .msg-fail { display:none; color:var(--note); }
528
+ #studio .copy-email.copied .msg-ok { opacity:1; }
529
+ #studio .copy-email.copy-failed .msg-ok { display:none; }
530
+ #studio .copy-email.copy-failed .msg-fail { display:inline; opacity:1; }
531
+ #studio .univ-block { display:flex; flex-direction:column; align-items:center; gap:10px; padding-top:10px; text-align:center; }
532
+ #studio .univ-logo { width:min(118px, 42vw); height:auto; display:block; }
533
+ #studio .univ-name { margin:0; font:650 15px/1.8 Vazirmatn,Tahoma,sans-serif; color:var(--heading); }
534
+ #studio .about-footer { margin-top:6px; padding-top:14px; border-top:1px solid var(--surface-border); text-align:center; }
535
+ #studio .about-footer p { margin:0; color:var(--note); font-size:12.5px; line-height:1.9; }
536
+
537
+ /* The input-mode tabset is nested inside #main-tabs, so the outer tab rules
538
+ above cascade into it as well. Two leaks are undone here: the house icon
539
+ that #main-tabs paints on its first tab also matches the first tab of this
540
+ inner tablist, and the fit-content width that hugs the outer pill group
541
+ shrinks this bar so it no longer spans the full card. The rules below come
542
+ later with equal specificity, so they win without touching the outer tabs. */
543
+ #studio #sources { border:0; box-shadow:none; }
544
+ #studio #sources [role=tablist] {
545
+ display:flex; flex-wrap:nowrap; gap:3px; padding:4px; background:var(--tablist-bg);
546
+ border-radius:10px; border:0; min-width:0;
547
+ width:100%;
548
+ }
549
+ #studio #sources [role=tab]:first-of-type::before { content:none; }
550
+ #studio #sources [role=tab] {
551
+ flex:1 1 0; min-width:0; justify-content:center; border:0; text-align:center;
552
+ background:transparent; color:var(--tab-text); font:580 14px/1.8 Vazirmatn,Tahoma,sans-serif;
553
+ padding:5px 3px; margin:0; border-radius:7px; white-space:nowrap;
554
+ }
555
+ #studio #sources [role=tab][aria-selected=true] { background:var(--tab-active-bg); color:var(--tab-active-text); box-shadow:0 1px 4px #183e3126; }
556
+ #studio #sources [role=tabpanel] { border:0; background:transparent; padding:12px 0 0; }
557
+
558
+ /* Upload drop zone + in-progress pill. */
559
+ #studio #upload-audio { border:1px dashed var(--upload-border); border-radius:14px; background:var(--upload-bg); }
560
+ #studio #upload-audio .progress-bar, #studio #upload-audio .progress-text { display:none !important; }
561
+ /* Everything sits behind :not([hidden]) so the plain hidden attribute is
562
+ enough to fully collapse the pill even if attribute selectors get rewritten. */
563
+ #studio .upload-status:not([hidden]) {
564
+ display:flex; align-items:center; gap:10px; direction:rtl; text-align:right;
565
+ padding:10px 14px; border-radius:12px;
566
+ border:1px solid var(--status-border); background:var(--status-bg); color:var(--status-text);
567
+ font-size:13px; line-height:1.8; font-weight:600;
568
+ }
569
+ #studio .upload-status .dot {
570
+ width:15px; height:15px; flex:none; border-radius:50%;
571
+ border:2px solid var(--accent); border-top-color:transparent;
572
+ animation: asr-spin .8s linear infinite;
573
+ }
574
+ @keyframes asr-spin { to { transform: rotate(360deg); } }
575
+
576
+ /* Sample list: rounded tinted well with pill-shaped rows. */
577
+ #studio .radio-head { margin:0; font:650 14px/1.8 Vazirmatn,Tahoma,sans-serif; color:var(--subhead); direction:rtl; text-align:right; }
578
+ #studio #sample-list {
579
+ border:1px solid var(--surface-border) !important;
580
+ border-radius:16px !important;
581
+ background:var(--surface-2) !important;
582
+ padding:10px 12px;
583
+ box-shadow:none !important;
584
+ }
585
+ #studio #sample-list .wrap, #studio #sample-list .options-wrap {
586
+ display:flex; flex-direction:column; gap:8px; border:0 !important;
587
+ background:transparent; box-shadow:none !important;
588
+ }
589
+ #studio #sample-list label { border:0 !important; box-shadow:none !important; margin:0; background:transparent; }
590
+ #studio #sample-list label:has(input) {
591
+ display:flex; align-items:center; gap:10px;
592
+ padding:10px 16px;
593
+ border:1px solid var(--chip-border) !important; border-radius:999px !important;
594
+ background:var(--chip-bg) !important; color:var(--chip-text);
595
+ cursor:pointer; transition:border-color .15s ease, background .15s ease;
596
+ }
597
+ #studio #sample-list label:has(input):hover { border-color:var(--chip-hover-border) !important; background:var(--chip-hover-bg) !important; }
598
+ #studio #sample-list label:has(input:checked) {
599
+ border-color:var(--chip-active-border) !important; background:var(--chip-active-bg) !important;
600
+ color:var(--chip-active-text); font-weight:650;
601
+ box-shadow:0 1px 6px #126c601a !important;
602
+ }
603
+ #studio #sample-list input[type=radio] { accent-color: var(--accent); }
604
+
605
+ #studio .subhead { margin:0; padding-top:12px; border-top:1px solid var(--subhead-border); font:650 15px/1.8 Vazirmatn,Tahoma,sans-serif; color:var(--subhead); }
606
+ #studio .player-empty { color:var(--empty-text); margin:0; padding:12px 14px; font-size:13px; line-height:1.8; border-radius:8px; background:var(--empty-bg); }
607
+ #studio .actions { gap:9px; flex-wrap:nowrap; }
608
+ #studio .actions button { border-radius:12px; min-width:0; min-height:41px; font:620 14px Vazirmatn,Tahoma,sans-serif; }
609
+ #studio button:disabled { opacity:.64; }
610
+ #studio #shared-player, #studio [data-testid="waveform"] { direction:ltr; }
611
+ #studio #transcript { box-shadow:none; border-radius:10px; background:var(--transcript-bg); border:1px solid var(--transcript-border); }
612
+ #studio #transcript textarea {
613
+ font:450 16px/2.05 Vazirmatn,Tahoma,sans-serif; text-align:right; direction:rtl;
614
+ color:var(--transcript-text); background:transparent; padding:14px; border:0; box-shadow:none;
615
+ }
616
+ #studio #transcript textarea::placeholder { color:var(--placeholder); font-size:14px; }
617
+ #studio dl { margin:0; }
618
+ #studio .metrics { display:grid; grid-template-columns:repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap:8px; }
619
+ #studio .metrics > div { padding:9px 12px; border:1px solid var(--card-border); border-radius:9px; background:var(--card-bg); min-width:0; }
620
+ #studio dt { color:var(--dt); font-size:12px; line-height:1.8; }
621
+ #studio dd { color:var(--dd); margin:0; font-size:14px; overflow-wrap:anywhere; }
622
+ #studio .metrics dd { font-size:19px; line-height:1.5; font-weight:650; font-variant-numeric:tabular-nums; }
623
+ #studio .metrics + .note, #studio .metrics + .facts { margin-top:12px; }
624
+ #studio .facts { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%, 185px),1fr)); gap:4px 18px; }
625
+ #studio .facts > div { padding:5px 0; border-bottom:1px solid var(--facts-border); }
626
+ #studio :focus-visible { outline: 3px solid var(--focus); outline-offset:2px; }
627
+ @media (max-width:760px) {
628
+ .gradio-container { padding:12px !important; }
629
+ #studio #desk { grid-template-columns:minmax(0,1fr); }
630
+ #studio .surface { padding:15px; }
631
+ #studio .masthead { min-height:150px; }
632
+ #studio .intro { max-width:76%; }
633
+ #studio .contours { left:-13%; width:48%; opacity:.54; }
634
+ }
635
+ @media (max-width:480px) {
636
+ #studio, #studio #desk, #studio #results { gap:10px; }
637
+ #studio .masthead { min-height:145px; padding:17px; }
638
+ #studio .intro { max-width:100%; }
639
+ #studio .masthead p { max-width:88%; font-size:12px; }
640
+ #studio .contours { left:-36%; width:63%; opacity:.26; }
641
+ #studio .model-row { display:grid; grid-template-columns:minmax(0,1fr); gap:8px; }
642
+ #studio #model-select { max-width:none; min-width:0 !important; }
643
+ #studio .model-note p { padding-inline-start:0; }
644
+ #studio #sources [role=tab] { font-size:12px; }
645
+ #studio #main-tabs [role=tab] { font-size:13px; padding:6px 13px; }
646
+ #studio #main-tabs [role=tab]:first-of-type::before { width:14px; height:14px; }
647
+ #studio .about-card { padding:15px; }
648
+ #studio .copy-email { padding:6px 12px; font-size:12px; }
649
+ #studio .theme-toggle { left:12px; top:12px; width:38px; height:38px; }
650
+ #studio .theme-toggle svg { width:18px; height:18px; }
651
+ #studio .metrics { grid-template-columns:minmax(0,1fr); }
652
+ }
dashboard_assets/travel.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dea8f189130c415e55b5b9aa94a6f2ef185243d9f9b3dbebb8d0415f0e0359c3
3
+ size 337964
dashboard_assets/university_logo.png ADDED

Git LFS Details

  • SHA256: a04a2be323f7e2d514368d01521e8e0475821b28dd5961d732e51332a77b4550
  • Pointer size: 131 Bytes
  • Size of remote file: 163 kB
icefall/__init__.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort:skip_file
2
+
3
+ from . import checkpoint, decode, dist, env, utils
4
+
5
+ from .byte_utils import (
6
+ byte_decode,
7
+ byte_encode,
8
+ smart_byte_decode,
9
+ )
10
+
11
+ from .checkpoint import (
12
+ average_checkpoints,
13
+ find_checkpoints,
14
+ load_checkpoint,
15
+ remove_checkpoints,
16
+ save_checkpoint,
17
+ save_checkpoint_with_global_batch_idx,
18
+ )
19
+
20
+ from .context_graph import ContextGraph, ContextState
21
+
22
+ from .decode import (
23
+ get_lattice,
24
+ nbest_decoding,
25
+ nbest_oracle,
26
+ one_best_decoding,
27
+ rescore_with_attention_decoder,
28
+ rescore_with_n_best_list,
29
+ rescore_with_whole_lattice,
30
+ )
31
+
32
+ from .dist import (
33
+ cleanup_dist,
34
+ setup_dist,
35
+ )
36
+
37
+ from .env import (
38
+ get_env_info,
39
+ get_git_branch_name,
40
+ get_git_date,
41
+ get_git_sha1,
42
+ )
43
+
44
+ from .utils import (
45
+ AttributeDict,
46
+ MetricsTracker,
47
+ add_eos,
48
+ add_sos,
49
+ concat,
50
+ encode_supervisions,
51
+ get_alignments,
52
+ get_executor,
53
+ get_texts,
54
+ is_cjk,
55
+ is_jit_tracing,
56
+ is_module_available,
57
+ l1_norm,
58
+ l2_norm,
59
+ linf_norm,
60
+ load_alignments,
61
+ make_pad_mask,
62
+ measure_gradient_norms,
63
+ measure_weight_norms,
64
+ optim_step_and_measure_param_change,
65
+ save_alignments,
66
+ setup_logger,
67
+ store_transcripts,
68
+ str2bool,
69
+ subsequent_chunk_mask,
70
+ tokenize_by_CJK_char,
71
+ tokenize_by_ja_char,
72
+ write_error_stats,
73
+ )
74
+
75
+ from .ngram_lm import NgramLm, NgramLmStateCost
76
+
77
+ from .lm_wrapper import LmScorer
icefall/ali.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Dict, List, Tuple
18
+
19
+ import torch
20
+ from torch.nn.utils.rnn import pad_sequence
21
+
22
+
23
+ def save_alignments(
24
+ alignments: Dict[str, List[int]],
25
+ subsampling_factor: int,
26
+ filename: str,
27
+ ) -> None:
28
+ """Save alignments to a file.
29
+
30
+ Args:
31
+ alignments:
32
+ A dict containing alignments. Keys of the dict are utterances and
33
+ values are the corresponding framewise alignments after subsampling.
34
+ subsampling_factor:
35
+ The subsampling factor of the model.
36
+ filename:
37
+ Path to save the alignments.
38
+ Returns:
39
+ Return None.
40
+ """
41
+ ali_dict = {
42
+ "subsampling_factor": subsampling_factor,
43
+ "alignments": alignments,
44
+ }
45
+ torch.save(ali_dict, filename)
46
+
47
+
48
+ def load_alignments(filename: str) -> Tuple[int, Dict[str, List[int]]]:
49
+ """Load alignments from a file.
50
+
51
+ Args:
52
+ filename:
53
+ Path to the file containing alignment information.
54
+ The file should be saved by :func:`save_alignments`.
55
+ Returns:
56
+ Return a tuple containing:
57
+ - subsampling_factor: The subsampling_factor used to compute
58
+ the alignments.
59
+ - alignments: A dict containing utterances and their corresponding
60
+ framewise alignment, after subsampling.
61
+ """
62
+ ali_dict = torch.load(filename, weights_only=False)
63
+ subsampling_factor = ali_dict["subsampling_factor"]
64
+ alignments = ali_dict["alignments"]
65
+ return subsampling_factor, alignments
66
+
67
+
68
+ def convert_alignments_to_tensor(
69
+ alignments: Dict[str, List[int]], device: torch.device
70
+ ) -> Dict[str, torch.Tensor]:
71
+ """Convert alignments from list of int to a 1-D torch.Tensor.
72
+
73
+ Args:
74
+ alignments:
75
+ A dict containing alignments. Keys are utterance IDs and
76
+ values are their corresponding frame-wise alignments.
77
+ device:
78
+ The device to move the alignments to.
79
+ Returns:
80
+ Return a dict using 1-D torch.Tensor to store the alignments.
81
+ The dtype of the tensor are `torch.int64`. We choose `torch.int64`
82
+ because `torch.nn.functional.one_hot` requires that.
83
+ """
84
+ ans = {}
85
+ for utt_id, ali in alignments.items():
86
+ ali = torch.tensor(ali, dtype=torch.int64, device=device)
87
+ ans[utt_id] = ali
88
+ return ans
89
+
90
+
91
+ def lookup_alignments(
92
+ cut_ids: List[str],
93
+ alignments: Dict[str, torch.Tensor],
94
+ num_classes: int,
95
+ log_score: float = -10,
96
+ ) -> torch.Tensor:
97
+ """Return a mask constructed from alignments by a list of cut IDs.
98
+
99
+ The returned mask is a 3-D tensor of shape (N, T, C). For each frame,
100
+ i.e., each row, of the returned mask, positions not corresponding to
101
+ the alignments are filled with `log_score`, while the position
102
+ specified by the alignment is filled with 0. For instance, if the alignments
103
+ of two utterances are:
104
+
105
+ [ [1, 3, 2], [1, 0, 4, 2] ]
106
+ num_classes is 5 and log_score is -10, then the returned mask is
107
+
108
+ [
109
+ [[-10, 0, -10, -10, -10],
110
+ [-10, -10, -10, 0, -10],
111
+ [-10, -10, 0, -10, -10],
112
+ [0, -10, -10, -10, -10]],
113
+ [[-10, 0, -10, -10, -10],
114
+ [0, -10, -10, -10, -10],
115
+ [-10, -10, -10, -10, 0],
116
+ [-10, -10, 0, -10, -10]]
117
+ ]
118
+ Note: We pad the alignment of the first utterance with 0.
119
+
120
+ Args:
121
+ cut_ids:
122
+ A list of utterance IDs.
123
+ alignments:
124
+ A dict containing alignments. The keys are utterance IDs and the values
125
+ are framewise alignments.
126
+ num_classes:
127
+ The max token ID + 1 that appears in the alignments.
128
+ log_score:
129
+ Positions in the returned tensor not corresponding to the alignments
130
+ are filled with this value.
131
+ Returns:
132
+ Return a 3-D torch.float32 tensor of shape (N, T, C).
133
+ """
134
+ # We assume all utterances have their alignments.
135
+ ali = [alignments[cut_id] for cut_id in cut_ids]
136
+ padded_ali = pad_sequence(ali, batch_first=True, padding_value=0)
137
+ padded_one_hot = torch.nn.functional.one_hot(
138
+ padded_ali,
139
+ num_classes=num_classes,
140
+ )
141
+ mask = (1 - padded_one_hot) * float(log_score)
142
+ return mask
icefall/bpe_graph_compiler.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ from pathlib import Path
19
+ from typing import List, Union
20
+
21
+ import k2
22
+ import sentencepiece as spm
23
+ import torch
24
+
25
+
26
+ class BpeCtcTrainingGraphCompiler(object):
27
+ def __init__(
28
+ self,
29
+ lang_dir: Path,
30
+ device: Union[str, torch.device] = "cpu",
31
+ sos_token: str = "<sos/eos>",
32
+ eos_token: str = "<sos/eos>",
33
+ ) -> None:
34
+ """
35
+ Args:
36
+ lang_dir:
37
+ This directory is expected to contain the following files:
38
+
39
+ - bpe.model
40
+ - words.txt
41
+ device:
42
+ It indicates CPU or CUDA.
43
+ sos_token:
44
+ The word piece that represents sos.
45
+ eos_token:
46
+ The word piece that represents eos.
47
+ """
48
+ lang_dir = Path(lang_dir)
49
+ model_file = lang_dir / "bpe.model"
50
+ sp = spm.SentencePieceProcessor()
51
+ sp.load(str(model_file))
52
+ self.sp = sp
53
+ self.word_table = k2.SymbolTable.from_file(lang_dir / "words.txt")
54
+ self.device = device
55
+
56
+ self.sos_id = self.sp.piece_to_id(sos_token)
57
+ self.eos_id = self.sp.piece_to_id(eos_token)
58
+
59
+ assert self.sos_id != self.sp.unk_id()
60
+ assert self.eos_id != self.sp.unk_id()
61
+
62
+ def texts_to_ids(self, texts: List[str]) -> List[List[int]]:
63
+ """Convert a list of texts to a list-of-list of piece IDs.
64
+
65
+ Args:
66
+ texts:
67
+ It is a list of strings. Each string consists of space(s)
68
+ separated words. An example containing two strings is given below:
69
+
70
+ ['HELLO ICEFALL', 'HELLO k2']
71
+ Returns:
72
+ Return a list-of-list of piece IDs.
73
+ """
74
+ return self.sp.encode(texts, out_type=int)
75
+
76
+ def compile(
77
+ self,
78
+ piece_ids: List[List[int]],
79
+ modified: bool = False,
80
+ ) -> k2.Fsa:
81
+ """Build a ctc graph from a list-of-list piece IDs.
82
+
83
+ Args:
84
+ piece_ids:
85
+ It is a list-of-list integer IDs.
86
+ modified:
87
+ See :func:`k2.ctc_graph` for its meaning.
88
+ Return:
89
+ Return an FsaVec, which is the result of composing a
90
+ CTC topology with linear FSAs constructed from the given
91
+ piece IDs.
92
+ """
93
+ graph = k2.ctc_graph(piece_ids, modified=modified, device=self.device)
94
+ return graph
icefall/byte_utils.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ #
6
+ # This file was copied and modified from https://github.com/facebookresearch/fairseq/blob/main/fairseq/data/encoders/byte_utils.py
7
+
8
+ import re
9
+ import unicodedata
10
+
11
+ WHITESPACE_NORMALIZER = re.compile(r"\s+")
12
+ SPACE = chr(32)
13
+ SPACE_ESCAPE = chr(9601)
14
+ BPE_UNK = chr(8263)
15
+
16
+ PRINTABLE_BASE_CHARS = [
17
+ 256,
18
+ 257,
19
+ 258,
20
+ 259,
21
+ 260,
22
+ 261,
23
+ 262,
24
+ 263,
25
+ 264,
26
+ 265,
27
+ 266,
28
+ 267,
29
+ 268,
30
+ 269,
31
+ 270,
32
+ 271,
33
+ 272,
34
+ 273,
35
+ 274,
36
+ 275,
37
+ 276,
38
+ 277,
39
+ 278,
40
+ 279,
41
+ 280,
42
+ 281,
43
+ 282,
44
+ 283,
45
+ 284,
46
+ 285,
47
+ 286,
48
+ 287,
49
+ 32,
50
+ 33,
51
+ 34,
52
+ 35,
53
+ 36,
54
+ 37,
55
+ 38,
56
+ 39,
57
+ 40,
58
+ 41,
59
+ 42,
60
+ 43,
61
+ 44,
62
+ 45,
63
+ 46,
64
+ 47,
65
+ 48,
66
+ 49,
67
+ 50,
68
+ 51,
69
+ 52,
70
+ 53,
71
+ 54,
72
+ 55,
73
+ 56,
74
+ 57,
75
+ 58,
76
+ 59,
77
+ 60,
78
+ 61,
79
+ 62,
80
+ 63,
81
+ 64,
82
+ 65,
83
+ 66,
84
+ 67,
85
+ 68,
86
+ 69,
87
+ 70,
88
+ 71,
89
+ 72,
90
+ 73,
91
+ 74,
92
+ 75,
93
+ 76,
94
+ 77,
95
+ 78,
96
+ 79,
97
+ 80,
98
+ 81,
99
+ 82,
100
+ 83,
101
+ 84,
102
+ 85,
103
+ 86,
104
+ 87,
105
+ 88,
106
+ 89,
107
+ 90,
108
+ 91,
109
+ 92,
110
+ 93,
111
+ 94,
112
+ 95,
113
+ 96,
114
+ 97,
115
+ 98,
116
+ 99,
117
+ 100,
118
+ 101,
119
+ 102,
120
+ 103,
121
+ 104,
122
+ 105,
123
+ 106,
124
+ 107,
125
+ 108,
126
+ 109,
127
+ 110,
128
+ 111,
129
+ 112,
130
+ 113,
131
+ 114,
132
+ 115,
133
+ 116,
134
+ 117,
135
+ 118,
136
+ 119,
137
+ 120,
138
+ 121,
139
+ 122,
140
+ 123,
141
+ 124,
142
+ 125,
143
+ 126,
144
+ 288,
145
+ 289,
146
+ 290,
147
+ 291,
148
+ 292,
149
+ 293,
150
+ 294,
151
+ 295,
152
+ 296,
153
+ 297,
154
+ 298,
155
+ 299,
156
+ 300,
157
+ 301,
158
+ 302,
159
+ 303,
160
+ 304,
161
+ 305,
162
+ 308,
163
+ 309,
164
+ 310,
165
+ 311,
166
+ 312,
167
+ 313,
168
+ 314,
169
+ 315,
170
+ 316,
171
+ 317,
172
+ 318,
173
+ 321,
174
+ 322,
175
+ 323,
176
+ 324,
177
+ 325,
178
+ 326,
179
+ 327,
180
+ 328,
181
+ 330,
182
+ 331,
183
+ 332,
184
+ 333,
185
+ 334,
186
+ 335,
187
+ 336,
188
+ 337,
189
+ 338,
190
+ 339,
191
+ 340,
192
+ 341,
193
+ 342,
194
+ 343,
195
+ 344,
196
+ 345,
197
+ 346,
198
+ 347,
199
+ 348,
200
+ 349,
201
+ 350,
202
+ 351,
203
+ 352,
204
+ 353,
205
+ 354,
206
+ 355,
207
+ 356,
208
+ 357,
209
+ 358,
210
+ 359,
211
+ 360,
212
+ 361,
213
+ 362,
214
+ 363,
215
+ 364,
216
+ 365,
217
+ 366,
218
+ 367,
219
+ 368,
220
+ 369,
221
+ 370,
222
+ 371,
223
+ 372,
224
+ 373,
225
+ 374,
226
+ 375,
227
+ 376,
228
+ 377,
229
+ 378,
230
+ 379,
231
+ 380,
232
+ 381,
233
+ 382,
234
+ 384,
235
+ 385,
236
+ 386,
237
+ 387,
238
+ 388,
239
+ 389,
240
+ 390,
241
+ 391,
242
+ 392,
243
+ 393,
244
+ 394,
245
+ 395,
246
+ 396,
247
+ 397,
248
+ 398,
249
+ 399,
250
+ 400,
251
+ 401,
252
+ 402,
253
+ 403,
254
+ 404,
255
+ 405,
256
+ 406,
257
+ 407,
258
+ 408,
259
+ 409,
260
+ 410,
261
+ 411,
262
+ 412,
263
+ 413,
264
+ 414,
265
+ 415,
266
+ 416,
267
+ 417,
268
+ 418,
269
+ 419,
270
+ 420,
271
+ 421,
272
+ 422,
273
+ ]
274
+
275
+ for c in PRINTABLE_BASE_CHARS:
276
+ assert unicodedata.normalize("NFKC", chr(c)) == chr(c), c
277
+
278
+ BYTE_TO_BCHAR = {b: chr(PRINTABLE_BASE_CHARS[b]) for b in range(256)}
279
+ BCHAR_TO_BYTE = {bc: b for b, bc in BYTE_TO_BCHAR.items()}
280
+ BCHAR_TO_BYTE[BPE_UNK] = 32 # map unk to space
281
+
282
+
283
+ def byte_encode(x: str) -> str:
284
+ normalized = WHITESPACE_NORMALIZER.sub(SPACE, x)
285
+ return "".join([BYTE_TO_BCHAR[b] for b in normalized.encode("utf-8")])
286
+
287
+
288
+ def byte_decode(x: str) -> str:
289
+ try:
290
+ return bytes([BCHAR_TO_BYTE[bc] for bc in x]).decode("utf-8")
291
+ except ValueError:
292
+ return ""
293
+
294
+
295
+ def smart_byte_decode(x: str) -> str:
296
+ output = byte_decode(x)
297
+ if output == "":
298
+ # DP the best recovery (max valid chars) if it's broken
299
+ n_bytes = len(x)
300
+ f = [0 for _ in range(n_bytes + 1)]
301
+ pt = [0 for _ in range(n_bytes + 1)]
302
+ for i in range(1, n_bytes + 1):
303
+ f[i], pt[i] = f[i - 1], i - 1
304
+ for j in range(1, min(4, i) + 1):
305
+ if f[i - j] + 1 > f[i] and len(byte_decode(x[i - j : i])) > 0:
306
+ f[i], pt[i] = f[i - j] + 1, i - j
307
+ cur_pt = n_bytes
308
+ while cur_pt > 0:
309
+ if f[cur_pt] == f[pt[cur_pt]] + 1:
310
+ output = byte_decode(x[pt[cur_pt] : cur_pt]) + output
311
+ cur_pt = pt[cur_pt]
312
+ return output
icefall/char_graph_compiler.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang,
2
+ # Wei Kang)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import re
19
+ from typing import List
20
+
21
+ import k2
22
+ import torch
23
+
24
+ from icefall.lexicon import Lexicon
25
+
26
+
27
+ class CharCtcTrainingGraphCompiler(object):
28
+ def __init__(
29
+ self,
30
+ lexicon: Lexicon,
31
+ device: torch.device,
32
+ sos_token: str = "<sos/eos>",
33
+ eos_token: str = "<sos/eos>",
34
+ oov: str = "<unk>",
35
+ ):
36
+ """
37
+ Args:
38
+ lexicon:
39
+ It is built from `data/lang_char/lexicon.txt`.
40
+ device:
41
+ The device to use for operations compiling transcripts to FSAs.
42
+ oov:
43
+ Out of vocabulary token. When a word(token) in the transcript
44
+ does not exist in the token list, it is replaced with `oov`.
45
+ """
46
+
47
+ assert oov in lexicon.token_table
48
+
49
+ self.oov_id = lexicon.token_table[oov]
50
+ self.token_table = lexicon.token_table
51
+
52
+ self.device = device
53
+
54
+ self.sos_id = self.token_table[sos_token]
55
+ self.eos_id = self.token_table[eos_token]
56
+
57
+ def texts_to_ids(self, texts: List[str], sep: str = "") -> List[List[int]]:
58
+ """Convert a list of texts to a list-of-list of token IDs.
59
+
60
+ Args:
61
+ texts:
62
+ It is a list of strings.
63
+ An example containing two strings is given below:
64
+
65
+ ['你好中国', '北京欢迎您']
66
+ sep:
67
+ The separator of the items in one sequence, mainly no separator for
68
+ Chinese (one character a token), "/" for Chinese characters plus BPE
69
+ token and pinyin tokens.
70
+ Returns:
71
+ Return a list-of-list of token IDs.
72
+ """
73
+ assert sep in ("", "/"), sep
74
+ ids: List[List[int]] = []
75
+ whitespace = re.compile(r"([ \t])")
76
+ for text in texts:
77
+ if sep == "":
78
+ text = re.sub(whitespace, "", text)
79
+ else:
80
+ text = text.split(sep)
81
+ sub_ids = [
82
+ self.token_table[txt] if txt in self.token_table else self.oov_id
83
+ for txt in text
84
+ ]
85
+ ids.append(sub_ids)
86
+ return ids
87
+
88
+ def compile(
89
+ self,
90
+ token_ids: List[List[int]],
91
+ modified: bool = False,
92
+ ) -> k2.Fsa:
93
+ """Build a ctc graph from a list-of-list token IDs.
94
+
95
+ Args:
96
+ piece_ids:
97
+ It is a list-of-list integer IDs.
98
+ modified:
99
+ See :func:`k2.ctc_graph` for its meaning.
100
+ Return:
101
+ Return an FsaVec, which is the result of composing a
102
+ CTC topology with linear FSAs constructed from the given
103
+ piece IDs.
104
+ """
105
+ graph = k2.ctc_graph(token_ids, modified=modified, device=self.device)
106
+ return graph
icefall/checkpoint.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021-2022 Xiaomi Corporation (authors: Fangjun Kuang,
2
+ # Zengwei Yao)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ import glob
20
+ import logging
21
+ import os
22
+ import re
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional, Union
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ from lhotse.dataset.sampling.base import CutSampler
29
+ from torch import Tensor
30
+ from torch.nn.parallel import DistributedDataParallel as DDP
31
+ from torch.optim import Optimizer
32
+
33
+ # use duck typing for LRScheduler since we have different possibilities, see
34
+ # our class LRScheduler.
35
+ LRSchedulerType = object
36
+
37
+
38
+ def save_checkpoint(
39
+ filename: Path,
40
+ model: Union[nn.Module, DDP],
41
+ model_avg: Optional[nn.Module] = None,
42
+ params: Optional[Dict[str, Any]] = None,
43
+ optimizer: Optional[Optimizer] = None,
44
+ scheduler: Optional[LRSchedulerType] = None,
45
+ scaler: Optional["GradScaler"] = None,
46
+ sampler: Optional[CutSampler] = None,
47
+ rank: int = 0,
48
+ ) -> None:
49
+ """Save training information to a file.
50
+
51
+ Args:
52
+ filename:
53
+ The checkpoint filename.
54
+ model:
55
+ The model to be saved. We only save its `state_dict()`.
56
+ model_avg:
57
+ The stored model averaged from the start of training.
58
+ params:
59
+ User defined parameters, e.g., epoch, loss.
60
+ optimizer:
61
+ The optimizer to be saved. We only save its `state_dict()`.
62
+ scheduler:
63
+ The scheduler to be saved. We only save its `state_dict()`.
64
+ scalar:
65
+ The GradScaler to be saved. We only save its `state_dict()`.
66
+ rank:
67
+ Used in DDP. We save checkpoint only for the node whose rank is 0.
68
+ Returns:
69
+ Return None.
70
+ """
71
+ if rank != 0:
72
+ return
73
+
74
+ logging.info(f"Saving checkpoint to {filename}")
75
+
76
+ if isinstance(model, DDP):
77
+ model = model.module
78
+
79
+ checkpoint = {
80
+ "model": model.state_dict(),
81
+ "optimizer": optimizer.state_dict() if optimizer is not None else None,
82
+ "scheduler": scheduler.state_dict() if scheduler is not None else None,
83
+ "grad_scaler": scaler.state_dict() if scaler is not None else None,
84
+ "sampler": sampler.state_dict() if sampler is not None else None,
85
+ }
86
+
87
+ if model_avg is not None:
88
+ checkpoint["model_avg"] = model_avg.to(torch.float32).state_dict()
89
+
90
+ if params:
91
+ for k, v in params.items():
92
+ assert k not in checkpoint, k
93
+ checkpoint[k] = v
94
+
95
+ torch.save(checkpoint, filename)
96
+
97
+
98
+ def load_checkpoint(
99
+ filename: Path,
100
+ model: nn.Module,
101
+ model_avg: Optional[nn.Module] = None,
102
+ optimizer: Optional[Optimizer] = None,
103
+ scheduler: Optional[LRSchedulerType] = None,
104
+ scaler: Optional["GradScaler"] = None,
105
+ sampler: Optional[CutSampler] = None,
106
+ strict: bool = False,
107
+ ) -> Dict[str, Any]:
108
+ """
109
+ TODO: document it
110
+ """
111
+ logging.info(f"Loading checkpoint from {filename}")
112
+ checkpoint = torch.load(filename, map_location="cpu", weights_only=False)
113
+
114
+ if next(iter(checkpoint["model"])).startswith("module."):
115
+ logging.info("Loading checkpoint saved by DDP")
116
+
117
+ dst_state_dict = model.state_dict()
118
+ src_state_dict = checkpoint["model"]
119
+ for key in dst_state_dict.keys():
120
+ src_key = "{}.{}".format("module", key)
121
+ dst_state_dict[key] = src_state_dict.pop(src_key)
122
+ assert len(src_state_dict) == 0
123
+ model.load_state_dict(dst_state_dict, strict=strict)
124
+ else:
125
+ model.load_state_dict(checkpoint["model"], strict=strict)
126
+
127
+ checkpoint.pop("model")
128
+
129
+ if model_avg is not None and "model_avg" in checkpoint:
130
+ logging.info("Loading averaged model")
131
+ model_avg.load_state_dict(checkpoint["model_avg"], strict=strict)
132
+ checkpoint.pop("model_avg")
133
+
134
+ def load(name, obj):
135
+ s = checkpoint.get(name, None)
136
+ if obj and s:
137
+ obj.load_state_dict(s)
138
+ checkpoint.pop(name)
139
+
140
+ load("optimizer", optimizer)
141
+ load("scheduler", scheduler)
142
+ load("grad_scaler", scaler)
143
+ load("sampler", sampler)
144
+
145
+ return checkpoint
146
+
147
+
148
+ def average_checkpoints(
149
+ filenames: List[Path], device: torch.device = torch.device("cpu")
150
+ ) -> dict:
151
+ """Average a list of checkpoints.
152
+
153
+ Args:
154
+ filenames:
155
+ Filenames of the checkpoints to be averaged. We assume all
156
+ checkpoints are saved by :func:`save_checkpoint`.
157
+ device:
158
+ Move checkpoints to this device before averaging.
159
+ Returns:
160
+ Return a dict (i.e., state_dict) which is the average of all
161
+ model state dicts contained in the checkpoints.
162
+ """
163
+ n = len(filenames)
164
+
165
+ avg = torch.load(filenames[0], map_location=device, weights_only=False)["model"]
166
+
167
+ # Identify shared parameters. Two parameters are said to be shared
168
+ # if they have the same data_ptr
169
+ uniqued: Dict[int, str] = dict()
170
+
171
+ for k, v in avg.items():
172
+ v_data_ptr = v.data_ptr()
173
+ if v_data_ptr in uniqued:
174
+ continue
175
+ uniqued[v_data_ptr] = k
176
+
177
+ uniqued_names = list(uniqued.values())
178
+
179
+ for i in range(1, n):
180
+ state_dict = torch.load(filenames[i], map_location=device, weights_only=False)[
181
+ "model"
182
+ ]
183
+ for k in uniqued_names:
184
+ avg[k] += state_dict[k]
185
+
186
+ for k in uniqued_names:
187
+ if avg[k].is_floating_point():
188
+ avg[k] /= n
189
+ else:
190
+ avg[k] //= n
191
+
192
+ return avg
193
+
194
+
195
+ def save_checkpoint_with_global_batch_idx(
196
+ out_dir: Path,
197
+ global_batch_idx: int,
198
+ model: Union[nn.Module, DDP],
199
+ model_avg: Optional[nn.Module] = None,
200
+ params: Optional[Dict[str, Any]] = None,
201
+ optimizer: Optional[Optimizer] = None,
202
+ scheduler: Optional[LRSchedulerType] = None,
203
+ scaler: Optional["GradScaler"] = None,
204
+ sampler: Optional[CutSampler] = None,
205
+ rank: int = 0,
206
+ ):
207
+ """Save training info after processing given number of batches.
208
+
209
+ Args:
210
+ out_dir:
211
+ The directory to save the checkpoint.
212
+ global_batch_idx:
213
+ The number of batches processed so far from the very start of the
214
+ training. The saved checkpoint will have the following filename:
215
+
216
+ f'out_dir / checkpoint-{global_batch_idx}.pt'
217
+ model:
218
+ The neural network model whose `state_dict` will be saved in the
219
+ checkpoint.
220
+ model_avg:
221
+ The stored model averaged from the start of training.
222
+ params:
223
+ A dict of training configurations to be saved.
224
+ optimizer:
225
+ The optimizer used in the training. Its `state_dict` will be saved.
226
+ scheduler:
227
+ The learning rate scheduler used in the training. Its `state_dict` will
228
+ be saved.
229
+ scaler:
230
+ The scaler used for mix precision training. Its `state_dict` will
231
+ be saved.
232
+ sampler:
233
+ The sampler used in the training dataset.
234
+ rank:
235
+ The rank ID used in DDP training of the current node. Set it to 0
236
+ if DDP is not used.
237
+ """
238
+ out_dir = Path(out_dir)
239
+ out_dir.mkdir(parents=True, exist_ok=True)
240
+ filename = out_dir / f"checkpoint-{global_batch_idx}.pt"
241
+ save_checkpoint(
242
+ filename=filename,
243
+ model=model,
244
+ model_avg=model_avg,
245
+ params=params,
246
+ optimizer=optimizer,
247
+ scheduler=scheduler,
248
+ scaler=scaler,
249
+ sampler=sampler,
250
+ rank=rank,
251
+ )
252
+
253
+
254
+ def find_checkpoints(out_dir: Path, iteration: int = 0) -> List[str]:
255
+ """Find all available checkpoints in a directory.
256
+
257
+ The checkpoint filenames have the form: `checkpoint-xxx.pt`
258
+ where xxx is a numerical value.
259
+
260
+ Assume you have the following checkpoints in the folder `foo`:
261
+
262
+ - checkpoint-1.pt
263
+ - checkpoint-20.pt
264
+ - checkpoint-300.pt
265
+ - checkpoint-4000.pt
266
+
267
+ Case 1 (Return all checkpoints)::
268
+
269
+ find_checkpoints(out_dir='foo')
270
+
271
+ Case 2 (Return checkpoints newer than checkpoint-20.pt, i.e.,
272
+ checkpoint-4000.pt, checkpoint-300.pt, and checkpoint-20.pt)
273
+
274
+ find_checkpoints(out_dir='foo', iteration=20)
275
+
276
+ Case 3 (Return checkpoints older than checkpoint-20.pt, i.e.,
277
+ checkpoint-20.pt, checkpoint-1.pt)::
278
+
279
+ find_checkpoints(out_dir='foo', iteration=-20)
280
+
281
+ Args:
282
+ out_dir:
283
+ The directory where to search for checkpoints.
284
+ iteration:
285
+ If it is 0, return all available checkpoints.
286
+ If it is positive, return the checkpoints whose iteration number is
287
+ greater than or equal to `iteration`.
288
+ If it is negative, return the checkpoints whose iteration number is
289
+ less than or equal to `-iteration`.
290
+ Returns:
291
+ Return a list of checkpoint filenames, sorted in descending
292
+ order by the numerical value in the filename.
293
+ """
294
+ checkpoints = list(glob.glob(f"{out_dir}/checkpoint-[0-9]*.pt"))
295
+ pattern = re.compile(r"checkpoint-([0-9]+).pt")
296
+ iter_checkpoints = []
297
+ for c in checkpoints:
298
+ result = pattern.search(c)
299
+ if not result:
300
+ logging.warn(f"Invalid checkpoint filename {c}")
301
+ continue
302
+
303
+ iter_checkpoints.append((int(result.group(1)), c))
304
+
305
+ # iter_checkpoints is a list of tuples. Each tuple contains
306
+ # two elements: (iteration_number, checkpoint-iteration_number.pt)
307
+
308
+ iter_checkpoints = sorted(iter_checkpoints, reverse=True, key=lambda x: x[0])
309
+ if iteration >= 0:
310
+ ans = [ic[1] for ic in iter_checkpoints if ic[0] >= iteration]
311
+ else:
312
+ ans = [ic[1] for ic in iter_checkpoints if ic[0] <= -iteration]
313
+
314
+ return ans
315
+
316
+
317
+ def remove_checkpoints(
318
+ out_dir: Path,
319
+ topk: int,
320
+ rank: int = 0,
321
+ ):
322
+ """Remove checkpoints from the given directory.
323
+
324
+ We assume that checkpoint filename has the form `checkpoint-xxx.pt`
325
+ where xxx is a number, representing the number of processed batches
326
+ when saving that checkpoint. We sort checkpoints by filename and keep
327
+ only the `topk` checkpoints with the highest `xxx`.
328
+
329
+ Args:
330
+ out_dir:
331
+ The directory containing checkpoints to be removed.
332
+ topk:
333
+ Number of checkpoints to keep.
334
+ rank:
335
+ If using DDP for training, it is the rank of the current node.
336
+ Use 0 if no DDP is used for training.
337
+ """
338
+ assert topk >= 1, topk
339
+ if rank != 0:
340
+ return
341
+ checkpoints = find_checkpoints(out_dir)
342
+
343
+ if len(checkpoints) == 0:
344
+ logging.warn(f"No checkpoints found in {out_dir}")
345
+ return
346
+
347
+ if len(checkpoints) <= topk:
348
+ return
349
+
350
+ to_remove = checkpoints[topk:]
351
+ for c in to_remove:
352
+ os.remove(c)
353
+
354
+
355
+ def update_averaged_model(
356
+ params: Dict[str, Tensor],
357
+ model_cur: Union[nn.Module, DDP],
358
+ model_avg: nn.Module,
359
+ ) -> None:
360
+ """Update the averaged model:
361
+ model_avg = model_cur * (average_period / batch_idx_train)
362
+ + model_avg * ((batch_idx_train - average_period) / batch_idx_train)
363
+
364
+ Args:
365
+ params:
366
+ User defined parameters, e.g., epoch, loss.
367
+ model_cur:
368
+ The current model.
369
+ model_avg:
370
+ The averaged model to be updated.
371
+ """
372
+ weight_cur = params.average_period / params.batch_idx_train
373
+ weight_avg = 1 - weight_cur
374
+
375
+ if isinstance(model_cur, DDP):
376
+ model_cur = model_cur.module
377
+
378
+ cur = model_cur.state_dict()
379
+ avg = model_avg.state_dict()
380
+
381
+ average_state_dict(
382
+ state_dict_1=avg,
383
+ state_dict_2=cur,
384
+ weight_1=weight_avg,
385
+ weight_2=weight_cur,
386
+ )
387
+
388
+
389
+ def average_checkpoints_with_averaged_model(
390
+ filename_start: str,
391
+ filename_end: str,
392
+ device: torch.device = torch.device("cpu"),
393
+ ) -> Dict[str, Tensor]:
394
+ """Average model parameters over the range with given
395
+ start model (excluded) and end model.
396
+
397
+ Let start = batch_idx_train of model-start;
398
+ end = batch_idx_train of model-end;
399
+ interval = end - start.
400
+ Then the average model over range from start (excluded) to end is
401
+ (1) avg = (model_end * end - model_start * start) / interval.
402
+ It can be written as
403
+ (2) avg = model_end * weight_end + model_start * weight_start,
404
+ where weight_end = end / interval,
405
+ weight_start = -start / interval = 1 - weight_end.
406
+ Since the terms `weight_end` and `weight_start` would be large
407
+ if the model has been trained for lots of batches, which would cause
408
+ overflow when multiplying the model parameters.
409
+ To avoid this, we rewrite (2) as:
410
+ (3) avg = (model_end + model_start * (weight_start / weight_end))
411
+ * weight_end
412
+
413
+ The model index could be epoch number or iteration number.
414
+
415
+ Args:
416
+ filename_start:
417
+ Checkpoint filename of the start model. We assume it
418
+ is saved by :func:`save_checkpoint`.
419
+ filename_end:
420
+ Checkpoint filename of the end model. We assume it
421
+ is saved by :func:`save_checkpoint`.
422
+ device:
423
+ Move checkpoints to this device before averaging.
424
+ """
425
+ state_dict_start = torch.load(
426
+ filename_start, map_location=device, weights_only=False
427
+ )
428
+ state_dict_end = torch.load(filename_end, map_location=device, weights_only=False)
429
+
430
+ average_period = state_dict_start["average_period"]
431
+
432
+ batch_idx_train_start = state_dict_start["batch_idx_train"]
433
+ batch_idx_train_start = (batch_idx_train_start // average_period) * average_period
434
+ batch_idx_train_end = state_dict_end["batch_idx_train"]
435
+ batch_idx_train_end = (batch_idx_train_end // average_period) * average_period
436
+ interval = batch_idx_train_end - batch_idx_train_start
437
+ assert interval > 0, interval
438
+ weight_end = batch_idx_train_end / interval
439
+ weight_start = 1 - weight_end
440
+
441
+ model_end = state_dict_end["model_avg"]
442
+ model_start = state_dict_start["model_avg"]
443
+ avg = model_end
444
+
445
+ # scale the weight to avoid overflow
446
+ average_state_dict(
447
+ state_dict_1=avg,
448
+ state_dict_2=model_start,
449
+ weight_1=1.0,
450
+ weight_2=weight_start / weight_end,
451
+ scaling_factor=weight_end,
452
+ )
453
+
454
+ return avg
455
+
456
+
457
+ def average_state_dict(
458
+ state_dict_1: Dict[str, Tensor],
459
+ state_dict_2: Dict[str, Tensor],
460
+ weight_1: float,
461
+ weight_2: float,
462
+ scaling_factor: float = 1.0,
463
+ ) -> Dict[str, Tensor]:
464
+ """Average two state_dict with given weights:
465
+ state_dict_1 = (state_dict_1 * weight_1 + state_dict_2 * weight_2)
466
+ * scaling_factor
467
+ It is an in-place operation on state_dict_1 itself.
468
+ """
469
+ # Identify shared parameters. Two parameters are said to be shared
470
+ # if they have the same data_ptr
471
+ uniqued: Dict[int, str] = dict()
472
+ for k, v in state_dict_1.items():
473
+ v_data_ptr = v.data_ptr()
474
+ if v_data_ptr in uniqued:
475
+ continue
476
+ uniqued[v_data_ptr] = k
477
+
478
+ uniqued_names = list(uniqued.values())
479
+ for k in uniqued_names:
480
+ v = state_dict_1[k]
481
+ if torch.is_floating_point(v):
482
+ v *= weight_1
483
+ v += state_dict_2[k].to(device=state_dict_1[k].device) * weight_2
484
+ v *= scaling_factor
icefall/context_graph.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Xiaomi Corp. (authors: Wei Kang)
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
+ import os
18
+ import shutil
19
+ from collections import deque
20
+ from typing import Dict, List, Optional, Tuple, Union
21
+
22
+
23
+ class ContextState:
24
+ """The state in ContextGraph"""
25
+
26
+ def __init__(
27
+ self,
28
+ id: int,
29
+ token: int,
30
+ token_score: float,
31
+ node_score: float,
32
+ output_score: float,
33
+ is_end: bool,
34
+ level: int,
35
+ phrase: str = "",
36
+ ac_threshold: float = 1.0,
37
+ ):
38
+ """Create a ContextState.
39
+
40
+ Args:
41
+ id:
42
+ The node id, only for visualization now. A node is in [0, graph.num_nodes).
43
+ The id of the root node is always 0.
44
+ token:
45
+ The token id.
46
+ token_score:
47
+ The bonus for each token during decoding, which will hopefully
48
+ boost the token up to survive beam search.
49
+ node_score:
50
+ The accumulated bonus from root of graph to current node, it will be
51
+ used to calculate the score for fail arc.
52
+ output_score:
53
+ The total scores of matched phrases, sum of the node_score of all
54
+ the output node for current node.
55
+ is_end:
56
+ True if current token is the end of a context.
57
+ level:
58
+ The distance from current node to root.
59
+ phrase:
60
+ The context phrase of current state, the value is valid only when
61
+ current state is end state (is_end == True).
62
+ ac_threshold:
63
+ The acoustic threshold (probability) of current context phrase, the
64
+ value is valid only when current state is end state (is_end == True).
65
+ Note: ac_threshold only used in keywords spotting.
66
+ """
67
+ self.id = id
68
+ self.token = token
69
+ self.token_score = token_score
70
+ self.node_score = node_score
71
+ self.output_score = output_score
72
+ self.is_end = is_end
73
+ self.level = level
74
+ self.next = {}
75
+ self.phrase = phrase
76
+ self.ac_threshold = ac_threshold
77
+ self.fail = None
78
+ self.output = None
79
+
80
+
81
+ class ContextGraph:
82
+ """The ContextGraph is modified from Aho-Corasick which is mainly
83
+ a Trie with a fail arc for each node.
84
+ See https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm for more details
85
+ of Aho-Corasick algorithm.
86
+
87
+ A ContextGraph contains some words / phrases that we expect to boost their
88
+ scores during decoding. If the substring of a decoded sequence matches the word / phrase
89
+ in the ContextGraph, we will give the decoded sequence a bonus to make it survive
90
+ beam search.
91
+ """
92
+
93
+ def __init__(self, context_score: float, ac_threshold: float = 1.0):
94
+ """Initialize a ContextGraph with the given ``context_score``.
95
+
96
+ A root node will be created (**NOTE:** the token of root is hardcoded to -1).
97
+
98
+ Args:
99
+ context_score:
100
+ The bonus score for each token(note: NOT for each word/phrase, it means longer
101
+ word/phrase will have larger bonus score, they have to be matched though).
102
+ Note: This is just the default score for each token, the users can manually
103
+ specify the context_score for each word/phrase (i.e. different phrase might
104
+ have different token score).
105
+ ac_threshold:
106
+ The acoustic threshold (probability) to trigger the word/phrase, this argument
107
+ is used only when applying the graph to keywords spotting system.
108
+ """
109
+ self.context_score = context_score
110
+ self.ac_threshold = ac_threshold
111
+ self.num_nodes = 0
112
+ self.root = ContextState(
113
+ id=self.num_nodes,
114
+ token=-1,
115
+ token_score=0,
116
+ node_score=0,
117
+ output_score=0,
118
+ is_end=False,
119
+ level=0,
120
+ )
121
+ self.root.fail = self.root
122
+
123
+ def _fill_fail_output(self):
124
+ """This function fills the fail arc for each trie node, it can be computed
125
+ in linear time by performing a breadth-first search starting from the root.
126
+ See https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm for the
127
+ details of the algorithm.
128
+ """
129
+ queue = deque()
130
+ for token, node in self.root.next.items():
131
+ node.fail = self.root
132
+ queue.append(node)
133
+ while queue:
134
+ current_node = queue.popleft()
135
+ for token, node in current_node.next.items():
136
+ fail = current_node.fail
137
+ if token in fail.next:
138
+ fail = fail.next[token]
139
+ else:
140
+ fail = fail.fail
141
+ while token not in fail.next:
142
+ fail = fail.fail
143
+ if fail.token == -1: # root
144
+ break
145
+ if token in fail.next:
146
+ fail = fail.next[token]
147
+ node.fail = fail
148
+ # fill the output arc
149
+ output = node.fail
150
+ while not output.is_end:
151
+ output = output.fail
152
+ if output.token == -1: # root
153
+ output = None
154
+ break
155
+ node.output = output
156
+ node.output_score += 0 if output is None else output.output_score
157
+ queue.append(node)
158
+
159
+ def build(
160
+ self,
161
+ token_ids: List[List[int]],
162
+ phrases: Optional[List[str]] = None,
163
+ scores: Optional[List[float]] = None,
164
+ ac_thresholds: Optional[List[float]] = None,
165
+ ):
166
+ """Build the ContextGraph from a list of token list.
167
+ It first build a trie from the given token lists, then fill the fail arc
168
+ for each trie node.
169
+
170
+ See https://en.wikipedia.org/wiki/Trie for how to build a trie.
171
+
172
+ Args:
173
+ token_ids:
174
+ The given token lists to build the ContextGraph, it is a list of
175
+ token list, the token list contains the token ids
176
+ for a word/phrase. The token id could be an id of a char
177
+ (modeling with single Chinese char) or an id of a BPE
178
+ (modeling with BPEs).
179
+ phrases:
180
+ The given phrases, they are the original text of the token_ids, the
181
+ length of `phrases` MUST be equal to the length of `token_ids`.
182
+ scores:
183
+ The customize boosting score(token level) for each word/phrase,
184
+ 0 means using the default value (i.e. self.context_score).
185
+ It is a list of floats, and the length of `scores` MUST be equal to
186
+ the length of `token_ids`.
187
+ ac_thresholds:
188
+ The customize trigger acoustic threshold (probability) for each phrase,
189
+ 0 means using the default value (i.e. self.ac_threshold). It is
190
+ used only when this graph applied for the keywords spotting system.
191
+ The length of `ac_threshold` MUST be equal to the length of `token_ids`.
192
+
193
+ Note: The phrases would have shared states, the score of the shared states is
194
+ the MAXIMUM value among all the tokens sharing this state.
195
+ """
196
+ num_phrases = len(token_ids)
197
+ if phrases is not None:
198
+ assert len(phrases) == num_phrases, (len(phrases), num_phrases)
199
+ if scores is not None:
200
+ assert len(scores) == num_phrases, (len(scores), num_phrases)
201
+ if ac_thresholds is not None:
202
+ assert len(ac_thresholds) == num_phrases, (len(ac_thresholds), num_phrases)
203
+
204
+ for index, tokens in enumerate(token_ids):
205
+ phrase = "" if phrases is None else phrases[index]
206
+ score = 0.0 if scores is None else scores[index]
207
+ ac_threshold = 0.0 if ac_thresholds is None else ac_thresholds[index]
208
+ node = self.root
209
+ # If has customized score using the customized token score, otherwise
210
+ # using the default score
211
+ context_score = self.context_score if score == 0.0 else score
212
+ threshold = self.ac_threshold if ac_threshold == 0.0 else ac_threshold
213
+ for i, token in enumerate(tokens):
214
+ node_next = {}
215
+ if token not in node.next:
216
+ self.num_nodes += 1
217
+ is_end = i == len(tokens) - 1
218
+ node_score = node.node_score + context_score
219
+ node.next[token] = ContextState(
220
+ id=self.num_nodes,
221
+ token=token,
222
+ token_score=context_score,
223
+ node_score=node_score,
224
+ output_score=node_score if is_end else 0,
225
+ is_end=is_end,
226
+ level=i + 1,
227
+ phrase=phrase if is_end else "",
228
+ ac_threshold=threshold if is_end else 0.0,
229
+ )
230
+ else:
231
+ # node exists, get the score of shared state.
232
+ token_score = max(context_score, node.next[token].token_score)
233
+ node.next[token].token_score = token_score
234
+ node_score = node.node_score + token_score
235
+ node.next[token].node_score = node_score
236
+ is_end = i == len(tokens) - 1 or node.next[token].is_end
237
+ node.next[token].output_score = node_score if is_end else 0
238
+ node.next[token].is_end = is_end
239
+ if i == len(tokens) - 1:
240
+ node.next[token].phrase = phrase
241
+ node.next[token].ac_threshold = threshold
242
+ node = node.next[token]
243
+ self._fill_fail_output()
244
+
245
+ def forward_one_step(
246
+ self, state: ContextState, token: int, strict_mode: bool = True
247
+ ) -> Tuple[float, ContextState, ContextState]:
248
+ """Search the graph with given state and token.
249
+
250
+ Args:
251
+ state:
252
+ The given token containing trie node to start.
253
+ token:
254
+ The given token.
255
+ strict_mode:
256
+ If the `strict_mode` is True, it can match multiple phrases simultaneously,
257
+ and will continue to match longer phrase after matching a shorter one.
258
+ If the `strict_mode` is False, it can only match one phrase at a time,
259
+ when it matches a phrase, then the state will fall back to root state
260
+ (i.e. forgetting all the history state and starting a new match). If
261
+ the matched state have multiple outputs (node.output is not None), the
262
+ longest phrase will be return.
263
+ For example, if the phrases are `he`, `she` and `shell`, the query is
264
+ `like shell`, when `strict_mode` is True, the query will match `he` and
265
+ `she` at token `e` and `shell` at token `l`, while when `strict_mode`
266
+ if False, the query can only match `she`(`she` is longer than `he`, so
267
+ `she` not `he`) at token `e`.
268
+ Caution: When applying this graph for keywords spotting system, the
269
+ `strict_mode` MUST be True.
270
+
271
+ Returns:
272
+ Return a tuple of boosting score for current state, next state and matched
273
+ state (if any). Note: Only returns the matched state with longest phrase of
274
+ current state, even if there are multiple matches phrases. If no phrase
275
+ matched, the matched state is None.
276
+ """
277
+ node = None
278
+ score = 0
279
+ # token matched
280
+ if token in state.next:
281
+ node = state.next[token]
282
+ score = node.token_score
283
+ else:
284
+ # token not matched
285
+ # We will trace along the fail arc until it matches the token or reaching
286
+ # root of the graph.
287
+ node = state.fail
288
+ while token not in node.next:
289
+ node = node.fail
290
+ if node.token == -1: # root
291
+ break
292
+
293
+ if token in node.next:
294
+ node = node.next[token]
295
+
296
+ # The score of the fail path
297
+ score = node.node_score - state.node_score
298
+ assert node is not None
299
+
300
+ # The matched node of current step, will only return the node with
301
+ # longest phrase if there are multiple phrases matches this step.
302
+ # None if no matched phrase.
303
+ matched_node = (
304
+ node if node.is_end else (node.output if node.output is not None else None)
305
+ )
306
+ if not strict_mode and node.output_score != 0:
307
+ # output_score != 0 means at least on phrase matched
308
+ assert matched_node is not None
309
+ output_score = (
310
+ node.node_score
311
+ if node.is_end
312
+ else (
313
+ node.node_score if node.output is None else node.output.node_score
314
+ )
315
+ )
316
+ return (score + output_score - node.node_score, self.root, matched_node)
317
+ assert (node.output_score != 0 and matched_node is not None) or (
318
+ node.output_score == 0 and matched_node is None
319
+ ), (
320
+ node.output_score,
321
+ matched_node,
322
+ )
323
+ return (score + node.output_score, node, matched_node)
324
+
325
+ def is_matched(self, state: ContextState) -> Tuple[bool, ContextState]:
326
+ """Whether current state matches any phrase (i.e. current state is the
327
+ end state or the output of current state is not None.
328
+
329
+ Args:
330
+ state:
331
+ The given state(trie node).
332
+
333
+ Returns:
334
+ Return a tuple of status and matched state.
335
+ """
336
+ if state.is_end:
337
+ return True, state
338
+ else:
339
+ if state.output is not None:
340
+ return True, state.output
341
+ return False, None
342
+
343
+ def finalize(self, state: ContextState) -> Tuple[float, ContextState]:
344
+ """When reaching the end of the decoded sequence, we need to finalize
345
+ the matching, the purpose is to subtract the added bonus score for the
346
+ state that is not the end of a word/phrase.
347
+
348
+ Args:
349
+ state:
350
+ The given state(trie node).
351
+
352
+ Returns:
353
+ Return a tuple of score and next state. If state is the end of a word/phrase
354
+ the score is zero, otherwise the score is the score of a implicit fail arc
355
+ to root. The next state is always root.
356
+ """
357
+ # The score of the fail arc
358
+ score = -state.node_score
359
+ return (score, self.root)
360
+
361
+ def draw(
362
+ self,
363
+ title: Optional[str] = None,
364
+ filename: Optional[str] = "",
365
+ symbol_table: Optional[Dict[int, str]] = None,
366
+ ) -> "Digraph": # noqa
367
+ """Visualize a ContextGraph via graphviz.
368
+
369
+ Render ContextGraph as an image via graphviz, and return the Digraph object;
370
+ and optionally save to file `filename`.
371
+ `filename` must have a suffix that graphviz understands, such as
372
+ `pdf`, `svg` or `png`.
373
+
374
+ Note:
375
+ You need to install graphviz to use this function::
376
+
377
+ pip install graphviz
378
+
379
+ Args:
380
+ title:
381
+ Title to be displayed in image, e.g. 'A simple FSA example'
382
+ filename:
383
+ Filename to (optionally) save to, e.g. 'foo.png', 'foo.svg',
384
+ 'foo.png' (must have a suffix that graphviz understands).
385
+ symbol_table:
386
+ Map the token ids to symbols.
387
+ Returns:
388
+ A Diagraph from grahpviz.
389
+ """
390
+
391
+ try:
392
+ import graphviz
393
+ except Exception:
394
+ print("You cannot use `to_dot` unless the graphviz package is installed.")
395
+ raise
396
+
397
+ graph_attr = {
398
+ "rankdir": "LR",
399
+ "size": "8.5,11",
400
+ "center": "1",
401
+ "orientation": "Portrait",
402
+ "ranksep": "0.4",
403
+ "nodesep": "0.25",
404
+ }
405
+ if title is not None:
406
+ graph_attr["label"] = title
407
+
408
+ default_node_attr = {
409
+ "shape": "circle",
410
+ "style": "bold",
411
+ "fontsize": "14",
412
+ }
413
+
414
+ final_state_attr = {
415
+ "shape": "doublecircle",
416
+ "style": "bold",
417
+ "fontsize": "14",
418
+ }
419
+
420
+ final_state = -1
421
+ dot = graphviz.Digraph(name="Context Graph", graph_attr=graph_attr)
422
+
423
+ seen = set()
424
+ queue = deque()
425
+ queue.append(self.root)
426
+ # root id is always 0
427
+ dot.node("0", label="0", **default_node_attr)
428
+ dot.edge("0", "0", color="red")
429
+ seen.add(0)
430
+
431
+ while len(queue):
432
+ current_node = queue.popleft()
433
+ for token, node in current_node.next.items():
434
+ if node.id not in seen:
435
+ node_score = f"{node.node_score:.2f}".rstrip("0").rstrip(".")
436
+ output_score = f"{node.output_score:.2f}".rstrip("0").rstrip(".")
437
+ label = f"{node.id}/({node_score}, {output_score})"
438
+ if node.is_end:
439
+ dot.node(str(node.id), label=label, **final_state_attr)
440
+ else:
441
+ dot.node(str(node.id), label=label, **default_node_attr)
442
+ seen.add(node.id)
443
+ weight = f"{node.token_score:.2f}".rstrip("0").rstrip(".")
444
+ label = str(token) if symbol_table is None else symbol_table[token]
445
+ dot.edge(str(current_node.id), str(node.id), label=f"{label}/{weight}")
446
+ dot.edge(
447
+ str(node.id),
448
+ str(node.fail.id),
449
+ color="red",
450
+ )
451
+ if node.output is not None:
452
+ dot.edge(
453
+ str(node.id),
454
+ str(node.output.id),
455
+ color="green",
456
+ )
457
+ queue.append(node)
458
+
459
+ if filename:
460
+ _, extension = os.path.splitext(filename)
461
+ if extension == "" or extension[0] != ".":
462
+ raise ValueError(
463
+ "Filename needs to have a suffix like .png, .pdf, .svg: {}".format(
464
+ filename
465
+ )
466
+ )
467
+
468
+ import tempfile
469
+
470
+ with tempfile.TemporaryDirectory() as tmp_dir:
471
+ temp_fn = dot.render(
472
+ filename="temp",
473
+ directory=tmp_dir,
474
+ format=extension[1:],
475
+ cleanup=True,
476
+ )
477
+
478
+ shutil.move(temp_fn, filename)
479
+
480
+ return dot
481
+
482
+
483
+ def _test(queries, score, strict_mode):
484
+ contexts_str = [
485
+ "S",
486
+ "HE",
487
+ "SHE",
488
+ "SHELL",
489
+ "HIS",
490
+ "HERS",
491
+ "HELLO",
492
+ "THIS",
493
+ "THEM",
494
+ ]
495
+
496
+ # test default score (1)
497
+ contexts = []
498
+ scores = []
499
+ phrases = []
500
+ for s in contexts_str:
501
+ contexts.append([ord(x) for x in s])
502
+ scores.append(round(score / len(s), 2))
503
+ phrases.append(s)
504
+
505
+ context_graph = ContextGraph(context_score=1)
506
+ context_graph.build(token_ids=contexts, scores=scores, phrases=phrases)
507
+
508
+ symbol_table = {}
509
+ for contexts in contexts_str:
510
+ for s in contexts:
511
+ symbol_table[ord(s)] = s
512
+
513
+ context_graph.draw(
514
+ title="Graph for: " + " / ".join(contexts_str),
515
+ filename=f"context_graph_{score}.pdf",
516
+ symbol_table=symbol_table,
517
+ )
518
+
519
+ for query, expected_score in queries.items():
520
+ total_scores = 0
521
+ state = context_graph.root
522
+ for q in query:
523
+ score, state, phrase = context_graph.forward_one_step(
524
+ state, ord(q), strict_mode
525
+ )
526
+ total_scores += score
527
+ score, state = context_graph.finalize(state)
528
+ assert state.token == -1, state.token
529
+ total_scores += score
530
+ assert round(total_scores, 2) == expected_score, (
531
+ total_scores,
532
+ expected_score,
533
+ query,
534
+ )
535
+
536
+
537
+ if __name__ == "__main__":
538
+ # test default score
539
+ queries = {
540
+ "HEHERSHE": 14, # "HE", "HE", "HERS", "S", "SHE", "HE"
541
+ "HERSHE": 12, # "HE", "HERS", "S", "SHE", "HE"
542
+ "HISHE": 9, # "HIS", "S", "SHE", "HE"
543
+ "SHED": 6, # "S", "SHE", "HE"
544
+ "SHELF": 6, # "S", "SHE", "HE"
545
+ "HELL": 2, # "HE"
546
+ "HELLO": 7, # "HE", "HELLO"
547
+ "DHRHISQ": 4, # "HIS", "S"
548
+ "THEN": 2, # "HE"
549
+ }
550
+ _test(queries, 0, True)
551
+
552
+ queries = {
553
+ "HEHERSHE": 7, # "HE", "HE", "S", "HE"
554
+ "HERSHE": 5, # "HE", "S", "HE"
555
+ "HISHE": 5, # "HIS", "HE"
556
+ "SHED": 3, # "S", "HE"
557
+ "SHELF": 3, # "S", "HE"
558
+ "HELL": 2, # "HE"
559
+ "HELLO": 2, # "HE"
560
+ "DHRHISQ": 3, # "HIS"
561
+ "THEN": 2, # "HE"
562
+ }
563
+ _test(queries, 0, False)
564
+
565
+ # test custom score
566
+ # S : 5
567
+ # HE : 5 (2.5 + 2.5)
568
+ # SHE : 8.34 (5 + 1.67 + 1.67)
569
+ # SHELL : 10.34 (5 + 1.67 + 1.67 + 1 + 1)
570
+ # HIS : 5.84 (2.5 + 1.67 + 1.67)
571
+ # HERS : 7.5 (2.5 + 2.5 + 1.25 + 1.25)
572
+ # HELLO : 8 (2.5 + 2.5 + 1 + 1 + 1)
573
+ # THIS : 5 (1.25 + 1.25 + 1.25 + 1.25)
574
+ queries = {
575
+ "HEHERSHE": 35.84, # "HE", "HE", "HERS", "S", "SHE", "HE"
576
+ "HERSHE": 30.84, # "HE", "HERS", "S", "SHE", "HE"
577
+ "HISHE": 24.18, # "HIS", "S", "SHE", "HE"
578
+ "SHED": 18.34, # "S", "SHE", "HE"
579
+ "SHELF": 18.34, # "S", "SHE", "HE"
580
+ "HELL": 5, # "HE"
581
+ "HELLO": 13, # "HE", "HELLO"
582
+ "DHRHISQ": 10.84, # "HIS", "S"
583
+ "THEN": 5, # "HE"
584
+ }
585
+
586
+ _test(queries, 5, True)
587
+
588
+ queries = {
589
+ "HEHERSHE": 20, # "HE", "HE", "S", "HE"
590
+ "HERSHE": 15, # "HE", "S", "HE"
591
+ "HISHE": 10.84, # "HIS", "HE"
592
+ "SHED": 10, # "S", "HE"
593
+ "SHELF": 10, # "S", "HE"
594
+ "HELL": 5, # "HE"
595
+ "HELLO": 5, # "HE"
596
+ "DHRHISQ": 5.84, # "HIS"
597
+ "THEN": 5, # "HE"
598
+ }
599
+ _test(queries, 5, False)
icefall/ctc/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.pdf
2
+ *.gv
icefall/ctc/README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+
3
+ This folder uses [kaldifst][kaldifst] for graph construction
4
+ and decoders from [kaldi-decoder][kaldi-decoder] for CTC decoding.
5
+
6
+ It supports only `CPU`.
7
+
8
+ You can use
9
+
10
+ ```bash
11
+ pip install kaldifst kaldi-decoder
12
+ ```
13
+ to install the dependencies.
14
+
15
+ [kaldi-decoder]: https://github.com/k2-fsa/kaldi-decoder
16
+ [kaldifst]: https://github.com/k2-fsa/kaldifst
17
+ [k2]: https://github.com/k2-fsa/k2
icefall/ctc/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .prepare_lang import (
2
+ Lexicon,
3
+ make_lexicon_fst_no_silence,
4
+ make_lexicon_fst_with_silence,
5
+ )
6
+ from .topo import add_disambig_self_loops, add_one, build_standard_ctc_topo
7
+ from .utils import merge_tokens
icefall/ctc/prepare_lang.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Xiaomi Corp. (author: Fangjun Kuang)
2
+
3
+ """
4
+ The lang_dir should contain the following files:
5
+ - "lexicon_disambig.txt"
6
+ - "tokens.txt"
7
+ - "words.txt"
8
+ """
9
+
10
+ import math
11
+ import re
12
+ from collections import defaultdict
13
+ from pathlib import Path
14
+ from typing import List, Tuple
15
+
16
+ import kaldifst
17
+
18
+
19
+ class Lexicon:
20
+ """Once constructed it is immutable"""
21
+
22
+ def __init__(
23
+ self,
24
+ lang_dir: str,
25
+ disambig_pattern: str = re.compile(r"^#\d+$"),
26
+ ):
27
+ """
28
+ Args:
29
+ lang_dir:
30
+ The path to the lang directory. We expect that it contains the
31
+ following files:
32
+ - lexicon_disambig.txt
33
+ - tokens.txt
34
+ - words.txt
35
+
36
+ The format of the above files is described below.
37
+
38
+ (1) lexicon_disambig.txt
39
+
40
+ Each line in the lexicon_disambig.txt has the following format:
41
+
42
+ word token1 token2 ... tokenN
43
+
44
+ That is, the first field is the word, the remaining fields are
45
+ pronunciations of this word. Fields are separated by space(s).
46
+
47
+ (2) tokens.txt
48
+
49
+ Each line in tokens.txt has two fields separated by space(s):
50
+
51
+ token ID
52
+
53
+ The first field is the token symbol and the second filed is the
54
+ integer ID of the token.
55
+
56
+ (3) words.txt
57
+
58
+ Each line in words.txt has two fields separated by space(s):
59
+
60
+ word ID
61
+
62
+ The first field is the word symbol and the second filed is the
63
+ integer ID of the word.
64
+ disambig_pattern:
65
+ It contains the pattern for disambiguation symbols.
66
+ """
67
+ lang_dir = Path(lang_dir)
68
+
69
+ lexicon_txt = lang_dir / "lexicon_disambig.txt"
70
+ tokens_txt = lang_dir / "tokens.txt"
71
+ words_txt = lang_dir / "words.txt"
72
+
73
+ assert lexicon_txt.is_file(), lexicon_txt
74
+ assert tokens_txt.is_file(), tokens_txt
75
+ assert words_txt.is_file(), words_txt
76
+
77
+ self._read_lexicon(lexicon_txt)
78
+ self._read_tokens(tokens_txt)
79
+ self._read_words(words_txt)
80
+
81
+ self.disambig_pattern = disambig_pattern
82
+
83
+ max_disambig_id = -1
84
+ for s, i in self.token2id.items():
85
+ if self.disambig_pattern.match(s) and i > max_disambig_id:
86
+ max_disambig_id = i
87
+
88
+ self.max_disambig_id = max_disambig_id
89
+
90
+ def _read_lexicon(self, lexicon_txt: str):
91
+ word2phones = defaultdict(list)
92
+ with open(lexicon_txt, encoding="utf-8") as f:
93
+ for line in f:
94
+ word_phones = line.strip().split()
95
+ assert len(word_phones) >= 2, (word_phones, line)
96
+ word = word_phones[0]
97
+ phones: str = " ".join(word_phones[1:])
98
+ word2phones[word].append(phones)
99
+ # We use a list here since a word may have multiple
100
+ # pronunciations
101
+
102
+ self.word2phones = word2phones
103
+
104
+ def _read_tokens(self, tokens_txt):
105
+ token2id = dict()
106
+ id2token = dict()
107
+ with open(tokens_txt, encoding="utf-8") as f:
108
+ for line in f:
109
+ token_id = line.strip().split()
110
+ assert len(token_id) == 2, token_id
111
+
112
+ token = token_id[0]
113
+ idx = int(token_id[1])
114
+
115
+ assert token not in token2id, f"Duplicate token {line}"
116
+ assert idx not in id2token, f"Duplicate ID {line}"
117
+
118
+ token2id[token] = idx
119
+ id2token[idx] = token
120
+ self.token2id = token2id
121
+ self.id2token = id2token
122
+
123
+ def _read_words(self, words_txt):
124
+ word2id = dict()
125
+ id2word = dict()
126
+ with open(words_txt, encoding="utf-8") as f:
127
+ for line in f:
128
+ word_id = line.strip().split()
129
+ assert len(word_id) == 2, word_id
130
+
131
+ word = word_id[0]
132
+ idx = int(word_id[1])
133
+
134
+ assert word not in word2id, f"Duplicate token {line}"
135
+ assert idx not in id2word, f"Duplicate ID {line}"
136
+
137
+ word2id[word] = idx
138
+ id2word[idx] = word
139
+
140
+ self.word2id = word2id
141
+ self.id2word = id2word
142
+
143
+ def __iter__(self) -> Tuple[str, List[str]]:
144
+ for word, phones_list in self.word2phones.items():
145
+ for phones in phones_list:
146
+ yield word, phones
147
+
148
+ def __str__(self):
149
+ return str(self.word2phones)
150
+
151
+ @property
152
+ def tokens(self) -> List[int]:
153
+ """Return a list of token IDs excluding those from
154
+ disambiguation symbols.
155
+
156
+ Caution:
157
+ 0 is not a token ID so it is excluded from the return value.
158
+ """
159
+ ans = []
160
+ for s in self.token2id:
161
+ if not self.disambig_pattern.match(s):
162
+ ans.append(self.token2id[s])
163
+ if 0 in ans:
164
+ ans.remove(0)
165
+ ans.sort()
166
+ return ans
167
+
168
+
169
+ # See also
170
+ # http://vpanayotov.blogspot.com/2012/06/kaldi-decoding-graph-construction.html
171
+ def make_lexicon_fst_with_silence(
172
+ lexicon: Lexicon,
173
+ sil_prob: float = 0.5,
174
+ sil_phone: str = "SIL",
175
+ attach_symbol_table: bool = True,
176
+ ) -> kaldifst.StdVectorFst:
177
+ phone2id = lexicon.token2id
178
+ word2id = lexicon.word2id
179
+
180
+ assert sil_phone in phone2id
181
+
182
+ assert sil_phone in phone2id, sil_phone
183
+
184
+ sil_cost = -1 * math.log(sil_prob)
185
+ no_sil_cost = -1 * math.log(1.0 - sil_prob)
186
+
187
+ fst = kaldifst.StdVectorFst()
188
+
189
+ start_state = fst.add_state()
190
+ loop_state = fst.add_state()
191
+ sil_state = fst.add_state()
192
+
193
+ fst.start = start_state
194
+ fst.set_final(state=loop_state, weight=0)
195
+
196
+ fst.add_arc(
197
+ state=start_state,
198
+ arc=kaldifst.StdArc(
199
+ ilabel=0,
200
+ olabel=0,
201
+ weight=no_sil_cost,
202
+ nextstate=loop_state,
203
+ ),
204
+ )
205
+
206
+ fst.add_arc(
207
+ state=start_state,
208
+ arc=kaldifst.StdArc(
209
+ ilabel=0,
210
+ olabel=0,
211
+ weight=sil_cost,
212
+ nextstate=sil_state,
213
+ ),
214
+ )
215
+
216
+ fst.add_arc(
217
+ state=sil_state,
218
+ arc=kaldifst.StdArc(
219
+ ilabel=phone2id[sil_phone],
220
+ olabel=0,
221
+ weight=0,
222
+ nextstate=loop_state,
223
+ ),
224
+ )
225
+
226
+ for word, phones in lexicon:
227
+ phoneseq = phones.split()
228
+ pron_cost = 0
229
+ cur_state = loop_state
230
+
231
+ for i in range(len(phoneseq) - 1):
232
+ next_state = fst.add_state()
233
+ fst.add_arc(
234
+ state=cur_state,
235
+ arc=kaldifst.StdArc(
236
+ ilabel=phone2id[phoneseq[i]],
237
+ olabel=word2id[word] if i == 0 else 0,
238
+ weight=pron_cost if i == 0 else 0,
239
+ nextstate=next_state,
240
+ ),
241
+ )
242
+ cur_state = next_state
243
+
244
+ i = len(phoneseq) - 1 # note: i == -1 if phoneseq is empty.
245
+
246
+ fst.add_arc(
247
+ state=cur_state,
248
+ arc=kaldifst.StdArc(
249
+ ilabel=phone2id[phoneseq[i]] if i >= 0 else 0,
250
+ olabel=word2id[word] if i <= 0 else 0,
251
+ weight=no_sil_cost + (pron_cost if i <= 0 else 0),
252
+ nextstate=loop_state,
253
+ ),
254
+ )
255
+
256
+ fst.add_arc(
257
+ state=cur_state,
258
+ arc=kaldifst.StdArc(
259
+ ilabel=phone2id[phoneseq[i]] if i >= 0 else 0,
260
+ olabel=word2id[word] if i <= 0 else 0,
261
+ weight=sil_cost + (pron_cost if i <= 0 else 0),
262
+ nextstate=sil_state,
263
+ ),
264
+ )
265
+
266
+ if attach_symbol_table:
267
+ isym = kaldifst.SymbolTable()
268
+ for p, i in phone2id.items():
269
+ isym.add_symbol(symbol=p, key=i)
270
+ fst.input_symbols = isym
271
+
272
+ osym = kaldifst.SymbolTable()
273
+ for w, i in word2id.items():
274
+ osym.add_symbol(symbol=w, key=i)
275
+ fst.output_symbols = osym
276
+
277
+ return fst
278
+
279
+
280
+ def make_lexicon_fst_no_silence(
281
+ lexicon: Lexicon,
282
+ attach_symbol_table: bool = True,
283
+ ) -> kaldifst.StdVectorFst:
284
+ phone2id = lexicon.token2id
285
+ word2id = lexicon.word2id
286
+
287
+ fst = kaldifst.StdVectorFst()
288
+
289
+ start_state = fst.add_state()
290
+ fst.start = start_state
291
+ fst.set_final(state=start_state, weight=0)
292
+
293
+ for word, phones in lexicon:
294
+ phoneseq = phones.split()
295
+ pron_cost = 0
296
+ cur_state = start_state
297
+
298
+ for i in range(len(phoneseq) - 1):
299
+ next_state = fst.add_state()
300
+ fst.add_arc(
301
+ state=cur_state,
302
+ arc=kaldifst.StdArc(
303
+ ilabel=phone2id[phoneseq[i]],
304
+ olabel=word2id[word] if i == 0 else 0,
305
+ weight=pron_cost if i == 0 else 0,
306
+ nextstate=next_state,
307
+ ),
308
+ )
309
+ cur_state = next_state
310
+
311
+ i = len(phoneseq) - 1 # note: i == -1 if phoneseq is empty.
312
+
313
+ fst.add_arc(
314
+ state=cur_state,
315
+ arc=kaldifst.StdArc(
316
+ ilabel=phone2id[phoneseq[i]] if i >= 0 else 0,
317
+ olabel=word2id[word] if i <= 0 else 0,
318
+ weight=pron_cost if i <= 0 else 0,
319
+ nextstate=start_state,
320
+ ),
321
+ )
322
+
323
+ if attach_symbol_table:
324
+ isym = kaldifst.SymbolTable()
325
+ for p, i in phone2id.items():
326
+ isym.add_symbol(symbol=p, key=i)
327
+ fst.input_symbols = isym
328
+
329
+ osym = kaldifst.SymbolTable()
330
+ for w, i in word2id.items():
331
+ osym.add_symbol(symbol=w, key=i)
332
+ fst.output_symbols = osym
333
+
334
+ return fst
icefall/ctc/test_ctc_topo.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2023 Xiaomi Corp. (authors: Fangjun Kuang)
3
+
4
+ from pathlib import Path
5
+
6
+ import graphviz
7
+ import kaldifst
8
+ import sentencepiece as spm
9
+ from prepare_lang import (
10
+ Lexicon,
11
+ make_lexicon_fst_no_silence,
12
+ make_lexicon_fst_with_silence,
13
+ )
14
+ from topo import add_disambig_self_loops, add_one, build_standard_ctc_topo
15
+
16
+
17
+ def test_yesno():
18
+ lang_dir = "/Users/fangjun/open-source/icefall/egs/yesno/ASR/data/lang_phone"
19
+ if not Path(lang_dir).is_dir():
20
+ print(f"{lang_dir} does not exist! Skip testing")
21
+ return
22
+ lexicon = Lexicon(lang_dir)
23
+ max_token_id = max(lexicon.tokens)
24
+
25
+ H = build_standard_ctc_topo(max_token_id=max_token_id)
26
+
27
+ isym = kaldifst.SymbolTable()
28
+ isym.add_symbol(symbol="<blk>", key=0)
29
+ for i in range(1, max_token_id + 1):
30
+ isym.add_symbol(symbol=lexicon.id2token[i], key=i)
31
+
32
+ osym = kaldifst.SymbolTable()
33
+ osym.add_symbol(symbol="<eps>", key=0)
34
+ for i in range(1, max_token_id + 1):
35
+ osym.add_symbol(symbol=lexicon.id2token[i], key=i)
36
+
37
+ H.input_symbols = isym
38
+ H.output_symbols = osym
39
+
40
+ fst_dot = kaldifst.draw(H, acceptor=False, portrait=True)
41
+ source = graphviz.Source(fst_dot)
42
+ source.render(outfile="standard_ctc_topo_yesno.pdf")
43
+ # See the link below to visualize the above PDF
44
+ # https://t.ly/7uXZ9
45
+
46
+ # Now test HL
47
+
48
+ # We need to add one to all tokens since we want to use ID 0
49
+ # for epsilon
50
+ add_one(H, treat_ilabel_zero_specially=False, update_olabel=True)
51
+
52
+ add_disambig_self_loops(
53
+ H,
54
+ start=lexicon.token2id["#0"] + 1,
55
+ end=lexicon.max_disambig_id,
56
+ )
57
+
58
+ fst_dot = kaldifst.draw(H, acceptor=False, portrait=True)
59
+ source = graphviz.Source(fst_dot)
60
+ source.render(outfile="standard_ctc_topo_disambig_yesno.pdf")
61
+
62
+ L = make_lexicon_fst_with_silence(lexicon)
63
+
64
+ # We also need to change the input labels of L
65
+ add_one(L, treat_ilabel_zero_specially=True, update_olabel=False)
66
+
67
+ H.output_symbols = None
68
+
69
+ kaldifst.arcsort(H, sort_type="olabel")
70
+ kaldifst.arcsort(L, sort_type="ilabel")
71
+ HL = kaldifst.compose(H, L)
72
+
73
+ lexicon.id2token[0] = "<blk>"
74
+ lexicon.token2id["<blk>"] = 0
75
+
76
+ isym = kaldifst.SymbolTable()
77
+ isym.add_symbol(symbol="<eps>", key=0)
78
+ for i in range(0, lexicon.max_disambig_id + 1):
79
+ isym.add_symbol(symbol=lexicon.id2token[i], key=i + 1)
80
+
81
+ osym = kaldifst.SymbolTable()
82
+ for i, word in lexicon.id2word.items():
83
+ osym.add_symbol(symbol=word, key=i)
84
+
85
+ HL.input_symbols = isym
86
+ HL.output_symbols = osym
87
+
88
+ fst_dot = kaldifst.draw(HL, acceptor=False, portrait=True)
89
+ source = graphviz.Source(fst_dot)
90
+ source.render(outfile="HL_yesno.pdf")
91
+
92
+
93
+ def test_librispeech():
94
+ lang_dir = (
95
+ "/star-fj/fangjun/open-source/icefall-2/egs/librispeech/ASR/data/lang_bpe_500"
96
+ )
97
+
98
+ if not Path(lang_dir).is_dir():
99
+ print(f"{lang_dir} does not exist! Skip testing")
100
+ return
101
+
102
+ lexicon = Lexicon(lang_dir)
103
+ HL = kaldifst.StdVectorFst.read(lang_dir + "/HL.fst")
104
+
105
+ sp = spm.SentencePieceProcessor()
106
+ sp.load(lang_dir + "/bpe.model")
107
+
108
+ i = lexicon.word2id["HELLOA"]
109
+ k = lexicon.word2id["WORLD"]
110
+ print(i, k)
111
+ s = f"""
112
+ 0 1 {i} {i}
113
+ 1 2 {k} {k}
114
+ 2
115
+ """
116
+ fst = kaldifst.compile(
117
+ s=s,
118
+ acceptor=False,
119
+ )
120
+
121
+ L = make_lexicon_fst_no_silence(lexicon, attach_symbol_table=False)
122
+ kaldifst.arcsort(L, sort_type="olabel")
123
+ with open("L.fst.txt", "w") as f:
124
+ print(L, file=f)
125
+
126
+ fst = kaldifst.compose(L, fst)
127
+ print(fst)
128
+ fst_dot = kaldifst.draw(fst, acceptor=False, portrait=True)
129
+ source = graphviz.Source(fst_dot)
130
+ source.render(outfile="a.pdf")
131
+ print(sp.encode(["HELLOA", "WORLD"]))
132
+
133
+
134
+ def main():
135
+ test_yesno()
136
+ test_librispeech()
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
icefall/ctc/test_prepare_lang.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2023 Xiaomi Corp. (authors: Fangjun Kuang)
3
+
4
+ from pathlib import Path
5
+
6
+ import graphviz
7
+ import kaldifst
8
+ from prepare_lang import Lexicon, make_lexicon_fst_with_silence
9
+
10
+
11
+ def test_yesno():
12
+ lang_dir = "/Users/fangjun/open-source/icefall/egs/yesno/ASR/data/lang_phone"
13
+ if not Path(lang_dir).is_dir():
14
+ print(f"{lang_dir} does not exist! Skip testing")
15
+ return
16
+
17
+ lexicon = Lexicon(lang_dir)
18
+
19
+ L = make_lexicon_fst_with_silence(lexicon)
20
+
21
+ isym = kaldifst.SymbolTable()
22
+ for i, token in lexicon.id2token.items():
23
+ isym.add_symbol(symbol=token, key=i)
24
+
25
+ osym = kaldifst.SymbolTable()
26
+ for i, word in lexicon.id2word.items():
27
+ osym.add_symbol(symbol=word, key=i)
28
+
29
+ L.input_symbols = isym
30
+ L.output_symbols = osym
31
+ fst_dot = kaldifst.draw(L, acceptor=False, portrait=True)
32
+ source = graphviz.Source(fst_dot)
33
+ source.render(outfile="L_yesno.pdf")
34
+ # See the link below to visualize the above PDF
35
+ # https://t.ly/jMfXW
36
+
37
+
38
+ def main():
39
+ test_yesno()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
icefall/ctc/test_utils.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2024 Xiaomi Corp. (authors: Fangjun Kuang)
3
+
4
+ from typing import List
5
+
6
+ from utils import TokenSpan, merge_tokens
7
+
8
+
9
+ def inefficient_merge_tokens(alignment: List[int], blank: int = 0) -> List[TokenSpan]:
10
+ """Compute start and end frames of each token from the given alignment.
11
+
12
+ Args:
13
+ alignment:
14
+ A list of token IDs.
15
+ blank_id:
16
+ ID of the blank.
17
+ Returns:
18
+ Return a list of TokenSpan.
19
+ """
20
+ ans = []
21
+ last_token = None
22
+ last_i = None
23
+
24
+ # import pdb
25
+
26
+ # pdb.set_trace()
27
+ for i, token in enumerate(alignment):
28
+ if token == blank:
29
+ if last_token is None or last_token == token:
30
+ continue
31
+
32
+ # end of the last token
33
+ span = TokenSpan(token=last_token, start=last_i, end=i)
34
+ ans.append(span)
35
+ last_token = None
36
+ last_i = None
37
+ continue
38
+
39
+ # The current token is not a blank
40
+ if last_token is None or last_token == blank:
41
+ last_token = token
42
+ last_i = i
43
+ continue
44
+
45
+ if last_token == token:
46
+ continue
47
+
48
+ # end of the last token and start of the current token
49
+ span = TokenSpan(token=last_token, start=last_i, end=i)
50
+ last_token = token
51
+ last_i = i
52
+ ans.append(span)
53
+
54
+ if last_token is not None:
55
+ assert last_i is not None, (last_i, last_token)
56
+ span = TokenSpan(token=last_token, start=last_i, end=len(alignment))
57
+ # Note for the last token, its end is larger than len(alignment)-1
58
+ ans.append(span)
59
+
60
+ return ans
61
+
62
+
63
+ def test_merge_tokens():
64
+ data_list = [
65
+ # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
66
+ [0, 1, 1, 1, 2, 0, 0, 0, 2, 2, 3, 2, 3, 3, 0],
67
+ [0, 1, 1, 1, 2, 0, 0, 0, 2, 2, 3, 2, 3, 3],
68
+ [1, 1, 1, 2, 0, 0, 0, 2, 2, 3, 2, 3, 3, 0],
69
+ [1, 1, 1, 2, 0, 0, 0, 2, 2, 3, 2, 3, 3],
70
+ [0, 1, 2, 3, 0],
71
+ [1, 2, 3, 0],
72
+ [0, 1, 2, 3],
73
+ [1, 2, 3],
74
+ ]
75
+
76
+ for data in data_list:
77
+ span1 = merge_tokens(data)
78
+ span2 = inefficient_merge_tokens(data)
79
+ assert span1 == span2, (data, span1, span2)
80
+
81
+
82
+ def main():
83
+ test_merge_tokens()
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
icefall/ctc/topo.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Xiaomi Corp. (authors: Fangjun Kuang)
2
+
3
+ import kaldifst
4
+
5
+
6
+ # Note the name contains `standard`; it means there will be non-standard
7
+ # topologies.
8
+ def build_standard_ctc_topo(max_token_id: int) -> kaldifst.StdVectorFst:
9
+ """Build a standard CTC topology.
10
+
11
+ Args:
12
+ Maximum valid token ID. We assume token IDs are contiguous
13
+ and starts from 0. In other words, the vocabulary size is
14
+ ``max_token_id + 1``. We assume the ID of the blank symbol is 0.
15
+ """
16
+ # Token ID starts from 0 and there are as many states as the
17
+ # number of tokens.
18
+ #
19
+ # Note that epsilon is not a token and the token with ID 0 in tokens.txt
20
+ # is not an epsilon. It means input label 0 of the resulting FST does
21
+ # not represent an epsilon.
22
+ #
23
+ # You can use the function `add_one()` to modify the input/output labels
24
+ # of the resulting FST
25
+
26
+ num_states = max_token_id + 1
27
+
28
+ # Step 1: Create as many states as the number of tokens.
29
+ # Each state is a final state
30
+ fst = kaldifst.StdVectorFst()
31
+ for i in range(num_states):
32
+ s = fst.add_state()
33
+ fst.set_final(state=s, weight=0)
34
+
35
+ # Step 2: Set state 0 as the start state.
36
+ # We assume the ID of the blank symbol is 0.
37
+ fst.start = 0
38
+
39
+ # Step 3: Build a fully connected graph.
40
+ for i in range(num_states):
41
+ for k in range(num_states):
42
+ fst.add_arc(
43
+ state=i,
44
+ arc=kaldifst.StdArc(
45
+ ilabel=k,
46
+ olabel=k if i != k else 0, # if i==k, it is a self loop
47
+ weight=0,
48
+ nextstate=k,
49
+ ),
50
+ )
51
+ # Please see ./test_ctc_topo.py if you want to know what the resulting
52
+ # FST looks like
53
+
54
+ return fst
55
+
56
+
57
+ def add_one(
58
+ fst: kaldifst.StdVectorFst,
59
+ treat_ilabel_zero_specially: bool,
60
+ update_olabel: bool,
61
+ ) -> None:
62
+ """Modify the input and output labels of the given FST in-place.
63
+
64
+ Args:
65
+ fst:
66
+ The FST to be modified. It is changed in-place.
67
+ treat_ilabel_zero_specially:
68
+ If True, then every non-zero input label is increased by one and the
69
+ zero input label is not changed.
70
+ If False, then every input label is increased by one.
71
+ update_olabel:
72
+ If False, the output label is not changed.
73
+ If True, then every non-zero output label is increased by one.
74
+ In either case, output label with 0 is not changed.
75
+ """
76
+ for state in kaldifst.StateIterator(fst):
77
+ for arc in kaldifst.ArcIterator(fst, state):
78
+ # If treat_ilabel_zero_specially is False, we always change it
79
+ # Otherwise, we only change non-zero input labels
80
+ if treat_ilabel_zero_specially is False or arc.ilabel != 0:
81
+ arc.ilabel += 1
82
+
83
+ if update_olabel and arc.olabel != 0:
84
+ arc.olabel += 1
85
+
86
+ if fst.input_symbols is not None:
87
+ input_symbols = kaldifst.SymbolTable()
88
+ input_symbols.add_symbol(symbol="<eps>", key=0)
89
+
90
+ for i in range(0, fst.input_symbols.num_symbols()):
91
+ s = fst.input_symbols.find(i)
92
+ input_symbols.add_symbol(symbol=s, key=i + 1)
93
+
94
+ fst.input_symbols = input_symbols
95
+
96
+ if update_olabel and fst.output_symbols is not None:
97
+ output_symbols = kaldifst.SymbolTable()
98
+ output_symbols.add_symbol(symbol="<eps>", key=0)
99
+
100
+ for i in range(0, fst.output_symbols.num_symbols()):
101
+ s = fst.output_symbols.find(i)
102
+ output_symbols.add_symbol(symbol=s, key=i + 1)
103
+
104
+ fst.output_symbols = output_symbols
105
+
106
+
107
+ def add_disambig_self_loops(fst: kaldifst.StdVectorFst, start: int, end: int):
108
+ """Add self-loops to each state.
109
+
110
+ For each disambig symbol, we add a self-loop with input label disambig_id
111
+ and output label diambig_id of that disambig symbol.
112
+
113
+ Args:
114
+ fst:
115
+ It is changed in-place.
116
+ start:
117
+ The ID of #0
118
+ end:
119
+ The ID of the last disambig symbol. For instance if there are 3
120
+ disambig symbols ``#0``, ``#1``, and ``#2``, then ``end`` is the ID
121
+ of ``#2``.
122
+ """
123
+ for state in kaldifst.StateIterator(fst):
124
+ for i in range(start, end + 1):
125
+ fst.add_arc(
126
+ state=state,
127
+ arc=kaldifst.StdArc(
128
+ ilabel=i,
129
+ olabel=i,
130
+ weight=0,
131
+ nextstate=state,
132
+ ),
133
+ )
134
+
135
+ if fst.output_symbols:
136
+ for i in range(start, end + 1):
137
+ fst.output_symbols.add_symbol(symbol=f"#{i-start}", key=i)
icefall/ctc/utils.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Xiaomi Corp. (authors: Fangjun Kuang)
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List
5
+
6
+ import torch
7
+
8
+
9
+ @dataclass
10
+ class TokenSpan:
11
+ # ID of the token
12
+ token: int
13
+
14
+ # Start frame of this token in the output log_prob
15
+ start: int
16
+
17
+ # End frame of this token in the output log_prob
18
+ end: int
19
+
20
+
21
+ # See also
22
+ # https://github.com/pytorch/audio/blob/main/src/torchaudio/functional/_alignment.py#L96
23
+ # We use torchaudio as a reference while implementing this function
24
+ def merge_tokens(alignment: List[int], blank: int = 0) -> List[TokenSpan]:
25
+ """Compute start and end frames of each token from the given alignment.
26
+
27
+ Args:
28
+ alignment:
29
+ A list of token IDs.
30
+ blank_id:
31
+ ID of the blank.
32
+ Returns:
33
+ Return a list of TokenSpan.
34
+ """
35
+ alignment_tensor = torch.tensor(alignment, dtype=torch.int32)
36
+
37
+ diff = torch.diff(
38
+ alignment_tensor,
39
+ prepend=torch.tensor([-1]),
40
+ append=torch.tensor([-1]),
41
+ )
42
+
43
+ non_zero_indexes = torch.nonzero(diff != 0).squeeze().tolist()
44
+
45
+ ans = []
46
+ for start, end in zip(non_zero_indexes[:-1], non_zero_indexes[1:]):
47
+ token = alignment[start]
48
+ if token == blank:
49
+ continue
50
+ span = TokenSpan(token=token, start=start, end=end)
51
+ ans.append(span)
52
+ return ans
icefall/dataset/__init__.py ADDED
File without changes
icefall/dataset/datamodule.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Piotr Żelasko
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 argparse
19
+ from typing import List, Union
20
+
21
+ from lhotse import CutSet
22
+ from torch.utils.data import DataLoader
23
+
24
+
25
+ class DataModule:
26
+ """
27
+ Contains dataset-related code. It is intended to read/construct Lhotse cuts,
28
+ and create Dataset/Sampler/DataLoader out of them.
29
+
30
+ There is a separate method to create each of train/valid/test DataLoader.
31
+ In principle, there might be multiple DataLoaders for each of
32
+ train/valid/test
33
+ (e.g. when a corpus has multiple test sets).
34
+ The API of this class allows to return lists of CutSets/DataLoaders.
35
+ """
36
+
37
+ def __init__(self, args: argparse.Namespace):
38
+ self.args = args
39
+
40
+ @classmethod
41
+ def add_arguments(cls, parser: argparse.ArgumentParser):
42
+ pass
43
+
44
+ def train_cuts(self) -> Union[CutSet, List[CutSet]]:
45
+ raise NotImplementedError()
46
+
47
+ def valid_cuts(self) -> Union[CutSet, List[CutSet]]:
48
+ raise NotImplementedError()
49
+
50
+ def test_cuts(self) -> Union[CutSet, List[CutSet]]:
51
+ raise NotImplementedError()
52
+
53
+ def train_dataloaders(self) -> Union[DataLoader, List[DataLoader]]:
54
+ raise NotImplementedError()
55
+
56
+ def valid_dataloaders(self) -> Union[DataLoader, List[DataLoader]]:
57
+ raise NotImplementedError()
58
+
59
+ def test_dataloaders(self) -> Union[DataLoader, List[DataLoader]]:
60
+ raise NotImplementedError()
icefall/decode.py ADDED
@@ -0,0 +1,2169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang,
2
+ # Wei Kang)
3
+ #
4
+ # See ../../../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import logging
19
+ from dataclasses import dataclass, field
20
+ from multiprocessing.pool import Pool
21
+ from typing import Dict, List, Optional, Tuple, Union
22
+
23
+ import k2
24
+ import torch
25
+
26
+ from icefall.context_graph import ContextGraph, ContextState
27
+ from icefall.lm_wrapper import LmScorer
28
+ from icefall.ngram_lm import NgramLm, NgramLmStateCost
29
+ from icefall.utils import add_eos, add_sos, get_texts
30
+
31
+ DEFAULT_LM_SCALE = [
32
+ 0.01,
33
+ 0.05,
34
+ 0.08,
35
+ 0.1,
36
+ 0.3,
37
+ 0.5,
38
+ 0.6,
39
+ 0.7,
40
+ 0.9,
41
+ 1.0,
42
+ 1.1,
43
+ 1.2,
44
+ 1.3,
45
+ 1.5,
46
+ 1.7,
47
+ 1.9,
48
+ 2.0,
49
+ 2.1,
50
+ 2.2,
51
+ 2.3,
52
+ 2.5,
53
+ 3.0,
54
+ 4.0,
55
+ 5.0,
56
+ ]
57
+
58
+
59
+ def _intersect_device(
60
+ a_fsas: k2.Fsa,
61
+ b_fsas: k2.Fsa,
62
+ b_to_a_map: torch.Tensor,
63
+ sorted_match_a: bool,
64
+ batch_size: int = 50,
65
+ ) -> k2.Fsa:
66
+ """This is a wrapper of k2.intersect_device and its purpose is to split
67
+ b_fsas into several batches and process each batch separately to avoid
68
+ CUDA OOM error.
69
+
70
+ The arguments and return value of this function are the same as
71
+ :func:`k2.intersect_device`.
72
+ """
73
+ num_fsas = b_fsas.shape[0]
74
+ if num_fsas <= batch_size:
75
+ return k2.intersect_device(
76
+ a_fsas, b_fsas, b_to_a_map=b_to_a_map, sorted_match_a=sorted_match_a
77
+ )
78
+
79
+ num_batches = (num_fsas + batch_size - 1) // batch_size
80
+ splits = []
81
+ for i in range(num_batches):
82
+ start = i * batch_size
83
+ end = min(start + batch_size, num_fsas)
84
+ splits.append((start, end))
85
+
86
+ ans = []
87
+ for start, end in splits:
88
+ indexes = torch.arange(start, end).to(b_to_a_map)
89
+
90
+ fsas = k2.index_fsa(b_fsas, indexes)
91
+ b_to_a = k2.index_select(b_to_a_map, indexes)
92
+ path_lattice = k2.intersect_device(
93
+ a_fsas, fsas, b_to_a_map=b_to_a, sorted_match_a=sorted_match_a
94
+ )
95
+ ans.append(path_lattice)
96
+
97
+ return k2.cat(ans)
98
+
99
+
100
+ def get_lattice(
101
+ nnet_output: torch.Tensor,
102
+ decoding_graph: k2.Fsa,
103
+ supervision_segments: torch.Tensor,
104
+ search_beam: float,
105
+ output_beam: float,
106
+ min_active_states: int,
107
+ max_active_states: int,
108
+ subsampling_factor: int = 1,
109
+ ) -> k2.Fsa:
110
+ """Get the decoding lattice from a decoding graph and neural
111
+ network output.
112
+ Args:
113
+ nnet_output:
114
+ It is the output of a neural model of shape `(N, T, C)`.
115
+ decoding_graph:
116
+ An Fsa, the decoding graph. It can be either an HLG
117
+ (see `compile_HLG.py`) or an H (see `k2.ctc_topo`).
118
+ supervision_segments:
119
+ A 2-D **CPU** tensor of dtype `torch.int32` with 3 columns.
120
+ Each row contains information for a supervision segment. Column 0
121
+ is the `sequence_index` indicating which sequence this segment
122
+ comes from; column 1 specifies the `start_frame` of this segment
123
+ within the sequence; column 2 contains the `duration` of this
124
+ segment.
125
+ search_beam:
126
+ Decoding beam, e.g. 20. Smaller is faster, larger is more exact
127
+ (less pruning). This is the default value; it may be modified by
128
+ `min_active_states` and `max_active_states`.
129
+ output_beam:
130
+ Beam to prune output, similar to lattice-beam in Kaldi. Relative
131
+ to best path of output.
132
+ min_active_states:
133
+ Minimum number of FSA states that are allowed to be active on any given
134
+ frame for any given intersection/composition task. This is advisory,
135
+ in that it will try not to have fewer than this number active.
136
+ Set it to zero if there is no constraint.
137
+ max_active_states:
138
+ Maximum number of FSA states that are allowed to be active on any given
139
+ frame for any given intersection/composition task. This is advisory,
140
+ in that it will try not to exceed that but may not always succeed.
141
+ You can use a very large number if no constraint is needed.
142
+ subsampling_factor:
143
+ The subsampling factor of the model.
144
+ Returns:
145
+ An FsaVec containing the decoding result. It has axes [utt][state][arc].
146
+ """
147
+ dense_fsa_vec = k2.DenseFsaVec(
148
+ nnet_output,
149
+ supervision_segments,
150
+ allow_truncate=subsampling_factor - 1,
151
+ )
152
+
153
+ lattice = k2.intersect_dense_pruned(
154
+ decoding_graph,
155
+ dense_fsa_vec,
156
+ search_beam=search_beam,
157
+ output_beam=output_beam,
158
+ min_active_states=min_active_states,
159
+ max_active_states=max_active_states,
160
+ )
161
+
162
+ return lattice
163
+
164
+
165
+ class Nbest(object):
166
+ """
167
+ An Nbest object contains two fields:
168
+
169
+ (1) fsa. It is an FsaVec containing a vector of **linear** FSAs.
170
+ Its axes are [path][state][arc]
171
+ (2) shape. Its type is :class:`k2.RaggedShape`.
172
+ Its axes are [utt][path]
173
+
174
+ The field `shape` has two axes [utt][path]. `shape.dim0` contains
175
+ the number of utterances, which is also the number of rows in the
176
+ supervision_segments. `shape.tot_size(1)` contains the number
177
+ of paths, which is also the number of FSAs in `fsa`.
178
+
179
+ Caution:
180
+ Don't be confused by the name `Nbest`. The best in the name `Nbest`
181
+ has nothing to do with `best scores`. The important part is
182
+ `N` in `Nbest`, not `best`.
183
+ """
184
+
185
+ def __init__(self, fsa: k2.Fsa, shape: k2.RaggedShape) -> None:
186
+ """
187
+ Args:
188
+ fsa:
189
+ An FsaVec with axes [path][state][arc]. It is expected to contain
190
+ a list of **linear** FSAs.
191
+ shape:
192
+ A ragged shape with two axes [utt][path].
193
+ """
194
+ assert len(fsa.shape) == 3, f"fsa.shape: {fsa.shape}"
195
+ assert shape.num_axes == 2, f"num_axes: {shape.num_axes}"
196
+
197
+ if fsa.shape[0] != shape.tot_size(1):
198
+ raise ValueError(
199
+ f"{fsa.shape[0]} vs {shape.tot_size(1)}\n"
200
+ "Number of FSAs in `fsa` does not match the given shape"
201
+ )
202
+
203
+ self.fsa = fsa
204
+ self.shape = shape
205
+
206
+ def __str__(self):
207
+ s = "Nbest("
208
+ s += f"Number of utterances:{self.shape.dim0}, "
209
+ s += f"Number of Paths:{self.fsa.shape[0]})"
210
+ return s
211
+
212
+ @staticmethod
213
+ def from_lattice(
214
+ lattice: k2.Fsa,
215
+ num_paths: int,
216
+ use_double_scores: bool = True,
217
+ nbest_scale: float = 0.5,
218
+ ) -> "Nbest":
219
+ """Construct an Nbest object by **sampling** `num_paths` from a lattice.
220
+
221
+ Each sampled path is a linear FSA.
222
+
223
+ We assume `lattice.labels` contains token IDs and `lattice.aux_labels`
224
+ contains word IDs.
225
+
226
+ Args:
227
+ lattice:
228
+ An FsaVec with axes [utt][state][arc].
229
+ num_paths:
230
+ Number of paths to **sample** from the lattice
231
+ using :func:`k2.random_paths`.
232
+ use_double_scores:
233
+ True to use double precision in :func:`k2.random_paths`.
234
+ False to use single precision.
235
+ scale:
236
+ Scale `lattice.score` before passing it to :func:`k2.random_paths`.
237
+ A smaller value leads to more unique paths at the risk of being not
238
+ to sample the path with the best score.
239
+ Returns:
240
+ Return an Nbest instance.
241
+ """
242
+ saved_scores = lattice.scores.clone()
243
+ lattice.scores *= nbest_scale
244
+ # path is a ragged tensor with dtype torch.int32.
245
+ # It has three axes [utt][path][arc_pos]
246
+ path = k2.random_paths(
247
+ lattice, num_paths=num_paths, use_double_scores=use_double_scores
248
+ )
249
+ lattice.scores = saved_scores
250
+
251
+ # word_seq is a k2.RaggedTensor sharing the same shape as `path`
252
+ # but it contains word IDs. Note that it also contains 0s and -1s.
253
+ # The last entry in each sublist is -1.
254
+ # It axes is [utt][path][word_id]
255
+ if isinstance(lattice.aux_labels, torch.Tensor):
256
+ word_seq = k2.ragged.index(lattice.aux_labels, path)
257
+ else:
258
+ word_seq = lattice.aux_labels.index(path)
259
+ word_seq = word_seq.remove_axis(word_seq.num_axes - 2)
260
+ word_seq = word_seq.remove_values_leq(0)
261
+
262
+ # Each utterance has `num_paths` paths but some of them transduces
263
+ # to the same word sequence, so we need to remove repeated word
264
+ # sequences within an utterance. After removing repeats, each utterance
265
+ # contains different number of paths
266
+ #
267
+ # `new2old` is a 1-D torch.Tensor mapping from the output path index
268
+ # to the input path index.
269
+ _, _, new2old = word_seq.unique(
270
+ need_num_repeats=False, need_new2old_indexes=True
271
+ )
272
+
273
+ # kept_path is a ragged tensor with dtype torch.int32.
274
+ # It has axes [utt][path][arc_pos]
275
+ kept_path, _ = path.index(new2old, axis=1, need_value_indexes=False)
276
+
277
+ # utt_to_path_shape has axes [utt][path]
278
+ utt_to_path_shape = kept_path.shape.get_layer(0)
279
+
280
+ # Remove the utterance axis.
281
+ # Now kept_path has only two axes [path][arc_pos]
282
+ kept_path = kept_path.remove_axis(0)
283
+
284
+ # labels is a ragged tensor with 2 axes [path][token_id]
285
+ # Note that it contains -1s.
286
+ labels = k2.ragged.index(lattice.labels.contiguous(), kept_path)
287
+
288
+ # Remove -1 from labels as we will use it to construct a linear FSA
289
+ labels = labels.remove_values_eq(-1)
290
+
291
+ if isinstance(lattice.aux_labels, k2.RaggedTensor):
292
+ # lattice.aux_labels is a ragged tensor with dtype torch.int32.
293
+ # It has 2 axes [arc][word], so aux_labels is also a ragged tensor
294
+ # with 2 axes [arc][word]
295
+ aux_labels, _ = lattice.aux_labels.index(
296
+ indexes=kept_path.values, axis=0, need_value_indexes=False
297
+ )
298
+ else:
299
+ assert isinstance(lattice.aux_labels, torch.Tensor)
300
+ aux_labels = k2.index_select(lattice.aux_labels, kept_path.values)
301
+ # aux_labels is a 1-D torch.Tensor. It also contains -1 and 0.
302
+
303
+ fsa = k2.linear_fsa(labels)
304
+ fsa.aux_labels = aux_labels
305
+ # Caution: fsa.scores are all 0s.
306
+ # `fsa` has only one extra attribute: aux_labels.
307
+ return Nbest(fsa=fsa, shape=utt_to_path_shape)
308
+
309
+ def intersect(self, lattice: k2.Fsa, use_double_scores=True) -> "Nbest":
310
+ """Intersect this Nbest object with a lattice, get 1-best
311
+ path from the resulting FsaVec, and return a new Nbest object.
312
+
313
+ The purpose of this function is to attach scores to an Nbest.
314
+
315
+ Args:
316
+ lattice:
317
+ An FsaVec with axes [utt][state][arc]. If it has `aux_labels`, then
318
+ we assume its `labels` are token IDs and `aux_labels` are word IDs.
319
+ If it has only `labels`, we assume its `labels` are word IDs.
320
+ use_double_scores:
321
+ True to use double precision when computing shortest path.
322
+ False to use single precision.
323
+ Returns:
324
+ Return a new Nbest. This new Nbest shares the same shape with `self`,
325
+ while its `fsa` is the 1-best path from intersecting `self.fsa` and
326
+ `lattice`. Also, its `fsa` has non-zero scores and inherits attributes
327
+ for `lattice`.
328
+ """
329
+ # Note: We view each linear FSA as a word sequence
330
+ # and we use the passed lattice to give each word sequence a score.
331
+ #
332
+ # We are not viewing each linear FSAs as a token sequence.
333
+ #
334
+ # So we use k2.invert() here.
335
+
336
+ # We use a word fsa to intersect with k2.invert(lattice)
337
+ word_fsa = k2.invert(self.fsa)
338
+
339
+ word_fsa.scores.zero_()
340
+ if hasattr(lattice, "aux_labels"):
341
+ # delete token IDs as it is not needed
342
+ del word_fsa.aux_labels
343
+ word_fsa_with_epsilon_loops = k2.linear_fsa_with_self_loops(word_fsa)
344
+ else:
345
+ word_fsa_with_epsilon_loops = k2.linear_fst_with_self_loops(word_fsa)
346
+
347
+ path_to_utt_map = self.shape.row_ids(1)
348
+
349
+ if hasattr(lattice, "aux_labels"):
350
+ # lattice has token IDs as labels and word IDs as aux_labels.
351
+ # inv_lattice has word IDs as labels and token IDs as aux_labels
352
+ inv_lattice = k2.invert(lattice)
353
+ inv_lattice = k2.arc_sort(inv_lattice)
354
+ else:
355
+ inv_lattice = k2.arc_sort(lattice)
356
+
357
+ if inv_lattice.shape[0] == 1:
358
+ path_lattice = _intersect_device(
359
+ inv_lattice,
360
+ word_fsa_with_epsilon_loops,
361
+ b_to_a_map=torch.zeros_like(path_to_utt_map),
362
+ sorted_match_a=True,
363
+ )
364
+ else:
365
+ path_lattice = _intersect_device(
366
+ inv_lattice,
367
+ word_fsa_with_epsilon_loops,
368
+ b_to_a_map=path_to_utt_map,
369
+ sorted_match_a=True,
370
+ )
371
+
372
+ # path_lattice has word IDs as labels and token IDs as aux_labels
373
+ path_lattice = k2.top_sort(k2.connect(path_lattice))
374
+
375
+ one_best = k2.shortest_path(path_lattice, use_double_scores=use_double_scores)
376
+
377
+ one_best = k2.invert(one_best)
378
+ # Now one_best has token IDs as labels and word IDs as aux_labels
379
+
380
+ return Nbest(fsa=one_best, shape=self.shape)
381
+
382
+ def compute_am_scores(self) -> k2.RaggedTensor:
383
+ """Compute AM scores of each linear FSA (i.e., each path within
384
+ an utterance).
385
+
386
+ Hint:
387
+ `self.fsa.scores` contains two parts: acoustic scores (AM scores)
388
+ and n-gram language model scores (LM scores).
389
+
390
+ Caution:
391
+ We require that ``self.fsa`` has an attribute ``lm_scores``.
392
+
393
+ Returns:
394
+ Return a ragged tensor with 2 axes [utt][path_scores].
395
+ Its dtype is torch.float64.
396
+ """
397
+ scores_shape = self.fsa.arcs.shape().remove_axis(1)
398
+ # scores_shape has axes [path][arc]
399
+ am_scores = self.fsa.scores - self.fsa.lm_scores
400
+ ragged_am_scores = k2.RaggedTensor(scores_shape, am_scores.contiguous())
401
+ tot_scores = ragged_am_scores.sum()
402
+
403
+ return k2.RaggedTensor(self.shape, tot_scores)
404
+
405
+ def compute_lm_scores(self) -> k2.RaggedTensor:
406
+ """Compute LM scores of each linear FSA (i.e., each path within
407
+ an utterance).
408
+
409
+ Hint:
410
+ `self.fsa.scores` contains two parts: acoustic scores (AM scores)
411
+ and n-gram language model scores (LM scores).
412
+
413
+ Caution:
414
+ We require that ``self.fsa`` has an attribute ``lm_scores``.
415
+
416
+ Returns:
417
+ Return a ragged tensor with 2 axes [utt][path_scores].
418
+ Its dtype is torch.float64.
419
+ """
420
+ scores_shape = self.fsa.arcs.shape().remove_axis(1)
421
+ # scores_shape has axes [path][arc]
422
+
423
+ ragged_lm_scores = k2.RaggedTensor(
424
+ scores_shape, self.fsa.lm_scores.contiguous()
425
+ )
426
+
427
+ tot_scores = ragged_lm_scores.sum()
428
+
429
+ return k2.RaggedTensor(self.shape, tot_scores)
430
+
431
+ def tot_scores(self) -> k2.RaggedTensor:
432
+ """Get total scores of FSAs in this Nbest.
433
+
434
+ Note:
435
+ Since FSAs in Nbest are just linear FSAs, log-semiring
436
+ and tropical semiring produce the same total scores.
437
+
438
+ Returns:
439
+ Return a ragged tensor with two axes [utt][path_scores].
440
+ Its dtype is torch.float64.
441
+ """
442
+ scores_shape = self.fsa.arcs.shape().remove_axis(1)
443
+ # scores_shape has axes [path][arc]
444
+
445
+ ragged_scores = k2.RaggedTensor(scores_shape, self.fsa.scores.contiguous())
446
+
447
+ tot_scores = ragged_scores.sum()
448
+
449
+ return k2.RaggedTensor(self.shape, tot_scores)
450
+
451
+ def build_levenshtein_graphs(self) -> k2.Fsa:
452
+ """Return an FsaVec with axes [utt][state][arc]."""
453
+ word_ids = get_texts(self.fsa, return_ragged=True)
454
+ return k2.levenshtein_graph(word_ids)
455
+
456
+
457
+ def one_best_decoding(
458
+ lattice: k2.Fsa,
459
+ use_double_scores: bool = True,
460
+ lm_scale_list: Optional[List[float]] = None,
461
+ ) -> Union[k2.Fsa, Dict[str, k2.Fsa]]:
462
+ """Get the best path from a lattice.
463
+
464
+ Args:
465
+ lattice:
466
+ The decoding lattice returned by :func:`get_lattice`.
467
+ use_double_scores:
468
+ True to use double precision floating point in the computation.
469
+ False to use single precision.
470
+ lm_scale_list:
471
+ A list of floats representing LM score scales.
472
+ Return:
473
+ An FsaVec containing linear paths.
474
+ """
475
+ if lm_scale_list is not None:
476
+ ans = dict()
477
+ saved_am_scores = lattice.scores - lattice.lm_scores
478
+ for lm_scale in lm_scale_list:
479
+ am_scores = saved_am_scores / lm_scale
480
+ lattice.scores = am_scores + lattice.lm_scores
481
+
482
+ best_path = k2.shortest_path(lattice, use_double_scores=use_double_scores)
483
+ key = f"lm_scale_{lm_scale}"
484
+ ans[key] = best_path
485
+ return ans
486
+
487
+ return k2.shortest_path(lattice, use_double_scores=use_double_scores)
488
+
489
+
490
+ def nbest_decoding(
491
+ lattice: k2.Fsa,
492
+ num_paths: int,
493
+ use_double_scores: bool = True,
494
+ nbest_scale: float = 1.0,
495
+ ) -> k2.Fsa:
496
+ """It implements something like CTC prefix beam search using n-best lists.
497
+
498
+ The basic idea is to first extract `num_paths` paths from the given lattice,
499
+ build a word sequence from these paths, and compute the total scores
500
+ of the word sequence in the tropical semiring. The one with the max score
501
+ is used as the decoding output.
502
+
503
+ Caution:
504
+ Don't be confused by `best` in the name `n-best`. Paths are selected
505
+ **randomly**, not by ranking their scores.
506
+
507
+ Hint:
508
+ This decoding method is for demonstration only and it does
509
+ not produce a lower WER than :func:`one_best_decoding`.
510
+
511
+ Args:
512
+ lattice:
513
+ The decoding lattice, e.g., can be the return value of
514
+ :func:`get_lattice`. It has 3 axes [utt][state][arc].
515
+ num_paths:
516
+ It specifies the size `n` in n-best. Note: Paths are selected randomly
517
+ and those containing identical word sequences are removed and only one
518
+ of them is kept.
519
+ use_double_scores:
520
+ True to use double precision floating point in the computation.
521
+ False to use single precision.
522
+ nbest_scale:
523
+ It's the scale applied to the `lattice.scores`. A smaller value
524
+ leads to more unique paths at the risk of missing the correct path.
525
+ Returns:
526
+ An FsaVec containing **linear** FSAs. It axes are [utt][state][arc].
527
+ """
528
+ nbest = Nbest.from_lattice(
529
+ lattice=lattice,
530
+ num_paths=num_paths,
531
+ use_double_scores=use_double_scores,
532
+ nbest_scale=nbest_scale,
533
+ )
534
+ # nbest.fsa.scores contains 0s
535
+
536
+ nbest = nbest.intersect(lattice)
537
+ # now nbest.fsa.scores gets assigned
538
+
539
+ # max_indexes contains the indexes for the path with the maximum score
540
+ # within an utterance.
541
+ max_indexes = nbest.tot_scores().argmax()
542
+
543
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
544
+ return best_path
545
+
546
+
547
+ def nbest_oracle(
548
+ lattice: k2.Fsa,
549
+ num_paths: int,
550
+ ref_texts: List[str],
551
+ word_table: k2.SymbolTable,
552
+ use_double_scores: bool = True,
553
+ nbest_scale: float = 0.5,
554
+ oov: str = "<UNK>",
555
+ ) -> Dict[str, List[List[int]]]:
556
+ """Select the best hypothesis given a lattice and a reference transcript.
557
+
558
+ The basic idea is to extract `num_paths` paths from the given lattice,
559
+ unique them, and select the one that has the minimum edit distance with
560
+ the corresponding reference transcript as the decoding output.
561
+
562
+ The decoding result returned from this function is the best result that
563
+ we can obtain using n-best decoding with all kinds of rescoring techniques.
564
+
565
+ This function is useful to tune the value of `nbest_scale`.
566
+
567
+ Args:
568
+ lattice:
569
+ An FsaVec with axes [utt][state][arc].
570
+ Note: We assume its `aux_labels` contains word IDs.
571
+ num_paths:
572
+ The size of `n` in n-best.
573
+ ref_texts:
574
+ A list of reference transcript. Each entry contains space(s)
575
+ separated words
576
+ word_table:
577
+ It is the word symbol table.
578
+ use_double_scores:
579
+ True to use double precision for computation. False to use
580
+ single precision.
581
+ nbest_scale:
582
+ It's the scale applied to the lattice.scores. A smaller value
583
+ yields more unique paths.
584
+ oov:
585
+ The out of vocabulary word.
586
+ Return:
587
+ Return a dict. Its key contains the information about the parameters
588
+ when calling this function, while its value contains the decoding output.
589
+ `len(ans_dict) == len(ref_texts)`
590
+ """
591
+ device = lattice.device
592
+
593
+ nbest = Nbest.from_lattice(
594
+ lattice=lattice,
595
+ num_paths=num_paths,
596
+ use_double_scores=use_double_scores,
597
+ nbest_scale=nbest_scale,
598
+ )
599
+
600
+ hyps = nbest.build_levenshtein_graphs()
601
+
602
+ oov_id = word_table[oov]
603
+ word_ids_list = []
604
+ for text in ref_texts:
605
+ word_ids = []
606
+ for word in text.split():
607
+ if word in word_table:
608
+ word_ids.append(word_table[word])
609
+ else:
610
+ word_ids.append(oov_id)
611
+ word_ids_list.append(word_ids)
612
+
613
+ refs = k2.levenshtein_graph(word_ids_list, device=device)
614
+
615
+ levenshtein_alignment = k2.levenshtein_alignment(
616
+ refs=refs,
617
+ hyps=hyps,
618
+ hyp_to_ref_map=nbest.shape.row_ids(1),
619
+ sorted_match_ref=True,
620
+ )
621
+
622
+ tot_scores = levenshtein_alignment.get_tot_scores(
623
+ use_double_scores=False, log_semiring=False
624
+ )
625
+ ragged_tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
626
+
627
+ max_indexes = ragged_tot_scores.argmax()
628
+
629
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
630
+ return best_path
631
+
632
+
633
+ def rescore_with_n_best_list(
634
+ lattice: k2.Fsa,
635
+ G: k2.Fsa,
636
+ num_paths: int,
637
+ lm_scale_list: List[float],
638
+ nbest_scale: float = 1.0,
639
+ use_double_scores: bool = True,
640
+ ) -> Dict[str, k2.Fsa]:
641
+ """Rescore an n-best list with an n-gram LM.
642
+ The path with the maximum score is used as the decoding output.
643
+
644
+ Args:
645
+ lattice:
646
+ An FsaVec with axes [utt][state][arc]. It must have the following
647
+ attributes: ``aux_labels`` and ``lm_scores``. Its labels are
648
+ token IDs and ``aux_labels`` word IDs.
649
+ G:
650
+ An FsaVec containing only a single FSA. It is an n-gram LM.
651
+ num_paths:
652
+ Size of nbest list.
653
+ lm_scale_list:
654
+ A list of floats representing LM score scales.
655
+ nbest_scale:
656
+ Scale to be applied to ``lattice.score`` when sampling paths
657
+ using ``k2.random_paths``.
658
+ use_double_scores:
659
+ True to use double precision during computation. False to use
660
+ single precision.
661
+ Returns:
662
+ A dict of FsaVec, whose key is an lm_scale and the value is the
663
+ best decoding path for each utterance in the lattice.
664
+ """
665
+ device = lattice.device
666
+
667
+ assert len(lattice.shape) == 3
668
+ assert hasattr(lattice, "aux_labels")
669
+ assert hasattr(lattice, "lm_scores")
670
+
671
+ assert G.shape == (1, None, None)
672
+ assert G.device == device
673
+ assert hasattr(G, "aux_labels") is False
674
+
675
+ max_loop_count = 10
676
+ loop_count = 0
677
+ while loop_count <= max_loop_count:
678
+ try:
679
+ nbest = Nbest.from_lattice(
680
+ lattice=lattice,
681
+ num_paths=num_paths,
682
+ use_double_scores=use_double_scores,
683
+ nbest_scale=nbest_scale,
684
+ )
685
+ # nbest.fsa.scores are all 0s at this point
686
+ nbest = nbest.intersect(lattice)
687
+ break
688
+ except RuntimeError as e:
689
+ logging.info(f"Caught exception:\n{e}\n")
690
+ logging.info(f"num_paths before decreasing: {num_paths}")
691
+ num_paths = int(num_paths / 2)
692
+ if loop_count >= max_loop_count or num_paths <= 0:
693
+ logging.info("Return None as the resulting lattice is too large.")
694
+ return None
695
+ logging.info(
696
+ "This OOM is not an error. You can ignore it. "
697
+ "If your model does not converge well, or --max-duration "
698
+ "is too large, or the input sound file is difficult to "
699
+ "decode, you will meet this exception."
700
+ )
701
+ logging.info(f"num_paths after decreasing: {num_paths}")
702
+ loop_count += 1
703
+
704
+ # Now nbest.fsa has its scores set
705
+ assert hasattr(nbest.fsa, "lm_scores")
706
+
707
+ am_scores = nbest.compute_am_scores()
708
+
709
+ nbest = nbest.intersect(G)
710
+ # Now nbest contains only lm scores
711
+ lm_scores = nbest.tot_scores()
712
+
713
+ ans = dict()
714
+ for lm_scale in lm_scale_list:
715
+ tot_scores = am_scores.values / lm_scale + lm_scores.values
716
+ tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
717
+ max_indexes = tot_scores.argmax()
718
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
719
+ key = f"lm_scale_{lm_scale}"
720
+ ans[key] = best_path
721
+ return ans
722
+
723
+
724
+ def nbest_rescore_with_LM(
725
+ lattice: k2.Fsa,
726
+ LM: k2.Fsa,
727
+ num_paths: int,
728
+ lm_scale_list: List[float],
729
+ nbest_scale: float = 1.0,
730
+ use_double_scores: bool = True,
731
+ ) -> Dict[str, k2.Fsa]:
732
+ """Rescore an n-best list with an n-gram LM.
733
+ The path with the maximum score is used as the decoding output.
734
+
735
+ Args:
736
+ lattice:
737
+ An FsaVec with axes [utt][state][arc]. It must have the following
738
+ attributes: ``aux_labels`` and ``lm_scores``. They are both token
739
+ IDs.
740
+ LM:
741
+ An FsaVec containing only a single FSA. It is one of follows:
742
+ - LG, L is lexicon and G is word-level n-gram LM.
743
+ - G, token-level n-gram LM.
744
+ num_paths:
745
+ Size of nbest list.
746
+ lm_scale_list:
747
+ A list of floats representing LM score scales.
748
+ nbest_scale:
749
+ Scale to be applied to ``lattice.score`` when sampling paths
750
+ using ``k2.random_paths``.
751
+ use_double_scores:
752
+ True to use double precision during computation. False to use
753
+ single precision.
754
+ Returns:
755
+ A dict of FsaVec, whose key is an lm_scale and the value is the
756
+ best decoding path for each utterance in the lattice.
757
+ """
758
+ device = lattice.device
759
+
760
+ assert len(lattice.shape) == 3
761
+ assert hasattr(lattice, "aux_labels")
762
+ assert hasattr(lattice, "lm_scores")
763
+
764
+ assert LM.shape == (1, None, None)
765
+ assert LM.device == device
766
+
767
+ nbest = Nbest.from_lattice(
768
+ lattice=lattice,
769
+ num_paths=num_paths,
770
+ use_double_scores=use_double_scores,
771
+ nbest_scale=nbest_scale,
772
+ )
773
+ # nbest.fsa.scores contains 0s
774
+
775
+ nbest = nbest.intersect(lattice)
776
+
777
+ # Now nbest.fsa has its scores set
778
+ assert hasattr(nbest.fsa, "lm_scores")
779
+
780
+ # am scores + bi-gram scores
781
+ hp_scores = nbest.tot_scores()
782
+
783
+ # Now start to intersect nbest with LG or G
784
+ inv_fsa = k2.invert(nbest.fsa)
785
+ if hasattr(LM, "aux_labels"):
786
+ # LM is LG here
787
+ # delete token IDs as it is not needed
788
+ del inv_fsa.aux_labels
789
+ inv_fsa.scores.zero_()
790
+ inv_fsa_with_epsilon_loops = k2.linear_fsa_with_self_loops(inv_fsa)
791
+ path_to_utt_map = nbest.shape.row_ids(1)
792
+
793
+ LM = k2.arc_sort(LM)
794
+ path_lattice = k2.intersect_device(
795
+ LM,
796
+ inv_fsa_with_epsilon_loops,
797
+ b_to_a_map=torch.zeros_like(path_to_utt_map),
798
+ sorted_match_a=True,
799
+ )
800
+
801
+ # Its labels are token IDs.
802
+ # If LM is G, its aux_labels are tokens IDs;
803
+ # If LM is LG, its aux_labels are words IDs.
804
+ path_lattice = k2.top_sort(k2.connect(path_lattice))
805
+ one_best = k2.shortest_path(path_lattice, use_double_scores=use_double_scores)
806
+
807
+ lm_scores = one_best.get_tot_scores(
808
+ use_double_scores=use_double_scores,
809
+ log_semiring=True, # Note: we always use True
810
+ )
811
+ # If LM is LG, we might get empty paths
812
+ lm_scores[lm_scores == float("-inf")] = -1e9
813
+
814
+ ans = dict()
815
+ for lm_scale in lm_scale_list:
816
+ tot_scores = hp_scores.values / lm_scale + lm_scores
817
+ tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
818
+ max_indexes = tot_scores.argmax()
819
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
820
+ key = f"lm_scale_{lm_scale}"
821
+ ans[key] = best_path
822
+ return ans
823
+
824
+
825
+ def rescore_with_whole_lattice(
826
+ lattice: k2.Fsa,
827
+ G_with_epsilon_loops: k2.Fsa,
828
+ lm_scale_list: Optional[List[float]] = None,
829
+ use_double_scores: bool = True,
830
+ ) -> Union[k2.Fsa, Dict[str, k2.Fsa]]:
831
+ """Intersect the lattice with an n-gram LM and use shortest path
832
+ to decode.
833
+
834
+ The input lattice is obtained by intersecting `HLG` with
835
+ a DenseFsaVec, where the `G` in `HLG` is in general a 3-gram LM.
836
+ The input `G_with_epsilon_loops` is usually a 4-gram LM. You can consider
837
+ this function as a second pass decoding. In the first pass decoding, we
838
+ use a small G, while we use a larger G in the second pass decoding.
839
+
840
+ Args:
841
+ lattice:
842
+ An FsaVec with axes [utt][state][arc]. Its `aux_lables` are word IDs.
843
+ It must have an attribute `lm_scores`.
844
+ G_with_epsilon_loops:
845
+ An FsaVec containing only a single FSA. It contains epsilon self-loops.
846
+ It is an acceptor and its labels are word IDs.
847
+ lm_scale_list:
848
+ Optional. If none, return the intersection of `lattice` and
849
+ `G_with_epsilon_loops`.
850
+ If not None, it contains a list of values to scale LM scores.
851
+ For each scale, there is a corresponding decoding result contained in
852
+ the resulting dict.
853
+ use_double_scores:
854
+ True to use double precision in the computation.
855
+ False to use single precision.
856
+ Returns:
857
+ If `lm_scale_list` is None, return a new lattice which is the intersection
858
+ result of `lattice` and `G_with_epsilon_loops`.
859
+ Otherwise, return a dict whose key is an entry in `lm_scale_list` and the
860
+ value is the decoding result (i.e., an FsaVec containing linear FSAs).
861
+ """
862
+ # Nbest is not used in this function
863
+ assert hasattr(lattice, "lm_scores")
864
+ assert G_with_epsilon_loops.shape == (1, None, None)
865
+
866
+ device = lattice.device
867
+ lattice.scores = lattice.scores - lattice.lm_scores
868
+ # We will use lm_scores from G, so remove lats.lm_scores here
869
+ del lattice.lm_scores
870
+
871
+ assert hasattr(G_with_epsilon_loops, "lm_scores")
872
+
873
+ # Now, lattice.scores contains only am_scores
874
+
875
+ # inv_lattice has word IDs as labels.
876
+ # Its `aux_labels` is token IDs
877
+ inv_lattice = k2.invert(lattice)
878
+ num_seqs = lattice.shape[0]
879
+
880
+ b_to_a_map = torch.zeros(num_seqs, device=device, dtype=torch.int32)
881
+
882
+ # NOTE: The choice of the threshold list is arbitrary here to avoid OOM.
883
+ # You may need to fine tune it.
884
+ prune_th_list = [1e-10, 1e-9, 1e-8, 1e-7, 1e-6]
885
+ prune_th_list += [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]
886
+ max_loop_count = 10
887
+ loop_count = 0
888
+ while loop_count <= max_loop_count:
889
+ try:
890
+ rescoring_lattice = k2.intersect_device(
891
+ G_with_epsilon_loops,
892
+ inv_lattice,
893
+ b_to_a_map,
894
+ sorted_match_a=True,
895
+ )
896
+ rescoring_lattice = k2.top_sort(k2.connect(rescoring_lattice))
897
+ break
898
+ except RuntimeError as e:
899
+ logging.info(f"Caught exception:\n{e}\n")
900
+ if loop_count >= max_loop_count:
901
+ logging.info("Return None as the resulting lattice is too large.")
902
+ return None
903
+ logging.info(f"num_arcs before pruning: {inv_lattice.arcs.num_elements()}")
904
+ logging.info(
905
+ "This OOM is not an error. You can ignore it. "
906
+ "If your model does not converge well, or --max-duration "
907
+ "is too large, or the input sound file is difficult to "
908
+ "decode, you will meet this exception."
909
+ )
910
+ inv_lattice = k2.prune_on_arc_post(
911
+ inv_lattice,
912
+ prune_th_list[loop_count],
913
+ True,
914
+ )
915
+ logging.info(f"num_arcs after pruning: {inv_lattice.arcs.num_elements()}")
916
+ loop_count += 1
917
+
918
+ # lat has token IDs as labels
919
+ # and word IDs as aux_labels.
920
+ lat = k2.invert(rescoring_lattice)
921
+
922
+ if lm_scale_list is None:
923
+ return lat
924
+
925
+ ans = dict()
926
+ saved_am_scores = lat.scores - lat.lm_scores
927
+ for lm_scale in lm_scale_list:
928
+ am_scores = saved_am_scores / lm_scale
929
+ lat.scores = am_scores + lat.lm_scores
930
+
931
+ best_path = k2.shortest_path(lat, use_double_scores=use_double_scores)
932
+ key = f"lm_scale_{lm_scale}"
933
+ ans[key] = best_path
934
+ return ans
935
+
936
+
937
+ def rescore_with_attention_decoder(
938
+ lattice: k2.Fsa,
939
+ num_paths: int,
940
+ model: torch.nn.Module,
941
+ memory: torch.Tensor,
942
+ memory_key_padding_mask: Optional[torch.Tensor],
943
+ sos_id: int,
944
+ eos_id: int,
945
+ nbest_scale: float = 1.0,
946
+ ngram_lm_scale: Optional[float] = None,
947
+ attention_scale: Optional[float] = None,
948
+ use_double_scores: bool = True,
949
+ ) -> Dict[str, k2.Fsa]:
950
+ """This function extracts `num_paths` paths from the given lattice and uses
951
+ an attention decoder to rescore them. The path with the highest score is
952
+ the decoding output.
953
+
954
+ Args:
955
+ lattice:
956
+ An FsaVec with axes [utt][state][arc].
957
+ num_paths:
958
+ Number of paths to extract from the given lattice for rescoring.
959
+ model:
960
+ A transformer model. See the class "Transformer" in
961
+ conformer_ctc/transformer.py for its interface.
962
+ memory:
963
+ The encoder memory of the given model. It is the output of
964
+ the last torch.nn.TransformerEncoder layer in the given model.
965
+ Its shape is `(T, N, C)`.
966
+ memory_key_padding_mask:
967
+ The padding mask for memory with shape `(N, T)`.
968
+ sos_id:
969
+ The token ID for SOS.
970
+ eos_id:
971
+ The token ID for EOS.
972
+ nbest_scale:
973
+ It's the scale applied to `lattice.scores`. A smaller value
974
+ leads to more unique paths at the risk of missing the correct path.
975
+ ngram_lm_scale:
976
+ Optional. It specifies the scale for n-gram LM scores.
977
+ attention_scale:
978
+ Optional. It specifies the scale for attention decoder scores.
979
+ Returns:
980
+ A dict of FsaVec, whose key contains a string
981
+ ngram_lm_scale_attention_scale and the value is the
982
+ best decoding path for each utterance in the lattice.
983
+ """
984
+ max_loop_count = 10
985
+ loop_count = 0
986
+ while loop_count <= max_loop_count:
987
+ try:
988
+ nbest = Nbest.from_lattice(
989
+ lattice=lattice,
990
+ num_paths=num_paths,
991
+ use_double_scores=use_double_scores,
992
+ nbest_scale=nbest_scale,
993
+ )
994
+ # nbest.fsa.scores are all 0s at this point
995
+ nbest = nbest.intersect(lattice)
996
+ break
997
+ except RuntimeError as e:
998
+ logging.info(f"Caught exception:\n{e}\n")
999
+ logging.info(f"num_paths before decreasing: {num_paths}")
1000
+ num_paths = int(num_paths / 2)
1001
+ if loop_count >= max_loop_count or num_paths <= 0:
1002
+ logging.info("Return None as the resulting lattice is too large.")
1003
+ return None
1004
+ logging.info(
1005
+ "This OOM is not an error. You can ignore it. "
1006
+ "If your model does not converge well, or --max-duration "
1007
+ "is too large, or the input sound file is difficult to "
1008
+ "decode, you will meet this exception."
1009
+ )
1010
+ logging.info(f"num_paths after decreasing: {num_paths}")
1011
+ loop_count += 1
1012
+
1013
+ # Now nbest.fsa has its scores set.
1014
+ # Also, nbest.fsa inherits the attributes from `lattice`.
1015
+ assert hasattr(nbest.fsa, "lm_scores")
1016
+
1017
+ am_scores = nbest.compute_am_scores()
1018
+ ngram_lm_scores = nbest.compute_lm_scores()
1019
+
1020
+ # The `tokens` attribute is set inside `compile_hlg.py`
1021
+ assert hasattr(nbest.fsa, "tokens")
1022
+ assert isinstance(nbest.fsa.tokens, torch.Tensor)
1023
+
1024
+ path_to_utt_map = nbest.shape.row_ids(1).to(torch.long)
1025
+ # the shape of memory is (T, N, C), so we use axis=1 here
1026
+ expanded_memory = memory.index_select(1, path_to_utt_map)
1027
+
1028
+ if memory_key_padding_mask is not None:
1029
+ # The shape of memory_key_padding_mask is (N, T), so we
1030
+ # use axis=0 here.
1031
+ expanded_memory_key_padding_mask = memory_key_padding_mask.index_select(
1032
+ 0, path_to_utt_map
1033
+ )
1034
+ else:
1035
+ expanded_memory_key_padding_mask = None
1036
+
1037
+ # remove axis corresponding to states.
1038
+ tokens_shape = nbest.fsa.arcs.shape().remove_axis(1)
1039
+ tokens = k2.RaggedTensor(tokens_shape, nbest.fsa.tokens)
1040
+ tokens = tokens.remove_values_leq(0)
1041
+ token_ids = tokens.tolist()
1042
+
1043
+ if len(token_ids) == 0:
1044
+ print("Warning: rescore_with_attention_decoder(): empty token-ids")
1045
+ return None
1046
+
1047
+ nll = model.decoder_nll(
1048
+ memory=expanded_memory,
1049
+ memory_key_padding_mask=expanded_memory_key_padding_mask,
1050
+ token_ids=token_ids,
1051
+ sos_id=sos_id,
1052
+ eos_id=eos_id,
1053
+ )
1054
+ assert nll.ndim == 2
1055
+ assert nll.shape[0] == len(token_ids)
1056
+
1057
+ attention_scores = -nll.sum(dim=1)
1058
+
1059
+ if ngram_lm_scale is None:
1060
+ ngram_lm_scale_list = [0.01, 0.05, 0.08]
1061
+ ngram_lm_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
1062
+ ngram_lm_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
1063
+ ngram_lm_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
1064
+ else:
1065
+ ngram_lm_scale_list = [ngram_lm_scale]
1066
+
1067
+ if attention_scale is None:
1068
+ attention_scale_list = [0.01, 0.05, 0.08]
1069
+ attention_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
1070
+ attention_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
1071
+ attention_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
1072
+ else:
1073
+ attention_scale_list = [attention_scale]
1074
+
1075
+ ans = dict()
1076
+ for n_scale in ngram_lm_scale_list:
1077
+ for a_scale in attention_scale_list:
1078
+ tot_scores = (
1079
+ am_scores.values
1080
+ + n_scale * ngram_lm_scores.values
1081
+ + a_scale * attention_scores
1082
+ )
1083
+ ragged_tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
1084
+ max_indexes = ragged_tot_scores.argmax()
1085
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
1086
+
1087
+ key = f"ngram_lm_scale_{n_scale}_attention_scale_{a_scale}"
1088
+ ans[key] = best_path
1089
+ return ans
1090
+
1091
+
1092
+ def rescore_with_attention_decoder_with_ngram(
1093
+ lattice: k2.Fsa,
1094
+ num_paths: int,
1095
+ attention_decoder: torch.nn.Module,
1096
+ encoder_out: torch.Tensor,
1097
+ encoder_out_lens: torch.Tensor,
1098
+ nbest_scale: float = 1.0,
1099
+ ngram_lm_scale: Optional[float] = None,
1100
+ attention_scale: Optional[float] = None,
1101
+ use_double_scores: bool = True,
1102
+ ) -> Dict[str, k2.Fsa]:
1103
+ """This function extracts `num_paths` paths from the given lattice and uses
1104
+ an attention decoder to rescore them. The path with the highest score is
1105
+ the decoding output.
1106
+
1107
+ Args:
1108
+ lattice:
1109
+ An FsaVec with axes [utt][state][arc].
1110
+ num_paths:
1111
+ Number of paths to extract from the given lattice for rescoring.
1112
+ attention_decoder:
1113
+ A transformer model. See the class "Transformer" in
1114
+ conformer_ctc/transformer.py for its interface.
1115
+ encoder_out:
1116
+ The encoder memory of the given model. It is the output of
1117
+ the last torch.nn.TransformerEncoder layer in the given model.
1118
+ Its shape is `(N, T, C)`.
1119
+ encoder_out_lens:
1120
+ Length of encoder outputs, with shape of `(N,)`.
1121
+ nbest_scale:
1122
+ It's the scale applied to `lattice.scores`. A smaller value
1123
+ leads to more unique paths at the risk of missing the correct path.
1124
+ ngram_lm_scale:
1125
+ Optional. It specifies the scale for n-gram LM scores.
1126
+ attention_scale:
1127
+ Optional. It specifies the scale for attention decoder scores.
1128
+ Returns:
1129
+ A dict of FsaVec, whose key contains a string
1130
+ ngram_lm_scale_attention_scale and the value is the
1131
+ best decoding path for each utterance in the lattice.
1132
+ """
1133
+ max_loop_count = 10
1134
+ loop_count = 0
1135
+ while loop_count <= max_loop_count:
1136
+ try:
1137
+ nbest = Nbest.from_lattice(
1138
+ lattice=lattice,
1139
+ num_paths=num_paths,
1140
+ use_double_scores=use_double_scores,
1141
+ nbest_scale=nbest_scale,
1142
+ )
1143
+ # nbest.fsa.scores are all 0s at this point
1144
+ nbest = nbest.intersect(lattice)
1145
+ break
1146
+ except RuntimeError as e:
1147
+ logging.info(f"Caught exception:\n{e}\n")
1148
+ logging.info(f"num_paths before decreasing: {num_paths}")
1149
+ num_paths = int(num_paths / 2)
1150
+ if loop_count >= max_loop_count or num_paths <= 0:
1151
+ logging.info("Return None as the resulting lattice is too large.")
1152
+ return None
1153
+ logging.info(
1154
+ "This OOM is not an error. You can ignore it. "
1155
+ "If your model does not converge well, or --max-duration "
1156
+ "is too large, or the input sound file is difficult to "
1157
+ "decode, you will meet this exception."
1158
+ )
1159
+ logging.info(f"num_paths after decreasing: {num_paths}")
1160
+ loop_count += 1
1161
+
1162
+ # Now nbest.fsa has its scores set.
1163
+ # Also, nbest.fsa inherits the attributes from `lattice`.
1164
+ assert hasattr(nbest.fsa, "lm_scores")
1165
+
1166
+ am_scores = nbest.compute_am_scores()
1167
+ ngram_lm_scores = nbest.compute_lm_scores()
1168
+
1169
+ # The `tokens` attribute is set inside `compile_hlg.py`
1170
+ assert hasattr(nbest.fsa, "tokens")
1171
+ assert isinstance(nbest.fsa.tokens, torch.Tensor)
1172
+
1173
+ path_to_utt_map = nbest.shape.row_ids(1).to(torch.long)
1174
+ # the shape of memory is (T, N, C), so we use axis=1 here
1175
+ expanded_encoder_out = encoder_out.index_select(0, path_to_utt_map)
1176
+ expanded_encoder_out_lens = encoder_out_lens.index_select(0, path_to_utt_map)
1177
+
1178
+ # remove axis corresponding to states.
1179
+ tokens_shape = nbest.fsa.arcs.shape().remove_axis(1)
1180
+ tokens = k2.RaggedTensor(tokens_shape, nbest.fsa.tokens)
1181
+ tokens = tokens.remove_values_leq(0)
1182
+ token_ids = tokens.tolist()
1183
+
1184
+ nll = attention_decoder.nll(
1185
+ encoder_out=expanded_encoder_out,
1186
+ encoder_out_lens=expanded_encoder_out_lens,
1187
+ token_ids=token_ids,
1188
+ )
1189
+ assert nll.ndim == 2
1190
+ assert nll.shape[0] == len(token_ids)
1191
+
1192
+ attention_scores = -nll.sum(dim=1)
1193
+
1194
+ if ngram_lm_scale is None:
1195
+ ngram_lm_scale_list = [0.01, 0.05, 0.08]
1196
+ ngram_lm_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
1197
+ ngram_lm_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
1198
+ ngram_lm_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
1199
+ else:
1200
+ ngram_lm_scale_list = [ngram_lm_scale]
1201
+
1202
+ if attention_scale is None:
1203
+ attention_scale_list = [0.01, 0.05, 0.08]
1204
+ attention_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
1205
+ attention_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
1206
+ attention_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
1207
+ else:
1208
+ attention_scale_list = [attention_scale]
1209
+
1210
+ ans = dict()
1211
+ for n_scale in ngram_lm_scale_list:
1212
+ for a_scale in attention_scale_list:
1213
+ tot_scores = (
1214
+ am_scores.values
1215
+ + n_scale * ngram_lm_scores.values
1216
+ + a_scale * attention_scores
1217
+ )
1218
+ ragged_tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
1219
+ max_indexes = ragged_tot_scores.argmax()
1220
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
1221
+
1222
+ key = f"ngram_lm_scale_{n_scale}_attention_scale_{a_scale}"
1223
+ ans[key] = best_path
1224
+ return ans
1225
+
1226
+
1227
+ def rescore_with_attention_decoder_no_ngram(
1228
+ lattice: k2.Fsa,
1229
+ num_paths: int,
1230
+ attention_decoder: torch.nn.Module,
1231
+ encoder_out: torch.Tensor,
1232
+ encoder_out_lens: torch.Tensor,
1233
+ nbest_scale: float = 1.0,
1234
+ attention_scale: Optional[float] = None,
1235
+ use_double_scores: bool = True,
1236
+ ) -> Dict[str, k2.Fsa]:
1237
+ """This function extracts `num_paths` paths from the given lattice and uses
1238
+ an attention decoder to rescore them. The path with the highest score is
1239
+ the decoding output.
1240
+
1241
+ Args:
1242
+ lattice:
1243
+ An FsaVec with axes [utt][state][arc].
1244
+ num_paths:
1245
+ Number of paths to extract from the given lattice for rescoring.
1246
+ attention_decoder:
1247
+ A transformer model. See the class "Transformer" in
1248
+ conformer_ctc/transformer.py for its interface.
1249
+ encoder_out:
1250
+ The encoder memory of the given model. It is the output of
1251
+ the last torch.nn.TransformerEncoder layer in the given model.
1252
+ Its shape is `(N, T, C)`.
1253
+ encoder_out_lens:
1254
+ Length of encoder outputs, with shape of `(N,)`.
1255
+ nbest_scale:
1256
+ It's the scale applied to `lattice.scores`. A smaller value
1257
+ leads to more unique paths at the risk of missing the correct path.
1258
+ attention_scale:
1259
+ Optional. It specifies the scale for attention decoder scores.
1260
+
1261
+ Returns:
1262
+ A dict of FsaVec, whose key contains a string
1263
+ ngram_lm_scale_attention_scale and the value is the
1264
+ best decoding path for each utterance in the lattice.
1265
+ """
1266
+ # path is a ragged tensor with dtype torch.int32.
1267
+ # It has three axes [utt][path][arc_pos]
1268
+ path = k2.random_paths(lattice, num_paths=num_paths, use_double_scores=True)
1269
+ # Note that labels, aux_labels and scores contains 0s and -1s.
1270
+ # The last entry in each sublist is -1.
1271
+ # The axes are [path][token_id]
1272
+ labels = k2.ragged.index(lattice.labels.contiguous(), path).remove_axis(0)
1273
+ aux_labels = k2.ragged.index(lattice.aux_labels.contiguous(), path).remove_axis(0)
1274
+ scores = k2.ragged.index(lattice.scores.contiguous(), path).remove_axis(0)
1275
+
1276
+ # Remove -1 from labels as we will use it to construct a linear FSA
1277
+ labels = labels.remove_values_eq(-1)
1278
+ fsa = k2.linear_fsa(labels)
1279
+ fsa.aux_labels = aux_labels.values
1280
+
1281
+ # utt_to_path_shape has axes [utt][path]
1282
+ utt_to_path_shape = path.shape.get_layer(0)
1283
+ scores = k2.RaggedTensor(utt_to_path_shape, scores.sum())
1284
+
1285
+ path_to_utt_map = utt_to_path_shape.row_ids(1).to(torch.long)
1286
+ # the shape of memory is (N, T, C), so we use axis=0 here
1287
+ expanded_encoder_out = encoder_out.index_select(0, path_to_utt_map)
1288
+ expanded_encoder_out_lens = encoder_out_lens.index_select(0, path_to_utt_map)
1289
+
1290
+ token_ids = aux_labels.remove_values_leq(0).tolist()
1291
+
1292
+ nll = attention_decoder.nll(
1293
+ encoder_out=expanded_encoder_out,
1294
+ encoder_out_lens=expanded_encoder_out_lens,
1295
+ token_ids=token_ids,
1296
+ )
1297
+ assert nll.ndim == 2
1298
+ assert nll.shape[0] == len(token_ids)
1299
+
1300
+ attention_scores = -nll.sum(dim=1)
1301
+
1302
+ if attention_scale is None:
1303
+ attention_scale_list = [0.01, 0.05, 0.08]
1304
+ attention_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
1305
+ attention_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
1306
+ attention_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
1307
+ attention_scale_list += [5.0, 6.0, 7.0, 8.0, 9.0]
1308
+ else:
1309
+ attention_scale_list = [attention_scale]
1310
+
1311
+ ans = dict()
1312
+
1313
+ for a_scale in attention_scale_list:
1314
+ tot_scores = scores.values + a_scale * attention_scores
1315
+ ragged_tot_scores = k2.RaggedTensor(utt_to_path_shape, tot_scores)
1316
+ max_indexes = ragged_tot_scores.argmax()
1317
+ best_path = k2.index_fsa(fsa, max_indexes)
1318
+
1319
+ key = f"attention_scale_{a_scale}"
1320
+ ans[key] = best_path
1321
+ return ans
1322
+
1323
+
1324
+ def rescore_with_rnn_lm(
1325
+ lattice: k2.Fsa,
1326
+ num_paths: int,
1327
+ rnn_lm_model: torch.nn.Module,
1328
+ model: torch.nn.Module,
1329
+ memory: torch.Tensor,
1330
+ memory_key_padding_mask: Optional[torch.Tensor],
1331
+ sos_id: int,
1332
+ eos_id: int,
1333
+ blank_id: int,
1334
+ nbest_scale: float = 1.0,
1335
+ ngram_lm_scale: Optional[float] = None,
1336
+ attention_scale: Optional[float] = None,
1337
+ rnn_lm_scale: Optional[float] = None,
1338
+ use_double_scores: bool = True,
1339
+ ) -> Dict[str, k2.Fsa]:
1340
+ """This function extracts `num_paths` paths from the given lattice and uses
1341
+ an attention decoder to rescore them. The path with the highest score is
1342
+ the decoding output.
1343
+
1344
+ Args:
1345
+ lattice:
1346
+ An FsaVec with axes [utt][state][arc].
1347
+ num_paths:
1348
+ Number of paths to extract from the given lattice for rescoring.
1349
+ rnn_lm_model:
1350
+ A rnn-lm model used for LM rescoring
1351
+ model:
1352
+ A transformer model. See the class "Transformer" in
1353
+ conformer_ctc/transformer.py for its interface.
1354
+ memory:
1355
+ The encoder memory of the given model. It is the output of
1356
+ the last torch.nn.TransformerEncoder layer in the given model.
1357
+ Its shape is `(T, N, C)`.
1358
+ memory_key_padding_mask:
1359
+ The padding mask for memory with shape `(N, T)`.
1360
+ sos_id:
1361
+ The token ID for SOS.
1362
+ eos_id:
1363
+ The token ID for EOS.
1364
+ nbest_scale:
1365
+ It's the scale applied to `lattice.scores`. A smaller value
1366
+ leads to more unique paths at the risk of missing the correct path.
1367
+ ngram_lm_scale:
1368
+ Optional. It specifies the scale for n-gram LM scores.
1369
+ attention_scale:
1370
+ Optional. It specifies the scale for attention decoder scores.
1371
+ rnn_lm_scale:
1372
+ Optional. It specifies the scale for RNN LM scores.
1373
+ Returns:
1374
+ A dict of FsaVec, whose key contains a string
1375
+ ngram_lm_scale_attention_scale and the value is the
1376
+ best decoding path for each utterance in the lattice.
1377
+ """
1378
+ nbest = Nbest.from_lattice(
1379
+ lattice=lattice,
1380
+ num_paths=num_paths,
1381
+ use_double_scores=use_double_scores,
1382
+ nbest_scale=nbest_scale,
1383
+ )
1384
+ # nbest.fsa.scores are all 0s at this point
1385
+
1386
+ nbest = nbest.intersect(lattice)
1387
+ # Now nbest.fsa has its scores set.
1388
+ # Also, nbest.fsa inherits the attributes from `lattice`.
1389
+ assert hasattr(nbest.fsa, "lm_scores")
1390
+
1391
+ am_scores = nbest.compute_am_scores()
1392
+ ngram_lm_scores = nbest.compute_lm_scores()
1393
+
1394
+ # The `tokens` attribute is set inside `compile_hlg.py`
1395
+ assert hasattr(nbest.fsa, "tokens")
1396
+ assert isinstance(nbest.fsa.tokens, torch.Tensor)
1397
+
1398
+ path_to_utt_map = nbest.shape.row_ids(1).to(torch.long)
1399
+ # the shape of memory is (T, N, C), so we use axis=1 here
1400
+ expanded_memory = memory.index_select(1, path_to_utt_map)
1401
+
1402
+ if memory_key_padding_mask is not None:
1403
+ # The shape of memory_key_padding_mask is (N, T), so we
1404
+ # use axis=0 here.
1405
+ expanded_memory_key_padding_mask = memory_key_padding_mask.index_select(
1406
+ 0, path_to_utt_map
1407
+ )
1408
+ else:
1409
+ expanded_memory_key_padding_mask = None
1410
+
1411
+ # remove axis corresponding to states.
1412
+ tokens_shape = nbest.fsa.arcs.shape().remove_axis(1)
1413
+ tokens = k2.RaggedTensor(tokens_shape, nbest.fsa.tokens)
1414
+ tokens = tokens.remove_values_leq(0)
1415
+ token_ids = tokens.tolist()
1416
+
1417
+ if len(token_ids) == 0:
1418
+ print("Warning: rescore_with_attention_decoder(): empty token-ids")
1419
+ return None
1420
+
1421
+ nll = model.decoder_nll(
1422
+ memory=expanded_memory,
1423
+ memory_key_padding_mask=expanded_memory_key_padding_mask,
1424
+ token_ids=token_ids,
1425
+ sos_id=sos_id,
1426
+ eos_id=eos_id,
1427
+ )
1428
+ assert nll.ndim == 2
1429
+ assert nll.shape[0] == len(token_ids)
1430
+
1431
+ attention_scores = -nll.sum(dim=1)
1432
+
1433
+ # Now for RNN LM
1434
+ sos_tokens = add_sos(tokens, sos_id)
1435
+ tokens_eos = add_eos(tokens, eos_id)
1436
+ sos_tokens_row_splits = sos_tokens.shape.row_splits(1)
1437
+ sentence_lengths = sos_tokens_row_splits[1:] - sos_tokens_row_splits[:-1]
1438
+
1439
+ x_tokens = sos_tokens.pad(mode="constant", padding_value=blank_id)
1440
+ y_tokens = tokens_eos.pad(mode="constant", padding_value=blank_id)
1441
+
1442
+ x_tokens = x_tokens.to(torch.int64)
1443
+ y_tokens = y_tokens.to(torch.int64)
1444
+ sentence_lengths = sentence_lengths.to(torch.int64)
1445
+
1446
+ rnn_lm_nll = rnn_lm_model(x=x_tokens, y=y_tokens, lengths=sentence_lengths)
1447
+ assert rnn_lm_nll.ndim == 2
1448
+ assert rnn_lm_nll.shape[0] == len(token_ids)
1449
+
1450
+ rnn_lm_scores = -1 * rnn_lm_nll.sum(dim=1)
1451
+
1452
+ ngram_lm_scale_list = DEFAULT_LM_SCALE
1453
+ attention_scale_list = DEFAULT_LM_SCALE
1454
+ rnn_lm_scale_list = DEFAULT_LM_SCALE
1455
+
1456
+ if ngram_lm_scale:
1457
+ ngram_lm_scale_list = [ngram_lm_scale]
1458
+
1459
+ if attention_scale:
1460
+ attention_scale_list = [attention_scale]
1461
+
1462
+ if rnn_lm_scale:
1463
+ rnn_lm_scale_list = [rnn_lm_scale]
1464
+
1465
+ ans = dict()
1466
+ for n_scale in ngram_lm_scale_list:
1467
+ for a_scale in attention_scale_list:
1468
+ for r_scale in rnn_lm_scale_list:
1469
+ tot_scores = (
1470
+ am_scores.values
1471
+ + n_scale * ngram_lm_scores.values
1472
+ + a_scale * attention_scores
1473
+ + r_scale * rnn_lm_scores
1474
+ )
1475
+ ragged_tot_scores = k2.RaggedTensor(nbest.shape, tot_scores)
1476
+ max_indexes = ragged_tot_scores.argmax()
1477
+ best_path = k2.index_fsa(nbest.fsa, max_indexes)
1478
+
1479
+ key = f"ngram_lm_scale_{n_scale}_attention_scale_{a_scale}_rnn_lm_scale_{r_scale}" # noqa
1480
+ ans[key] = best_path
1481
+ return ans
1482
+
1483
+
1484
+ def ctc_greedy_search(
1485
+ ctc_output: torch.Tensor,
1486
+ encoder_out_lens: torch.Tensor,
1487
+ blank_id: int = 0,
1488
+ ) -> List[List[int]]:
1489
+ """CTC greedy search.
1490
+
1491
+ Args:
1492
+ ctc_output: (batch, seq_len, vocab_size)
1493
+ encoder_out_lens: (batch,)
1494
+ Returns:
1495
+ List[List[int]]: greedy search result
1496
+ """
1497
+ batch = ctc_output.shape[0]
1498
+ index = ctc_output.argmax(dim=-1) # (batch, seq_len)
1499
+ hyps = [
1500
+ torch.unique_consecutive(index[i, : encoder_out_lens[i]]) for i in range(batch)
1501
+ ]
1502
+
1503
+ hyps = [h[h != blank_id].tolist() for h in hyps]
1504
+
1505
+ return hyps
1506
+
1507
+
1508
+ @dataclass
1509
+ class Hypothesis:
1510
+ # The predicted tokens so far.
1511
+ # Newly predicted tokens are appended to `ys`.
1512
+ ys: List[int] = field(default_factory=list)
1513
+
1514
+ # The log prob of ys that ends with blank token.
1515
+ # It contains only one entry.
1516
+ log_prob_blank: torch.Tensor = torch.zeros(1, dtype=torch.float32)
1517
+
1518
+ # The log prob of ys that ends with non blank token.
1519
+ # It contains only one entry.
1520
+ log_prob_non_blank: torch.Tensor = torch.tensor(
1521
+ [float("-inf")], dtype=torch.float32
1522
+ )
1523
+
1524
+ # timestamp[i] is the frame index after subsampling
1525
+ # on which ys[i] is decoded
1526
+ timestamp: List[int] = field(default_factory=list)
1527
+
1528
+ # The lm score of ys
1529
+ # May contain external LM score (including LODR score) and contextual biasing score
1530
+ # It contains only one entry
1531
+ lm_score: torch.Tensor = torch.zeros(1, dtype=torch.float32)
1532
+
1533
+ # the lm log_probs for next token given the history ys
1534
+ # The number of elements should be equal to vocabulary size.
1535
+ lm_log_probs: Optional[torch.Tensor] = None
1536
+
1537
+ # the RNNLM states (h and c in LSTM)
1538
+ state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
1539
+
1540
+ # LODR (N-gram LM) state
1541
+ LODR_state: Optional[NgramLmStateCost] = None
1542
+
1543
+ # N-gram LM state
1544
+ Ngram_state: Optional[NgramLmStateCost] = None
1545
+
1546
+ # Context graph state
1547
+ context_state: Optional[ContextState] = None
1548
+
1549
+ # This is the total score of current path, acoustic plus external LM score.
1550
+ @property
1551
+ def tot_score(self) -> torch.Tensor:
1552
+ return self.log_prob + self.lm_score
1553
+
1554
+ # This is only the probability from model output (i.e External LM score not included).
1555
+ @property
1556
+ def log_prob(self) -> torch.Tensor:
1557
+ return torch.logaddexp(self.log_prob_non_blank, self.log_prob_blank)
1558
+
1559
+ @property
1560
+ def key(self) -> tuple:
1561
+ """Return a tuple representation of self.ys"""
1562
+ return tuple(self.ys)
1563
+
1564
+ def clone(self) -> "Hypothesis":
1565
+ return Hypothesis(
1566
+ ys=self.ys,
1567
+ log_prob_blank=self.log_prob_blank,
1568
+ log_prob_non_blank=self.log_prob_non_blank,
1569
+ timestamp=self.timestamp,
1570
+ lm_log_probs=self.lm_log_probs,
1571
+ lm_score=self.lm_score,
1572
+ state=self.state,
1573
+ LODR_state=self.LODR_state,
1574
+ Ngram_state=self.Ngram_state,
1575
+ context_state=self.context_state,
1576
+ )
1577
+
1578
+
1579
+ class HypothesisList(object):
1580
+ def __init__(self, data: Optional[Dict[tuple, Hypothesis]] = None) -> None:
1581
+ """
1582
+ Args:
1583
+ data:
1584
+ A dict of Hypotheses. Its key is its `value.key`.
1585
+ """
1586
+ if data is None:
1587
+ self._data = {}
1588
+ else:
1589
+ self._data = data
1590
+
1591
+ @property
1592
+ def data(self) -> Dict[tuple, Hypothesis]:
1593
+ return self._data
1594
+
1595
+ def add(self, hyp: Hypothesis) -> None:
1596
+ """Add a Hypothesis to `self`.
1597
+ If `hyp` already exists in `self`, its probability is updated using
1598
+ `log-sum-exp` with the existed one.
1599
+ Args:
1600
+ hyp:
1601
+ The hypothesis to be added.
1602
+ """
1603
+ key = hyp.key
1604
+ if key in self:
1605
+ old_hyp = self._data[key] # shallow copy
1606
+ torch.logaddexp(
1607
+ old_hyp.log_prob_blank, hyp.log_prob_blank, out=old_hyp.log_prob_blank
1608
+ )
1609
+ torch.logaddexp(
1610
+ old_hyp.log_prob_non_blank,
1611
+ hyp.log_prob_non_blank,
1612
+ out=old_hyp.log_prob_non_blank,
1613
+ )
1614
+ else:
1615
+ self._data[key] = hyp
1616
+
1617
+ def get_most_probable(self, length_norm: bool = False) -> Hypothesis:
1618
+ """Get the most probable hypothesis, i.e., the one with
1619
+ the largest `tot_score`.
1620
+ Args:
1621
+ length_norm:
1622
+ If True, the `tot_score` of a hypothesis is normalized by the
1623
+ number of tokens in it.
1624
+ Returns:
1625
+ Return the hypothesis that has the largest `tot_score`.
1626
+ """
1627
+ if length_norm:
1628
+ return max(self._data.values(), key=lambda hyp: hyp.tot_score / len(hyp.ys))
1629
+ else:
1630
+ return max(self._data.values(), key=lambda hyp: hyp.tot_score)
1631
+
1632
+ def remove(self, hyp: Hypothesis) -> None:
1633
+ """Remove a given hypothesis.
1634
+ Caution:
1635
+ `self` is modified **in-place**.
1636
+ Args:
1637
+ hyp:
1638
+ The hypothesis to be removed from `self`.
1639
+ Note: It must be contained in `self`. Otherwise,
1640
+ an exception is raised.
1641
+ """
1642
+ key = hyp.key
1643
+ assert key in self, f"{key} does not exist"
1644
+ del self._data[key]
1645
+
1646
+ def filter(self, threshold: torch.Tensor) -> "HypothesisList":
1647
+ """Remove all Hypotheses whose tot_score is less than threshold.
1648
+ Caution:
1649
+ `self` is not modified. Instead, a new HypothesisList is returned.
1650
+ Returns:
1651
+ Return a new HypothesisList containing all hypotheses from `self`
1652
+ with `tot_score` being greater than the given `threshold`.
1653
+ """
1654
+ ans = HypothesisList()
1655
+ for _, hyp in self._data.items():
1656
+ if hyp.tot_score > threshold:
1657
+ ans.add(hyp) # shallow copy
1658
+ return ans
1659
+
1660
+ def topk(self, k: int, length_norm: bool = False) -> "HypothesisList":
1661
+ """Return the top-k hypothesis.
1662
+ Args:
1663
+ length_norm:
1664
+ If True, the `tot_score` of a hypothesis is normalized by the
1665
+ number of tokens in it.
1666
+ """
1667
+ hyps = list(self._data.items())
1668
+
1669
+ if length_norm:
1670
+ hyps = sorted(
1671
+ hyps, key=lambda h: h[1].tot_score / len(h[1].ys), reverse=True
1672
+ )[:k]
1673
+ else:
1674
+ hyps = sorted(hyps, key=lambda h: h[1].tot_score, reverse=True)[:k]
1675
+
1676
+ ans = HypothesisList(dict(hyps))
1677
+ return ans
1678
+
1679
+ def __contains__(self, key: tuple):
1680
+ return key in self._data
1681
+
1682
+ def __getitem__(self, key: tuple):
1683
+ return self._data[key]
1684
+
1685
+ def __iter__(self):
1686
+ return iter(self._data.values())
1687
+
1688
+ def __len__(self) -> int:
1689
+ return len(self._data)
1690
+
1691
+ def __str__(self) -> str:
1692
+ s = []
1693
+ for key in self:
1694
+ s.append(key)
1695
+ return ", ".join(str(s))
1696
+
1697
+
1698
+ def get_hyps_shape(hyps: List[HypothesisList]) -> k2.RaggedShape:
1699
+ """Return a ragged shape with axes [utt][num_hyps].
1700
+ Args:
1701
+ hyps:
1702
+ len(hyps) == batch_size. It contains the current hypothesis for
1703
+ each utterance in the batch.
1704
+ Returns:
1705
+ Return a ragged shape with 2 axes [utt][num_hyps]. Note that
1706
+ the shape is on CPU.
1707
+ """
1708
+ num_hyps = [len(h) for h in hyps]
1709
+
1710
+ # torch.cumsum() is inclusive sum, so we put a 0 at the beginning
1711
+ # to get exclusive sum later.
1712
+ num_hyps.insert(0, 0)
1713
+
1714
+ num_hyps = torch.tensor(num_hyps)
1715
+ row_splits = torch.cumsum(num_hyps, dim=0, dtype=torch.int32)
1716
+ ans = k2.ragged.create_ragged_shape2(
1717
+ row_splits=row_splits, cached_tot_size=row_splits[-1].item()
1718
+ )
1719
+ return ans
1720
+
1721
+
1722
+ def _step_worker(
1723
+ log_probs: torch.Tensor,
1724
+ indexes: torch.Tensor,
1725
+ B: HypothesisList,
1726
+ beam: int = 4,
1727
+ blank_id: int = 0,
1728
+ nnlm_scale: float = 0,
1729
+ LODR_lm_scale: float = 0,
1730
+ context_graph: Optional[ContextGraph] = None,
1731
+ ) -> HypothesisList:
1732
+ """The worker to decode one step.
1733
+ Args:
1734
+ log_probs:
1735
+ topk log_probs of current step (i.e. the kept tokens of first pass pruning),
1736
+ the shape is (beam,)
1737
+ topk_indexes:
1738
+ The indexes of the topk_values above, the shape is (beam,)
1739
+ B:
1740
+ An instance of HypothesisList containing the kept hypothesis.
1741
+ beam:
1742
+ The number of hypothesis to be kept at each step.
1743
+ blank_id:
1744
+ The id of blank in the vocabulary.
1745
+ lm_scale:
1746
+ The scale of nn lm.
1747
+ LODR_lm_scale:
1748
+ The scale of the LODR_lm
1749
+ context_graph:
1750
+ A ContextGraph instance containing contextual phrases.
1751
+ Return:
1752
+ Returns the updated HypothesisList.
1753
+ """
1754
+ A = list(B)
1755
+ B = HypothesisList()
1756
+ for h in range(len(A)):
1757
+ hyp = A[h]
1758
+ for k in range(log_probs.size(0)):
1759
+ log_prob, index = log_probs[k], indexes[k]
1760
+ new_token = index.item()
1761
+ update_prefix = False
1762
+ new_hyp = hyp.clone()
1763
+ if new_token == blank_id:
1764
+ # Case 0: *a + ε => *a
1765
+ # *aε + ε => *a
1766
+ # Prefix does not change, update log_prob of blank
1767
+ new_hyp.log_prob_non_blank = torch.tensor(
1768
+ [float("-inf")], dtype=torch.float32
1769
+ )
1770
+ new_hyp.log_prob_blank = hyp.log_prob + log_prob
1771
+ B.add(new_hyp)
1772
+ elif len(hyp.ys) > 0 and hyp.ys[-1] == new_token:
1773
+ # Case 1: *a + a => *a
1774
+ # Prefix does not change, update log_prob of non_blank
1775
+ new_hyp.log_prob_non_blank = hyp.log_prob_non_blank + log_prob
1776
+ new_hyp.log_prob_blank = torch.tensor(
1777
+ [float("-inf")], dtype=torch.float32
1778
+ )
1779
+ B.add(new_hyp)
1780
+
1781
+ # Case 2: *aε + a => *aa
1782
+ # Prefix changes, update log_prob of blank
1783
+ new_hyp = hyp.clone()
1784
+ # Caution: DO NOT use append, as clone is shallow copy
1785
+ new_hyp.ys = hyp.ys + [new_token]
1786
+ new_hyp.log_prob_non_blank = hyp.log_prob_blank + log_prob
1787
+ new_hyp.log_prob_blank = torch.tensor(
1788
+ [float("-inf")], dtype=torch.float32
1789
+ )
1790
+ update_prefix = True
1791
+ else:
1792
+ # Case 3: *a + b => *ab, *aε + b => *ab
1793
+ # Prefix changes, update log_prob of non_blank
1794
+ # Caution: DO NOT use append, as clone is shallow copy
1795
+ new_hyp.ys = hyp.ys + [new_token]
1796
+ new_hyp.log_prob_non_blank = hyp.log_prob + log_prob
1797
+ new_hyp.log_prob_blank = torch.tensor(
1798
+ [float("-inf")], dtype=torch.float32
1799
+ )
1800
+ update_prefix = True
1801
+
1802
+ if update_prefix:
1803
+ lm_score = hyp.lm_score
1804
+ if hyp.lm_log_probs is not None:
1805
+ lm_score = lm_score + hyp.lm_log_probs[new_token] * nnlm_scale
1806
+ new_hyp.lm_log_probs = None
1807
+
1808
+ if context_graph is not None and hyp.context_state is not None:
1809
+ (
1810
+ context_score,
1811
+ new_context_state,
1812
+ matched_state,
1813
+ ) = context_graph.forward_one_step(hyp.context_state, new_token)
1814
+ lm_score = lm_score + context_score
1815
+ new_hyp.context_state = new_context_state
1816
+
1817
+ if hyp.LODR_state is not None:
1818
+ state_cost = hyp.LODR_state.forward_one_step(new_token)
1819
+ # calculate the score of the latest token
1820
+ current_ngram_score = state_cost.lm_score - hyp.LODR_state.lm_score
1821
+ assert current_ngram_score <= 0.0, (
1822
+ state_cost.lm_score,
1823
+ hyp.LODR_state.lm_score,
1824
+ )
1825
+ lm_score = lm_score + LODR_lm_scale * current_ngram_score
1826
+ new_hyp.LODR_state = state_cost
1827
+
1828
+ new_hyp.lm_score = lm_score
1829
+ B.add(new_hyp)
1830
+ B = B.topk(beam)
1831
+ return B
1832
+
1833
+
1834
+ def _sequence_worker(
1835
+ topk_values: torch.Tensor,
1836
+ topk_indexes: torch.Tensor,
1837
+ B: HypothesisList,
1838
+ encoder_out_lens: torch.Tensor,
1839
+ beam: int = 4,
1840
+ blank_id: int = 0,
1841
+ ) -> HypothesisList:
1842
+ """The worker to decode one sequence.
1843
+ Args:
1844
+ topk_values:
1845
+ topk log_probs of model output (i.e. the kept tokens of first pass pruning),
1846
+ the shape is (T, beam)
1847
+ topk_indexes:
1848
+ The indexes of the topk_values above, the shape is (T, beam)
1849
+ B:
1850
+ An instance of HypothesisList containing the kept hypothesis.
1851
+ encoder_out_lens:
1852
+ The lengths (frames) of sequences after subsampling, the shape is (B,)
1853
+ beam:
1854
+ The number of hypothesis to be kept at each step.
1855
+ blank_id:
1856
+ The id of blank in the vocabulary.
1857
+ Return:
1858
+ Returns the updated HypothesisList.
1859
+ """
1860
+ B.add(Hypothesis())
1861
+ for j in range(encoder_out_lens):
1862
+ log_probs, indexes = topk_values[j], topk_indexes[j]
1863
+ B = _step_worker(log_probs, indexes, B, beam, blank_id)
1864
+ return B
1865
+
1866
+
1867
+ def ctc_prefix_beam_search(
1868
+ ctc_output: torch.Tensor,
1869
+ encoder_out_lens: torch.Tensor,
1870
+ beam: int = 4,
1871
+ blank_id: int = 0,
1872
+ process_pool: Optional[Pool] = None,
1873
+ return_nbest: Optional[bool] = False,
1874
+ ) -> Union[List[List[int]], List[HypothesisList]]:
1875
+ """Implement prefix search decoding in "Connectionist Temporal Classification:
1876
+ Labelling Unsegmented Sequence Data with Recurrent Neural Networks".
1877
+ Args:
1878
+ ctc_output:
1879
+ The output of ctc head (log probability), the shape is (B, T, V)
1880
+ encoder_out_lens:
1881
+ The lengths (frames) of sequences after subsampling, the shape is (B,)
1882
+ beam:
1883
+ The number of hypothesis to be kept at each step.
1884
+ blank_id:
1885
+ The id of blank in the vocabulary.
1886
+ process_pool:
1887
+ The process pool for parallel decoding, if not provided, it will use all
1888
+ you cpu cores by default.
1889
+ return_nbest:
1890
+ If true, return a list of HypothesisList, return a list of list of decoded token ids otherwise.
1891
+ """
1892
+ batch_size, num_frames, vocab_size = ctc_output.shape
1893
+
1894
+ # TODO: using a larger beam for first pass pruning
1895
+ topk_values, topk_indexes = ctc_output.topk(beam) # (B, T, beam)
1896
+ topk_values = topk_values.cpu()
1897
+ topk_indexes = topk_indexes.cpu()
1898
+
1899
+ B = [HypothesisList() for _ in range(batch_size)]
1900
+
1901
+ pool = Pool() if process_pool is None else process_pool
1902
+ arguments = []
1903
+ for i in range(batch_size):
1904
+ arguments.append(
1905
+ (
1906
+ topk_values[i],
1907
+ topk_indexes[i],
1908
+ B[i],
1909
+ encoder_out_lens[i].item(),
1910
+ beam,
1911
+ blank_id,
1912
+ )
1913
+ )
1914
+ async_results = pool.starmap_async(_sequence_worker, arguments)
1915
+ B = list(async_results.get())
1916
+ if process_pool is None:
1917
+ pool.close()
1918
+ pool.join()
1919
+ if return_nbest:
1920
+ return B
1921
+ else:
1922
+ best_hyps = [b.get_most_probable() for b in B]
1923
+ return [hyp.ys for hyp in best_hyps]
1924
+
1925
+
1926
+ def ctc_prefix_beam_search_shallow_fussion(
1927
+ ctc_output: torch.Tensor,
1928
+ encoder_out_lens: torch.Tensor,
1929
+ beam: int = 4,
1930
+ blank_id: int = 0,
1931
+ LODR_lm: Optional[NgramLm] = None,
1932
+ LODR_lm_scale: Optional[float] = 0,
1933
+ NNLM: Optional[LmScorer] = None,
1934
+ context_graph: Optional[ContextGraph] = None,
1935
+ ) -> List[List[int]]:
1936
+ """Implement prefix search decoding in "Connectionist Temporal Classification:
1937
+ Labelling Unsegmented Sequence Data with Recurrent Neural Networks" and add
1938
+ nervous language model shallow fussion, it also supports contextual
1939
+ biasing with a given grammar.
1940
+ Args:
1941
+ ctc_output:
1942
+ The output of ctc head (log probability), the shape is (B, T, V)
1943
+ encoder_out_lens:
1944
+ The lengths (frames) of sequences after subsampling, the shape is (B,)
1945
+ beam:
1946
+ The number of hypothesis to be kept at each step.
1947
+ blank_id:
1948
+ The id of blank in the vocabulary.
1949
+ LODR_lm:
1950
+ A low order n-gram LM, whose score will be subtracted during shallow fusion
1951
+ LODR_lm_scale:
1952
+ The scale of the LODR_lm
1953
+ LM:
1954
+ A neural net LM, e.g an RNNLM or transformer LM
1955
+ context_graph:
1956
+ A ContextGraph instance containing contextual phrases.
1957
+ Return:
1958
+ Returns a list of list of decoded token ids.
1959
+ """
1960
+ batch_size, num_frames, vocab_size = ctc_output.shape
1961
+ # TODO: using a larger beam for first pass pruning
1962
+ topk_values, topk_indexes = ctc_output.topk(beam) # (B, T, beam)
1963
+ topk_values = topk_values.cpu()
1964
+ topk_indexes = topk_indexes.cpu()
1965
+ encoder_out_lens = encoder_out_lens.tolist()
1966
+ device = ctc_output.device
1967
+
1968
+ nnlm_scale = 0
1969
+ init_scores = None
1970
+ init_states = None
1971
+ if NNLM is not None:
1972
+ nnlm_scale = NNLM.lm_scale
1973
+ sos_id = getattr(NNLM, "sos_id", 1)
1974
+ # get initial lm score and lm state by scoring the "sos" token
1975
+ sos_token = torch.tensor([[sos_id]]).to(torch.int64).to(device)
1976
+ lens = torch.tensor([1]).to(device)
1977
+ init_scores, init_states = NNLM.score_token(sos_token, lens)
1978
+ init_scores, init_states = init_scores.cpu(), (
1979
+ init_states[0].cpu(),
1980
+ init_states[1].cpu(),
1981
+ )
1982
+
1983
+ B = [HypothesisList() for _ in range(batch_size)]
1984
+ for i in range(batch_size):
1985
+ B[i].add(
1986
+ Hypothesis(
1987
+ ys=[],
1988
+ log_prob_non_blank=torch.tensor([float("-inf")], dtype=torch.float32),
1989
+ log_prob_blank=torch.zeros(1, dtype=torch.float32),
1990
+ lm_score=torch.zeros(1, dtype=torch.float32),
1991
+ state=init_states,
1992
+ lm_log_probs=None if init_scores is None else init_scores.reshape(-1),
1993
+ LODR_state=None if LODR_lm is None else NgramLmStateCost(LODR_lm),
1994
+ context_state=None if context_graph is None else context_graph.root,
1995
+ )
1996
+ )
1997
+ for j in range(num_frames):
1998
+ for i in range(batch_size):
1999
+ if j < encoder_out_lens[i]:
2000
+ log_probs, indexes = topk_values[i][j], topk_indexes[i][j]
2001
+ B[i] = _step_worker(
2002
+ log_probs=log_probs,
2003
+ indexes=indexes,
2004
+ B=B[i],
2005
+ beam=beam,
2006
+ blank_id=blank_id,
2007
+ nnlm_scale=nnlm_scale,
2008
+ LODR_lm_scale=LODR_lm_scale,
2009
+ context_graph=context_graph,
2010
+ )
2011
+ if NNLM is None:
2012
+ continue
2013
+ # update lm_log_probs
2014
+ token_list = [] # a list of list
2015
+ hs = []
2016
+ cs = []
2017
+ indexes = [] # (batch_idx, key)
2018
+ for batch_idx, hyps in enumerate(B):
2019
+ for hyp in hyps:
2020
+ if hyp.lm_log_probs is None: # those hyps that prefix changes
2021
+ if NNLM.lm_type == "rnn":
2022
+ token_list.append([hyp.ys[-1]])
2023
+ # store the LSTM states
2024
+ hs.append(hyp.state[0])
2025
+ cs.append(hyp.state[1])
2026
+ else:
2027
+ # for transformer LM
2028
+ token_list.append([sos_id] + hyp.ys[:])
2029
+ indexes.append((batch_idx, hyp.key))
2030
+ if len(token_list) != 0:
2031
+ x_lens = torch.tensor([len(tokens) for tokens in token_list]).to(device)
2032
+ if NNLM.lm_type == "rnn":
2033
+ tokens_to_score = (
2034
+ torch.tensor(token_list).to(torch.int64).to(device).reshape(-1, 1)
2035
+ )
2036
+ hs = torch.cat(hs, dim=1).to(device)
2037
+ cs = torch.cat(cs, dim=1).to(device)
2038
+ state = (hs, cs)
2039
+ else:
2040
+ # for transformer LM
2041
+ tokens_list = [torch.tensor(tokens) for tokens in token_list]
2042
+ tokens_to_score = (
2043
+ torch.nn.utils.rnn.pad_sequence(
2044
+ tokens_list, batch_first=True, padding_value=0.0
2045
+ )
2046
+ .to(device)
2047
+ .to(torch.int64)
2048
+ )
2049
+ state = None
2050
+
2051
+ scores, lm_states = NNLM.score_token(tokens_to_score, x_lens, state)
2052
+ scores, lm_states = scores.cpu(), (lm_states[0].cpu(), lm_states[1].cpu())
2053
+ assert scores.size(0) == len(indexes), (scores.size(0), len(indexes))
2054
+ for i in range(scores.size(0)):
2055
+ batch_idx, key = indexes[i]
2056
+ B[batch_idx][key].lm_log_probs = scores[i]
2057
+ if NNLM.lm_type == "rnn":
2058
+ state = (
2059
+ lm_states[0][:, i, :].unsqueeze(1),
2060
+ lm_states[1][:, i, :].unsqueeze(1),
2061
+ )
2062
+ B[batch_idx][key].state = state
2063
+
2064
+ # finalize context_state, if the matched contexts do not reach final state
2065
+ # we need to add the score on the corresponding backoff arc
2066
+ if context_graph is not None:
2067
+ for hyps in B:
2068
+ for hyp in hyps:
2069
+ context_score, new_context_state = context_graph.finalize(
2070
+ hyp.context_state
2071
+ )
2072
+ hyp.lm_score += context_score
2073
+ hyp.context_state = new_context_state
2074
+
2075
+ best_hyps = [b.get_most_probable() for b in B]
2076
+ return [hyp.ys for hyp in best_hyps]
2077
+
2078
+
2079
+ def ctc_prefix_beam_search_attention_decoder_rescoring(
2080
+ ctc_output: torch.Tensor,
2081
+ attention_decoder: torch.nn.Module,
2082
+ encoder_out: torch.Tensor,
2083
+ encoder_out_lens: torch.Tensor,
2084
+ beam: int = 8,
2085
+ blank_id: int = 0,
2086
+ attention_scale: Optional[float] = None,
2087
+ process_pool: Optional[Pool] = None,
2088
+ ):
2089
+ """Implement prefix search decoding in "Connectionist Temporal Classification:
2090
+ Labelling Unsegmented Sequence Data with Recurrent Neural Networks" and add
2091
+ attention decoder rescoring.
2092
+ Args:
2093
+ ctc_output:
2094
+ The output of ctc head (log probability), the shape is (B, T, V)
2095
+ attention_decoder:
2096
+ The attention decoder.
2097
+ encoder_out:
2098
+ The output of encoder, the shape is (B, T, D)
2099
+ encoder_out_lens:
2100
+ The lengths (frames) of sequences after subsampling, the shape is (B,)
2101
+ beam:
2102
+ The number of hypothesis to be kept at each step.
2103
+ blank_id:
2104
+ The id of blank in the vocabulary.
2105
+ attention_scale:
2106
+ The scale of attention decoder score, if not provided it will search in
2107
+ a default list (see the code below).
2108
+ process_pool:
2109
+ The process pool for parallel decoding, if not provided, it will use all
2110
+ you cpu cores by default.
2111
+ """
2112
+ # List[HypothesisList]
2113
+ nbest = ctc_prefix_beam_search(
2114
+ ctc_output=ctc_output,
2115
+ encoder_out_lens=encoder_out_lens,
2116
+ beam=beam,
2117
+ blank_id=blank_id,
2118
+ return_nbest=True,
2119
+ )
2120
+
2121
+ device = ctc_output.device
2122
+
2123
+ hyp_shape = get_hyps_shape(nbest).to(device)
2124
+ hyp_to_utt_map = hyp_shape.row_ids(1).to(torch.long)
2125
+ # the shape of encoder_out is (N, T, C), so we use axis=0 here
2126
+ expanded_encoder_out = encoder_out.index_select(0, hyp_to_utt_map)
2127
+ expanded_encoder_out_lens = encoder_out_lens.index_select(0, hyp_to_utt_map)
2128
+
2129
+ nbest = [list(x) for x in nbest]
2130
+ token_ids = []
2131
+ scores = []
2132
+ for hyps in nbest:
2133
+ for hyp in hyps:
2134
+ token_ids.append(hyp.ys)
2135
+ scores.append(hyp.log_prob.reshape(1))
2136
+ scores = torch.cat(scores).to(device)
2137
+
2138
+ nll = attention_decoder.nll(
2139
+ encoder_out=expanded_encoder_out,
2140
+ encoder_out_lens=expanded_encoder_out_lens,
2141
+ token_ids=token_ids,
2142
+ )
2143
+ assert nll.ndim == 2
2144
+ assert nll.shape[0] == len(token_ids)
2145
+
2146
+ attention_scores = -nll.sum(dim=1)
2147
+
2148
+ if attention_scale is None:
2149
+ attention_scale_list = [0.01, 0.05, 0.08]
2150
+ attention_scale_list += [0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 1.0]
2151
+ attention_scale_list += [1.1, 1.2, 1.3, 1.5, 1.7, 1.9, 2.0]
2152
+ attention_scale_list += [2.1, 2.2, 2.3, 2.5, 3.0, 4.0, 5.0]
2153
+ attention_scale_list += [5.0, 6.0, 7.0, 8.0, 9.0]
2154
+ else:
2155
+ attention_scale_list = [attention_scale]
2156
+
2157
+ ans = dict()
2158
+
2159
+ start_indexes = hyp_shape.row_splits(1)[0:-1]
2160
+ for a_scale in attention_scale_list:
2161
+ tot_scores = scores + a_scale * attention_scores
2162
+ ragged_tot_scores = k2.RaggedTensor(hyp_shape, tot_scores)
2163
+ max_indexes = ragged_tot_scores.argmax()
2164
+ max_indexes = max_indexes - start_indexes
2165
+ max_indexes = max_indexes.cpu()
2166
+ best_path = [nbest[i][max_indexes[i]].ys for i in range(len(max_indexes))]
2167
+ key = f"attention_scale_{a_scale}"
2168
+ ans[key] = best_path
2169
+ return ans
icefall/diagnostics.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022-2024 Xiaomi Corp. (authors: Daniel Povey
2
+ # Zengwei Yao
3
+ # Mingshuang Luo,
4
+ # Zengrui Jin,)
5
+ #
6
+ # See ../LICENSE for clarification regarding multiple authors
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ import logging
21
+ import random
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple
24
+
25
+ import torch
26
+ from torch import Tensor, nn
27
+
28
+
29
+ class TensorDiagnosticOptions(object):
30
+ """Options object for tensor diagnostics:
31
+
32
+ Args:
33
+ max_eig_dim:
34
+ The maximum dimension for which we print out eigenvalues
35
+ (limited for speed reasons).
36
+ """
37
+
38
+ def __init__(self, max_eig_dim: int = 512):
39
+ self.max_eig_dim = max_eig_dim
40
+
41
+ def dim_is_summarized(self, size: int):
42
+ return size > 10 and size != 31
43
+
44
+
45
+ def get_tensor_stats(
46
+ x: Tensor,
47
+ dim: int,
48
+ stats_type: str,
49
+ ) -> Tuple[Tensor, int]:
50
+ """
51
+ Returns the specified transformation of the Tensor (either x or x.abs()
52
+ or (x > 0), summed over all but the index `dim`.
53
+
54
+ Args:
55
+ x:
56
+ Tensor, tensor to be analyzed
57
+ dim:
58
+ Dimension with 0 <= dim < x.ndim
59
+ stats_type:
60
+ The stats_type includes several types:
61
+ "abs" -> take abs() before summing
62
+ "positive" -> take (x > 0) before summing
63
+ "rms" -> square before summing, we'll take sqrt later
64
+ "value" -> just sum x itself
65
+ "max", "min" -> take the maximum or minimum [over all other dims but dim] instead of summing
66
+ "rms-sort" -> this is a bit different than the others, it's based on computing the
67
+ rms over the specified dim and returning percentiles of the result (11 of them).
68
+ Returns:
69
+ stats: a Tensor of shape (x.shape[dim],).
70
+ count: an integer saying how many items were counted in each element
71
+ of stats.
72
+ """
73
+
74
+ if stats_type == "rms-sort":
75
+ rms = (x**2).mean(dim=dim).sqrt()
76
+ rms = rms.flatten()
77
+ rms = rms.sort()[0]
78
+ rms = rms[(torch.arange(11) * rms.numel() // 10).clamp(max=rms.numel() - 1)]
79
+ count = 1.0
80
+ return rms, count
81
+
82
+ count = x.numel() // x.shape[dim]
83
+
84
+ if stats_type == "eigs":
85
+ x = x.transpose(dim, -1)
86
+ x = x.reshape(-1, x.shape[-1])
87
+ # shape of returned tensor: (s, s),
88
+ # where s is size of dimension `dim` of original x.
89
+ return torch.matmul(x.transpose(0, 1), x), count
90
+ elif stats_type == "abs":
91
+ x = x.abs()
92
+ elif stats_type == "rms":
93
+ x = x**2
94
+ elif stats_type == "positive":
95
+ x = (x > 0).to(dtype=torch.float)
96
+ else:
97
+ assert stats_type in ["value", "max", "min"]
98
+
99
+ sum_dims = [d for d in range(x.ndim) if d != dim]
100
+ if len(sum_dims) > 0:
101
+ if stats_type == "max":
102
+ for dim in reversed(sum_dims):
103
+ x = torch.max(x, dim=dim)[0]
104
+ elif stats_type == "min":
105
+ for dim in reversed(sum_dims):
106
+ x = torch.min(x, dim=dim)[0]
107
+ else:
108
+ x = torch.sum(x, dim=sum_dims)
109
+ x = x.flatten().clone()
110
+ return x, count
111
+
112
+
113
+ @dataclass
114
+ class TensorAndCount:
115
+ tensor: Tensor
116
+ count: int
117
+
118
+
119
+ class TensorDiagnostic(object):
120
+ """This class is not directly used by the user, it is responsible for
121
+ collecting diagnostics for a module or parameter tensor of a torch.nn.Module.
122
+
123
+ Args:
124
+ opts:
125
+ Options object.
126
+ name:
127
+ The name associated with this diagnostics object, will probably be {module_name}.X
128
+ where X is "output" or "grad", or {parameter_name}.Y where Y is param_value or param_grad.
129
+ """
130
+
131
+ def __init__(self, opts: TensorDiagnosticOptions, name: str):
132
+ self.opts = opts
133
+ self.name = name
134
+ self.class_name = None # will assign in accumulate()
135
+
136
+ self.stats = None # we'll later assign a list to self.stats.
137
+ # It's a list of dicts, indexed by dim (i.e. by the
138
+ # axis of the tensor). The dicts, in turn, are
139
+ # indexed by `stats-type` which are strings in
140
+ # ["abs", "max", "min", "positive", "value", "rms"].
141
+
142
+ # scalar_stats contains some analysis of the activations and gradients,
143
+ self.scalar_stats = None
144
+
145
+ # the keys into self.stats[dim] are strings, whose values can be
146
+ # "abs", "max", "min" ,"value", "positive", "rms", "value".
147
+ # The values e.g. self.stats[dim]["rms"] are lists of dataclass TensorAndCount,
148
+ # containing a tensor and its associated count (which is the sum of the other dims
149
+ # that we aggregated over, e.g. the number of frames and/or batch elements and/or
150
+ # channels.
151
+ # ... we actually accumulate the Tensors / counts any time we have the same-dim tensor,
152
+ # only adding a new element to the list if there was a different dim.
153
+ # if the string in the key is "eigs", if we detect a length mismatch we put None as the value.
154
+
155
+ def accumulate(self, x, class_name: Optional[str] = None):
156
+ """
157
+ Accumulate tensors.
158
+ """
159
+ if class_name is not None:
160
+ self.class_name = class_name
161
+ if isinstance(x, Tuple):
162
+ x = x[0]
163
+ if not isinstance(x, Tensor):
164
+ return
165
+ if x.numel() == 0: # for empty tensor
166
+ return
167
+ x = x.detach().clone()
168
+ if x.ndim == 0:
169
+ x = x.unsqueeze(0)
170
+ ndim = x.ndim
171
+ if self.stats is None:
172
+ self.stats = [dict() for _ in range(ndim)]
173
+
174
+ for dim in range(ndim):
175
+ this_dim_stats = self.stats[dim]
176
+ if ndim > 1:
177
+ # rms-sort is different from the others, it's based on summing over just this
178
+ # dim, then sorting and returning the percentiles.
179
+ stats_types = [
180
+ "abs",
181
+ "max",
182
+ "min",
183
+ "positive",
184
+ "value",
185
+ "rms",
186
+ "rms-sort",
187
+ ]
188
+ if x.shape[dim] <= self.opts.max_eig_dim:
189
+ stats_types.append("eigs")
190
+ else:
191
+ stats_types = ["value", "abs", "max", "min"]
192
+
193
+ for stats_type in stats_types:
194
+ stats, count = get_tensor_stats(x, dim, stats_type)
195
+ if stats_type not in this_dim_stats:
196
+ this_dim_stats[stats_type] = [] # list of TensorAndCount
197
+
198
+ done = False
199
+ if this_dim_stats[stats_type] is None:
200
+ # we can reach here if we detected for stats_type "eigs" that
201
+ # where was more than one different size for this dim. Then we
202
+ # disable accumulating this stats type, as it uses too much memory.
203
+ continue
204
+ for s in this_dim_stats[stats_type]:
205
+ if s.tensor.shape == stats.shape:
206
+ if stats_type == "max":
207
+ s.tensor = torch.maximum(s.tensor, stats)
208
+
209
+ elif stats_type == "min":
210
+ s.tensor = torch.minimum(s.tensor, stats)
211
+ else:
212
+ assert stats_type != "max"
213
+ s.tensor += stats
214
+ s.count += count
215
+ done = True
216
+ break
217
+ if not done:
218
+ if this_dim_stats[stats_type] != [] and stats_type == "eigs":
219
+ # >1 size encountered on this dim, e.g. it's a batch or time dimension,
220
+ # don't accumulat "eigs" stats type, it uses too much memory
221
+ this_dim_stats[stats_type] = None
222
+ else:
223
+ this_dim_stats[stats_type].append(TensorAndCount(stats, count))
224
+
225
+ def print_diagnostics(self):
226
+ """Print diagnostics for each dimension of the tensor."""
227
+ if self.stats is None:
228
+ print(f"Warning: the stats of {self.name} is None.")
229
+ return
230
+ for dim, this_dim_stats in enumerate(self.stats):
231
+ if "rms" in this_dim_stats and "value" in this_dim_stats:
232
+ # produce "stddev" stats, which is centered RMS.
233
+ rms_stats_list = this_dim_stats["rms"]
234
+ value_stats_list = this_dim_stats["value"]
235
+ if len(rms_stats_list) == len(value_stats_list):
236
+ stddev_stats_list = []
237
+ for r, v in zip(rms_stats_list, value_stats_list):
238
+ stddev_stats_list.append(
239
+ # r.count and v.count should be the same, but we don't check this.
240
+ TensorAndCount(
241
+ r.tensor - v.tensor * v.tensor / (v.count + 1.0e-20),
242
+ r.count,
243
+ )
244
+ )
245
+ this_dim_stats["stddev"] = stddev_stats_list
246
+
247
+ for stats_type, stats_list in this_dim_stats.items():
248
+ # stats_type could be "rms", "value", "abs", "eigs", "positive", "min" or "max".
249
+ # "stats_list" could be a list of TensorAndCount (one list per distinct tensor
250
+ # shape of the stats), or None
251
+ if stats_list is None:
252
+ assert stats_type == "eigs"
253
+ continue
254
+
255
+ def get_count(count):
256
+ return 1 if stats_type in ["max", "min"] else count
257
+
258
+ if len(stats_list) == 1:
259
+ stats = stats_list[0].tensor / get_count(stats_list[0].count)
260
+ else:
261
+ # a dimension that has variable size in different nnet
262
+ # forwards, e.g. a time dimension in an ASR model.
263
+ stats = torch.cat(
264
+ [x.tensor / get_count(x.count) for x in stats_list], dim=0
265
+ )
266
+
267
+ if stats_type == "eigs":
268
+ try:
269
+ if hasattr(torch, "linalg") and hasattr(torch.linalg, "eigh"):
270
+ eigs, _ = torch.linalg.eigh(stats)
271
+ else:
272
+ eigs, _ = torch.symeig(stats)
273
+ stats = eigs.abs().sqrt()
274
+ except: # noqa
275
+ print("Error getting eigenvalues, trying another method.")
276
+ if hasattr(torch, "linalg") and hasattr(torch.linalg, "eig"):
277
+ eigs, _ = torch.linalg.eig(stats)
278
+ eigs = eigs.abs()
279
+ else:
280
+ eigs, _ = torch.eig(stats)
281
+ eigs = eigs.norm(dim=1)
282
+ stats = eigs.sqrt()
283
+ # sqrt so it reflects data magnitude, like stddev- not variance
284
+
285
+ if stats_type in ["rms", "stddev"]:
286
+ # we stored the square; after aggregation we need to take sqrt.
287
+ stats = stats.sqrt()
288
+
289
+ # if `summarize` we print percentiles of the stats; else,
290
+ # we print out individual elements.
291
+ summarize = (len(stats_list) > 1) or self.opts.dim_is_summarized(
292
+ stats.numel()
293
+ )
294
+ if summarize: # usually `summarize` will be true
295
+ # print out percentiles.
296
+ stats = stats.sort()[0]
297
+ num_percentiles = 10
298
+ size = stats.numel()
299
+ percentiles = []
300
+ for i in range(num_percentiles + 1):
301
+ index = (i * (size - 1)) // num_percentiles
302
+ percentiles.append(stats[index].item())
303
+ percentiles = ["%.2g" % x for x in percentiles]
304
+ percentiles = " ".join(percentiles)
305
+ ans = f"percentiles: [{percentiles}]"
306
+ else:
307
+ ans = stats.tolist()
308
+ ans = ["%.2g" % x for x in ans]
309
+ ans = "[" + " ".join(ans) + "]"
310
+ if stats_type in ["value", "rms", "stddev", "eigs"]:
311
+ # This norm is useful because it is strictly less than the largest
312
+ # sqrt(eigenvalue) of the variance, which we print out, and shows,
313
+ # speaking in an approximate way, how much of that largest eigenvalue
314
+ # can be attributed to the mean of the distribution.
315
+ norm = (stats**2).sum().sqrt().item()
316
+ ans += f", norm={norm:.2g}"
317
+ mean = stats.mean().item()
318
+ rms = (stats**2).mean().sqrt().item()
319
+ ans += f", mean={mean:.3g}, rms={rms:.3g}"
320
+
321
+ # OK, "ans" contains the actual stats, e.g.
322
+ # ans = "percentiles: [0.43 0.46 0.48 0.49 0.49 0.5 0.51 0.52 0.53 0.54 0.59], mean=0.5, rms=0.5"
323
+
324
+ sizes = [x.tensor.shape[0] for x in stats_list]
325
+ size_str = (
326
+ f"{sizes[0]}" if len(sizes) == 1 else f"{min(sizes)}..{max(sizes)}"
327
+ )
328
+ maybe_class_name = (
329
+ f" type={self.class_name}," if self.class_name is not None else ""
330
+ )
331
+ print(
332
+ f"module={self.name},{maybe_class_name} dim={dim}, size={size_str}, {stats_type} {ans}"
333
+ )
334
+
335
+
336
+ class ScalarDiagnostic(object):
337
+ """This class is not directly used by the user, it is responsible for
338
+ collecting diagnostics for a single module (subclass of torch.nn.Module) that
339
+ represents some kind of nonlinearity, e.g. ReLU, sigmoid, etc.
340
+ """
341
+
342
+ def __init__(self, opts: TensorDiagnosticOptions, name: str):
343
+ self.opts = opts
344
+ self.name = name
345
+ self.class_name = None # will assign in accumulate()
346
+ self.is_forward_pass = True
347
+
348
+ self.tick_scale = None
349
+
350
+ self.saved_inputs = []
351
+ self.is_ok = True
352
+
353
+ self.counts = None
354
+ self.sum_grad = None
355
+ self.sum_gradsq = None
356
+ self.sum_abs_grad = None
357
+
358
+ def accumulate_input(self, x: Tensor, class_name: Optional[str] = None):
359
+ """
360
+ Called in forward pass.
361
+ """
362
+ if not self.is_forward_pass:
363
+ # in case we did a forward pass without a backward pass, for some reason.
364
+ self.saved_inputs = []
365
+ self.is_forward_pass = True
366
+
367
+ if class_name is not None:
368
+ self.class_name = class_name
369
+ if not self.is_ok:
370
+ return
371
+
372
+ limit = 10
373
+ if len(self.saved_inputs) > limit:
374
+ print(
375
+ f"ERROR: forward pass called for this module over {limit} times with no backward pass. "
376
+ f" Will not accumulate scalar stats."
377
+ )
378
+ self.is_ok = False
379
+ return
380
+ self.saved_inputs.append(x)
381
+
382
+ def accumulate_output_grad(self, grad: Tensor):
383
+ if not self.is_ok:
384
+ return
385
+ if self.is_forward_pass:
386
+ self.is_forward_pass = False
387
+
388
+ last_shape = (
389
+ "n/a" if len(self.saved_inputs) == 0 else self.saved_inputs[-1].shape
390
+ )
391
+ if len(self.saved_inputs) == 0 or grad.shape != last_shape:
392
+ print(
393
+ f"ERROR: shape mismatch or no forward activation present when backward "
394
+ f"pass called: grad shape ={tuple(grad.shape)}, num-saved-inputs={len(self.saved_inputs)}"
395
+ f", shape-of-last-saved-input={last_shape}"
396
+ )
397
+ self.is_ok = False
398
+ return
399
+
400
+ x = self.saved_inputs.pop()
401
+ self.process_input_and_grad(x, grad)
402
+
403
+ def process_input_and_grad(self, x: Tensor, grad: Tensor):
404
+ assert x.shape == grad.shape
405
+ x = x.flatten()
406
+ grad = grad.flatten()
407
+
408
+ num_ticks_per_side = 256
409
+
410
+ if self.tick_scale is None:
411
+ x_abs_sorted = x.abs().sort()[0]
412
+ # take the 98th percentile as the largest value we count separately.
413
+ index = int(x.numel() * 0.98)
414
+ self.tick_scale = float(x_abs_sorted[index] / num_ticks_per_side)
415
+
416
+ # integerize from tick * (-num ticks_per_side .. num_ticks_per_side - 1]
417
+ self.counts = torch.zeros(
418
+ 2 * num_ticks_per_side, dtype=torch.long, device=x.device
419
+ )
420
+ self.sum_grad = torch.zeros(
421
+ 2 * num_ticks_per_side, dtype=torch.double, device=x.device
422
+ )
423
+ # sum_gradsq is for getting error bars.
424
+ self.sum_gradsq = torch.zeros(
425
+ 2 * num_ticks_per_side, dtype=torch.double, device=x.device
426
+ )
427
+ self.sum_abs_grad = torch.zeros(
428
+ 2 * num_ticks_per_side, dtype=torch.double, device=x.device
429
+ )
430
+
431
+ # this will round down.
432
+ x = (x / self.tick_scale).to(torch.long)
433
+ x = x.clamp_(min=-num_ticks_per_side, max=num_ticks_per_side - 1)
434
+ x = x + num_ticks_per_side
435
+
436
+ self.counts.index_add_(dim=0, index=x, source=torch.ones_like(x))
437
+ self.sum_grad.index_add_(dim=0, index=x, source=grad.to(torch.double))
438
+ self.sum_gradsq.index_add_(
439
+ dim=0, index=x, source=(grad * grad).to(torch.double)
440
+ )
441
+ self.sum_abs_grad.index_add_(dim=0, index=x, source=grad.abs().to(torch.double))
442
+
443
+ def print_diagnostics(self):
444
+ """Print diagnostics."""
445
+ if self.is_ok is False or self.counts is None:
446
+ print(f"Warning: no stats accumulated for {self.name}, is_ok={self.is_ok}")
447
+ return
448
+
449
+ counts = self.counts.to("cpu")
450
+ sum_grad = self.sum_grad.to(device="cpu", dtype=torch.float32)
451
+ sum_gradsq = self.sum_gradsq.to(device="cpu", dtype=torch.float32)
452
+ sum_abs_grad = self.sum_abs_grad.to(device="cpu", dtype=torch.float32)
453
+
454
+ counts_cumsum = counts.cumsum(dim=0)
455
+ counts_tot = counts_cumsum[-1]
456
+
457
+ # subdivide the distribution up into `num_bins` intervals for analysis, for greater
458
+ # statistical significance. each bin corresponds to multiple of the original 'tick' intervals.
459
+ num_bins = 20
460
+
461
+ # integer division
462
+ counts_per_bin = (counts_tot // num_bins) + 1
463
+ bin_indexes = counts_cumsum // counts_per_bin
464
+ bin_indexes = bin_indexes.clamp(min=0, max=num_bins).to(torch.long)
465
+
466
+ bin_counts = torch.zeros(num_bins, dtype=torch.long)
467
+ bin_counts.index_add_(dim=0, index=bin_indexes, source=counts)
468
+ bin_grad = torch.zeros(num_bins)
469
+ bin_grad.index_add_(dim=0, index=bin_indexes, source=sum_grad)
470
+ bin_gradsq = torch.zeros(num_bins)
471
+ bin_gradsq.index_add_(dim=0, index=bin_indexes, source=sum_gradsq)
472
+ bin_abs_grad = torch.zeros(num_bins)
473
+ bin_abs_grad.index_add_(dim=0, index=bin_indexes, source=sum_abs_grad)
474
+
475
+ avg_grad = bin_grad / bin_counts
476
+ avg_grad_stddev = (bin_gradsq / bin_counts).sqrt()
477
+
478
+ bin_boundary_counts = (
479
+ torch.arange(num_bins + 1, dtype=torch.long) * counts_per_bin
480
+ )
481
+ bin_tick_indexes = torch.searchsorted(counts_cumsum, bin_boundary_counts)
482
+ # boundaries are the "x" values between the bins, e.g. corresponding to the
483
+ # locations of percentiles of the distribution.
484
+ num_ticks_per_side = counts.numel() // 2
485
+ bin_boundaries = (bin_tick_indexes - num_ticks_per_side) * self.tick_scale
486
+
487
+ bin_grad = bin_grad / (bin_counts + 1)
488
+ bin_conf_interval = bin_gradsq.sqrt() / (
489
+ bin_counts + 1
490
+ ) # consider this a standard deviation.
491
+ # bin_grad / bin_abs_grad will give us a sense for how important in a practical sense,
492
+ # the gradients are.
493
+ bin_abs_grad = bin_abs_grad / (bin_counts + 1)
494
+
495
+ bin_rel_grad = bin_grad / (bin_abs_grad + 1.0e-20)
496
+ bin_conf = bin_grad / (bin_conf_interval + 1.0e-20)
497
+
498
+ def tensor_to_str(x: Tensor):
499
+ x = ["%.2g" % f for f in x]
500
+ x = "[" + " ".join(x) + "]"
501
+ return x
502
+
503
+ maybe_class_name = (
504
+ f" type={self.class_name}," if self.class_name is not None else ""
505
+ )
506
+
507
+ print(
508
+ f"module={self.name},{maybe_class_name} bin-boundaries={tensor_to_str(bin_boundaries)}, "
509
+ f"rel_grad={tensor_to_str(bin_rel_grad)}, grad_conf={tensor_to_str(bin_conf)}"
510
+ )
511
+
512
+
513
+ class ModelDiagnostic(object):
514
+ """This class stores diagnostics for all tensors in the torch.nn.Module.
515
+
516
+ Args:
517
+ opts:
518
+ Options object.
519
+ """
520
+
521
+ def __init__(self, opts: Optional[TensorDiagnosticOptions] = None):
522
+ # In this dictionary, the keys are tensors names and the values
523
+ # are corresponding TensorDiagnostic objects.
524
+ if opts is None:
525
+ self.opts = TensorDiagnosticOptions()
526
+ else:
527
+ self.opts = opts
528
+ self.diagnostics = dict()
529
+
530
+ def __getitem__(self, name: str):
531
+ T = ScalarDiagnostic if name[-7:] == ".scalar" else TensorDiagnostic
532
+ if name not in self.diagnostics:
533
+ self.diagnostics[name] = T(self.opts, name)
534
+ return self.diagnostics[name]
535
+
536
+ def print_diagnostics(self):
537
+ """Print diagnostics for each tensor."""
538
+ for k in sorted(self.diagnostics.keys()):
539
+ self.diagnostics[k].print_diagnostics()
540
+
541
+
542
+ def get_class_name(module: nn.Module):
543
+ ans = type(module).__name__
544
+ # we put the below in try blocks in case anyone is using a different version of these modules that
545
+ # might have different member names.
546
+ if ans == "Balancer" or ans == "ActivationBalancer":
547
+ try:
548
+ ans += f"[{float(module.min_positive)},{float(module.max_positive)},{float(module.min_abs)},{float(module.max_abs)}]"
549
+ except:
550
+ pass
551
+ elif ans == "AbsValuePenalizer":
552
+ try:
553
+ ans += f"[{module.limit}]"
554
+ except:
555
+ pass
556
+ return ans
557
+
558
+
559
+ def attach_diagnostics(
560
+ model: nn.Module, opts: Optional[TensorDiagnosticOptions] = None
561
+ ) -> ModelDiagnostic:
562
+ """Attach a ModelDiagnostic object to the model by
563
+ 1) registering forward hook and backward hook on each module, to accumulate
564
+ its output tensors and gradient tensors, respectively;
565
+ 2) registering backward hook on each module parameter, to accumulate its
566
+ values and gradients.
567
+
568
+ Args:
569
+ model:
570
+ the model to be analyzed.
571
+ opts:
572
+ Options object.
573
+
574
+ Returns:
575
+ The ModelDiagnostic object attached to the model.
576
+ """
577
+
578
+ ans = ModelDiagnostic(opts)
579
+ for name, module in model.named_modules():
580
+ if name == "":
581
+ name = "<top-level>"
582
+
583
+ # Setting model_diagnostic=ans and n=name below, instead of trying to
584
+ # capture the variables, ensures that we use the current values.
585
+ # (this matters for `name`, since the variable gets overwritten).
586
+ # These closures don't really capture by value, only by
587
+ # "the final value the variable got in the function" :-(
588
+ def forward_hook(_module, _input, _output, _model_diagnostic=ans, _name=name):
589
+ if isinstance(_output, tuple) and len(_output) == 1:
590
+ _output = _output[0]
591
+
592
+ if isinstance(_output, Tensor) and _output.dtype in (
593
+ torch.float32,
594
+ torch.float16,
595
+ torch.float64,
596
+ ):
597
+ _model_diagnostic[f"{_name}.output"].accumulate(
598
+ _output, class_name=get_class_name(_module)
599
+ )
600
+ elif isinstance(_output, tuple):
601
+ for i, o in enumerate(_output):
602
+ if isinstance(o, Tensor) and o.dtype in (
603
+ torch.float32,
604
+ torch.float16,
605
+ torch.float64,
606
+ ):
607
+ _model_diagnostic[f"{_name}.output[{i}]"].accumulate(
608
+ o, class_name=get_class_name(_module)
609
+ )
610
+
611
+ def backward_hook(_module, _input, _output, _model_diagnostic=ans, _name=name):
612
+ if isinstance(_output, tuple) and len(_output) == 1:
613
+ _output = _output[0]
614
+ if isinstance(_output, Tensor) and _output.dtype in (
615
+ torch.float32,
616
+ torch.float16,
617
+ torch.float64,
618
+ ):
619
+ _model_diagnostic[f"{_name}.grad"].accumulate(
620
+ _output, class_name=get_class_name(_module)
621
+ )
622
+ elif isinstance(_output, tuple):
623
+ for i, o in enumerate(_output):
624
+ if isinstance(o, Tensor) and o.dtype in (
625
+ torch.float32,
626
+ torch.float16,
627
+ torch.float64,
628
+ ):
629
+ _model_diagnostic[f"{_name}.grad[{i}]"].accumulate(
630
+ o, class_name=get_class_name(_module)
631
+ )
632
+
633
+ module.register_forward_hook(forward_hook)
634
+ if hasattr(module, "register_full_backward_hook"):
635
+ module.register_full_backward_hook(backward_hook)
636
+ else:
637
+ module.register_backward_hook(backward_hook)
638
+
639
+ if type(module).__name__ in [
640
+ "Sigmoid",
641
+ "Tanh",
642
+ "ReLU",
643
+ "TanSwish",
644
+ "Swish",
645
+ "DoubleSwish",
646
+ "Swoosh",
647
+ ]:
648
+ # For these specific module types, accumulate some additional diagnostics
649
+ # that can help us improve the activation function. These require a lot of memory,
650
+ # to save the forward activations, so limit this to some select classes.
651
+ # Note: this will not work correctly for all model types.
652
+ def scalar_forward_hook(
653
+ _module, _input, _output, _model_diagnostic=ans, _name=name
654
+ ):
655
+ if isinstance(_input, tuple):
656
+ (_input,) = _input
657
+ assert isinstance(_input, Tensor)
658
+ _model_diagnostic[f"{_name}.scalar"].accumulate_input(
659
+ _input, class_name=get_class_name(_module)
660
+ )
661
+
662
+ def scalar_backward_hook(
663
+ _module, _input, _output, _model_diagnostic=ans, _name=name
664
+ ):
665
+ if isinstance(_output, tuple):
666
+ (_output,) = _output
667
+ assert isinstance(_output, Tensor)
668
+ _model_diagnostic[f"{_name}.scalar"].accumulate_output_grad(_output)
669
+
670
+ module.register_forward_hook(scalar_forward_hook)
671
+ if hasattr(module, "register_full_backward_hook"):
672
+ module.register_full_backward_hook(scalar_backward_hook)
673
+ else:
674
+ module.register_backward_hook(scalar_backward_hook)
675
+
676
+ for name, parameter in model.named_parameters():
677
+
678
+ def param_backward_hook(
679
+ grad, _parameter=parameter, _model_diagnostic=ans, _name=name
680
+ ):
681
+ _model_diagnostic[f"{_name}.param_value"].accumulate(_parameter)
682
+ _model_diagnostic[f"{_name}.param_grad"].accumulate(grad)
683
+
684
+ try:
685
+ parameter.register_hook(param_backward_hook)
686
+ except:
687
+ logging.warning(
688
+ f"Warning: could not register backward hook for parameter {name}, "
689
+ f"it might not be differentiable."
690
+ )
691
+
692
+ return ans
693
+
694
+
695
+ def _test_tensor_diagnostic():
696
+ opts = TensorDiagnosticOptions(512)
697
+
698
+ diagnostic = TensorDiagnostic(opts, "foo")
699
+
700
+ for _ in range(10):
701
+ diagnostic.accumulate(torch.randn(50, 100) * 10.0)
702
+
703
+ diagnostic.print_diagnostics()
704
+
705
+ model = nn.Sequential(nn.Linear(100, 50), nn.ReLU(), nn.Linear(50, 80))
706
+
707
+ diagnostic = attach_diagnostics(model, opts)
708
+ for _ in range(10):
709
+ T = random.randint(200, 300)
710
+ x = torch.randn(T, 100)
711
+ y = model(x)
712
+ y.sum().backward()
713
+
714
+ diagnostic.print_diagnostics()
715
+
716
+
717
+ if __name__ == "__main__":
718
+ _test_tensor_diagnostic()
icefall/dist.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import os
19
+
20
+ import torch
21
+ from torch import distributed as dist
22
+
23
+
24
+ def setup_dist(
25
+ rank=None, world_size=None, master_port=None, use_ddp_launch=False, master_addr=None
26
+ ):
27
+ """
28
+ rank and world_size are used only if use_ddp_launch is False.
29
+ """
30
+ if "MASTER_ADDR" not in os.environ:
31
+ os.environ["MASTER_ADDR"] = (
32
+ "localhost" if master_addr is None else str(master_addr)
33
+ )
34
+
35
+ if "MASTER_PORT" not in os.environ:
36
+ os.environ["MASTER_PORT"] = "12354" if master_port is None else str(master_port)
37
+
38
+ if use_ddp_launch is False:
39
+ dist.init_process_group("nccl", rank=rank, world_size=world_size)
40
+ torch.cuda.set_device(rank)
41
+ else:
42
+ dist.init_process_group("nccl")
43
+
44
+
45
+ def cleanup_dist():
46
+ dist.destroy_process_group()
47
+
48
+
49
+ def get_world_size():
50
+ if "WORLD_SIZE" in os.environ:
51
+ return int(os.environ["WORLD_SIZE"])
52
+ if dist.is_available() and dist.is_initialized():
53
+ return dist.get_world_size()
54
+ else:
55
+ return 1
56
+
57
+
58
+ def get_rank():
59
+ if "RANK" in os.environ:
60
+ return int(os.environ["RANK"])
61
+ elif dist.is_available() and dist.is_initialized():
62
+ return dist.get_rank()
63
+ else:
64
+ return 0
65
+
66
+
67
+ def get_local_rank():
68
+ return int(os.environ.get("LOCAL_RANK", 0))
icefall/env.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang
2
+ # Wei Kang)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ import socket
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+ from typing import Any, Dict
24
+
25
+ import k2
26
+ import k2.version
27
+ import lhotse
28
+ import torch
29
+
30
+
31
+ def get_git_sha1():
32
+ try:
33
+ git_commit = (
34
+ subprocess.run(
35
+ ["git", "rev-parse", "--short", "HEAD"],
36
+ check=True,
37
+ stdout=subprocess.PIPE,
38
+ )
39
+ .stdout.decode()
40
+ .rstrip("\n")
41
+ .strip()
42
+ )
43
+ dirty_commit = (
44
+ len(
45
+ subprocess.run(
46
+ ["git", "diff", "--shortstat"],
47
+ check=True,
48
+ stdout=subprocess.PIPE,
49
+ )
50
+ .stdout.decode()
51
+ .rstrip("\n")
52
+ .strip()
53
+ )
54
+ > 0
55
+ )
56
+ git_commit = git_commit + "-dirty" if dirty_commit else git_commit + "-clean"
57
+ except: # noqa
58
+ return None
59
+
60
+ return git_commit
61
+
62
+
63
+ def get_git_date():
64
+ try:
65
+ git_date = (
66
+ subprocess.run(
67
+ ["git", "log", "-1", "--format=%ad", "--date=local"],
68
+ check=True,
69
+ stdout=subprocess.PIPE,
70
+ )
71
+ .stdout.decode()
72
+ .rstrip("\n")
73
+ .strip()
74
+ )
75
+ except: # noqa
76
+ return None
77
+
78
+ return git_date
79
+
80
+
81
+ def get_git_branch_name():
82
+ try:
83
+ git_date = (
84
+ subprocess.run(
85
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
86
+ check=True,
87
+ stdout=subprocess.PIPE,
88
+ )
89
+ .stdout.decode()
90
+ .rstrip("\n")
91
+ .strip()
92
+ )
93
+ except: # noqa
94
+ return None
95
+
96
+ return git_date
97
+
98
+
99
+ def get_env_info() -> Dict[str, Any]:
100
+ """Get the environment information."""
101
+ return {
102
+ "k2-version": k2.version.__version__,
103
+ "k2-build-type": k2.version.__build_type__,
104
+ "k2-with-cuda": k2.with_cuda,
105
+ "k2-git-sha1": k2.version.__git_sha1__,
106
+ "k2-git-date": k2.version.__git_date__,
107
+ "lhotse-version": lhotse.__version__,
108
+ "torch-version": str(torch.__version__),
109
+ "torch-cuda-available": torch.cuda.is_available(),
110
+ "torch-cuda-version": torch.version.cuda,
111
+ "python-version": ".".join(sys.version.split(".")[:2]),
112
+ "icefall-git-branch": get_git_branch_name(),
113
+ "icefall-git-sha1": get_git_sha1(),
114
+ "icefall-git-date": get_git_date(),
115
+ "icefall-path": str(Path(__file__).resolve().parent.parent),
116
+ "k2-path": str(Path(k2.__file__).resolve()),
117
+ "lhotse-path": str(Path(lhotse.__file__).resolve()),
118
+ "hostname": socket.gethostname(),
119
+ "IP address": socket.gethostbyname(socket.gethostname()),
120
+ }
icefall/err.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Xiaomi Corp. (authors: Zengrui Jin,)
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
+ def raise_grad_scale_is_too_small_error(cur_grad_scale: float):
19
+ raise RuntimeError(
20
+ f"""
21
+ grad_scale is too small, exiting: {cur_grad_scale}
22
+
23
+ ========================= NOTE =========================
24
+ If you see this error, it means that the gradient scale is too small.
25
+
26
+ The default base_lr is 0.045 / 0.05 (depends on which recipe you are
27
+ using), this is an empirical value obtained mostly using 4 * 32GB V100
28
+ GPUs with a max_duration of approx. 1,000.
29
+ The proper value of base_lr may vary depending on the number of GPUs
30
+ and the value of max-duration you are using.
31
+
32
+ To fix this issue, you may need to adjust the value of base_lr accordingly.
33
+
34
+ We would suggest you to decrease the value of base_lr by 0.005 (e.g.,
35
+ from 0.045 to 0.04), and try again. If the error still exists, you may
36
+ repeat the process until base_lr hits 0.02. (Note that this will lead to
37
+ certain loss of performance, but it should work. You can compensate this by
38
+ increasing the num_epochs.)
39
+
40
+ If the error still exists, you could try to seek help by raising an issue,
41
+ with a detailed description of (a) your computational resources, (b) the
42
+ base_lr and (c) the max_duration you are using, (d) detailed configuration
43
+ of your model.
44
+
45
+ ========================================================
46
+ """
47
+ )
icefall/graph_compiler.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ from typing import List
19
+
20
+ import k2
21
+ import torch
22
+
23
+ from icefall.lexicon import Lexicon
24
+
25
+
26
+ class CtcTrainingGraphCompiler(object):
27
+ def __init__(
28
+ self,
29
+ lexicon: Lexicon,
30
+ device: torch.device,
31
+ oov: str = "<UNK>",
32
+ need_repeat_flag: bool = False,
33
+ ):
34
+ """
35
+ Args:
36
+ lexicon:
37
+ It is built from `data/lang/lexicon.txt`.
38
+ device:
39
+ The device to use for operations compiling transcripts to FSAs.
40
+ oov:
41
+ Out of vocabulary word. When a word in the transcript
42
+ does not exist in the lexicon, it is replaced with `oov`.
43
+ need_repeat_flag:
44
+ If True, will add an attribute named `_is_repeat_token_` to ctc_topo
45
+ indicating whether this token is a repeat token in ctc graph.
46
+ This attribute is needed to implement delay-penalty for phone-based
47
+ ctc loss. See https://github.com/k2-fsa/k2/pull/1086 for more
48
+ details. Note: The above change MUST be included in k2 to open this
49
+ flag.
50
+ """
51
+ L_inv = lexicon.L_inv.to(device)
52
+ assert L_inv.requires_grad is False
53
+
54
+ assert oov in lexicon.word_table
55
+
56
+ self.L_inv = k2.arc_sort(L_inv)
57
+ self.oov_id = lexicon.word_table[oov]
58
+ self.word_table = lexicon.word_table
59
+
60
+ max_token_id = max(lexicon.tokens)
61
+ ctc_topo = k2.ctc_topo(max_token_id, modified=False)
62
+
63
+ self.ctc_topo = ctc_topo.to(device)
64
+
65
+ if need_repeat_flag:
66
+ self.ctc_topo._is_repeat_token_ = (
67
+ self.ctc_topo.labels != self.ctc_topo.aux_labels
68
+ )
69
+
70
+ self.device = device
71
+
72
+ def compile(self, texts: List[str]) -> k2.Fsa:
73
+ """Build decoding graphs by composing ctc_topo with
74
+ given transcripts.
75
+
76
+ Args:
77
+ texts:
78
+ A list of strings. Each string contains a sentence for an utterance.
79
+ A sentence consists of spaces separated words. An example `texts`
80
+ looks like:
81
+
82
+ ['hello icefall', 'CTC training with k2']
83
+
84
+ Returns:
85
+ An FsaVec, the composition result of `self.ctc_topo` and the
86
+ transcript FSA.
87
+ """
88
+ transcript_fsa = self.convert_transcript_to_fsa(texts)
89
+
90
+ # NOTE: k2.compose runs on CUDA only when treat_epsilons_specially
91
+ # is False, so we add epsilon self-loops here
92
+ fsa_with_self_loops = k2.remove_epsilon_and_add_self_loops(transcript_fsa)
93
+
94
+ fsa_with_self_loops = k2.arc_sort(fsa_with_self_loops)
95
+
96
+ decoding_graph = k2.compose(
97
+ self.ctc_topo, fsa_with_self_loops, treat_epsilons_specially=False
98
+ )
99
+
100
+ assert decoding_graph.requires_grad is False
101
+
102
+ return decoding_graph
103
+
104
+ def texts_to_ids(self, texts: List[str]) -> List[List[int]]:
105
+ """Convert a list of texts to a list-of-list of word IDs.
106
+
107
+ Args:
108
+ texts:
109
+ It is a list of strings. Each string consists of space(s)
110
+ separated words. An example containing two strings is given below:
111
+
112
+ ['HELLO ICEFALL', 'HELLO k2']
113
+ Returns:
114
+ Return a list-of-list of word IDs.
115
+ """
116
+ word_ids_list = []
117
+ for text in texts:
118
+ word_ids = []
119
+ for word in text.split():
120
+ if word in self.word_table:
121
+ word_ids.append(self.word_table[word])
122
+ else:
123
+ word_ids.append(self.oov_id)
124
+ word_ids_list.append(word_ids)
125
+ return word_ids_list
126
+
127
+ def convert_transcript_to_fsa(self, texts: List[str]) -> k2.Fsa:
128
+ """Convert a list of transcript texts to an FsaVec.
129
+
130
+ Args:
131
+ texts:
132
+ A list of strings. Each string contains a sentence for an utterance.
133
+ A sentence consists of spaces separated words. An example `texts`
134
+ looks like:
135
+
136
+ ['hello icefall', 'CTC training with k2']
137
+
138
+ Returns:
139
+ Return an FsaVec, whose `shape[0]` equals to `len(texts)`.
140
+ """
141
+ word_ids_list = []
142
+ for text in texts:
143
+ word_ids = []
144
+ for word in text.split():
145
+ if word in self.word_table:
146
+ word_ids.append(self.word_table[word])
147
+ else:
148
+ word_ids.append(self.oov_id)
149
+ word_ids_list.append(word_ids)
150
+
151
+ word_fsa = k2.linear_fsa(word_ids_list, self.device)
152
+
153
+ word_fsa_with_self_loops = k2.add_epsilon_self_loops(word_fsa)
154
+
155
+ fsa = k2.intersect(
156
+ self.L_inv, word_fsa_with_self_loops, treat_epsilons_specially=False
157
+ )
158
+ # fsa has word ID as labels and token ID as aux_labels, so
159
+ # we need to invert it
160
+ ans_fsa = fsa.invert_()
161
+ return k2.arc_sort(ans_fsa)
icefall/hooks.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021-2024 Xiaomi Corporation (authors: Zengwei Yao,
2
+ # Daniel Povey,
3
+ # Zengrui Jin,)
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 logging
20
+ import random
21
+
22
+ import torch
23
+ from torch import Tensor, nn
24
+
25
+
26
+ def register_inf_check_hooks(model: nn.Module) -> None:
27
+ """Registering forward hook on each module, to check
28
+ whether its output tensors is not finite.
29
+
30
+ Args:
31
+ model:
32
+ the model to be analyzed.
33
+ """
34
+
35
+ for name, module in model.named_modules():
36
+ if name == "":
37
+ name = "<top-level>"
38
+
39
+ # default param _name is a way to capture the current value of the variable "name".
40
+ def forward_hook(_module, _input, _output, _name=name):
41
+ if isinstance(_output, Tensor):
42
+ try:
43
+ if not torch.isfinite(_output.to(torch.float32).sum()):
44
+ logging.warning(f"The sum of {_name}.output is not finite")
45
+ except RuntimeError: # e.g. CUDA out of memory
46
+ pass
47
+ elif isinstance(_output, tuple):
48
+ for i, o in enumerate(_output):
49
+ if isinstance(o, tuple):
50
+ o = o[0]
51
+ if not isinstance(o, Tensor):
52
+ continue
53
+ try:
54
+ if not torch.isfinite(o.to(torch.float32).sum()):
55
+ logging.warning(
56
+ f"The sum of {_name}.output[{i}] is not finite"
57
+ )
58
+ except RuntimeError: # e.g. CUDA out of memory
59
+ pass
60
+
61
+ # default param _name is a way to capture the current value of the variable "name".
62
+ def backward_hook(_module, _input, _output, _name=name):
63
+ if isinstance(_output, Tensor):
64
+ try:
65
+ if not torch.isfinite(_output.to(torch.float32).sum()):
66
+ logging.warning(f"The sum of {_name}.grad is not finite")
67
+ except RuntimeError: # e.g. CUDA out of memory
68
+ pass
69
+
70
+ elif isinstance(_output, tuple):
71
+ for i, o in enumerate(_output):
72
+ if isinstance(o, tuple):
73
+ o = o[0]
74
+ if not isinstance(o, Tensor):
75
+ continue
76
+ if not torch.isfinite(o.to(torch.float32).sum()):
77
+ logging.warning(f"The sum of {_name}.grad[{i}] is not finite")
78
+
79
+ module.register_forward_hook(forward_hook)
80
+
81
+ if hasattr(module, "register_full_backward_hook"):
82
+ module.register_full_backward_hook(backward_hook)
83
+ else:
84
+ module.register_backward_hook(backward_hook)
85
+
86
+ for name, parameter in model.named_parameters():
87
+
88
+ def param_backward_hook(grad, _name=name):
89
+ if not torch.isfinite(grad.to(torch.float32).sum()):
90
+ logging.warning(f"The sum of {_name}.param_grad is not finite")
91
+
92
+ try:
93
+ parameter.register_hook(param_backward_hook)
94
+ except:
95
+ logging.warning(
96
+ f"Warning: could not register backward hook for parameter {name}, "
97
+ f"it might not be differentiable."
98
+ )
99
+
100
+
101
+ def _test_inf_check_hooks():
102
+ model = nn.Sequential(nn.Linear(100, 50), nn.Linear(50, 80))
103
+
104
+ register_inf_check_hooks(model)
105
+ for _ in range(10):
106
+ T = random.randint(200, 300)
107
+ x = torch.randn(T, 100) + float("inf") * (T % 2)
108
+ y = model(x)
109
+ y.sum().backward()
110
+
111
+
112
+ if __name__ == "__main__":
113
+ _test_inf_check_hooks()
icefall/lexicon.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import logging
19
+ import re
20
+ import sys
21
+ from pathlib import Path
22
+ from typing import List, Tuple
23
+
24
+ import k2
25
+ import torch
26
+
27
+
28
+ def read_lexicon(filename: str) -> List[Tuple[str, List[str]]]:
29
+ """Read a lexicon from `filename`.
30
+
31
+ Each line in the lexicon contains "word p1 p2 p3 ...".
32
+ That is, the first field is a word and the remaining
33
+ fields are tokens. Fields are separated by space(s).
34
+
35
+ Args:
36
+ filename:
37
+ Path to the lexicon.txt
38
+
39
+ Returns:
40
+ A list of tuples., e.g., [('w', ['p1', 'p2']), ('w1', ['p3, 'p4'])]
41
+ """
42
+ ans = []
43
+
44
+ with open(filename, "r", encoding="utf-8") as f:
45
+ whitespace = re.compile("[ \t]+")
46
+ for line in f:
47
+ a = whitespace.split(line.strip(" \t\r\n"))
48
+ if len(a) == 0:
49
+ continue
50
+
51
+ if len(a) < 2:
52
+ logging.info(f"Found bad line {line} in lexicon file {filename}")
53
+ logging.info("Every line is expected to contain at least 2 fields")
54
+ sys.exit(1)
55
+ word = a[0]
56
+ if word == "<eps>":
57
+ logging.info(f"Found bad line {line} in lexicon file {filename}")
58
+ logging.info("<eps> should not be a valid word")
59
+ sys.exit(1)
60
+
61
+ tokens = a[1:]
62
+ ans.append((word, tokens))
63
+
64
+ return ans
65
+
66
+
67
+ def write_lexicon(filename: str, lexicon: List[Tuple[str, List[str]]]) -> None:
68
+ """Write a lexicon to a file.
69
+
70
+ Args:
71
+ filename:
72
+ Path to the lexicon file to be generated.
73
+ lexicon:
74
+ It can be the return value of :func:`read_lexicon`.
75
+ """
76
+ with open(filename, "w", encoding="utf-8") as f:
77
+ for word, tokens in lexicon:
78
+ f.write(f"{word} {' '.join(tokens)}\n")
79
+
80
+
81
+ def convert_lexicon_to_ragged(
82
+ filename: str, word_table: k2.SymbolTable, token_table: k2.SymbolTable
83
+ ) -> k2.RaggedTensor:
84
+ """Read a lexicon and convert it to a ragged tensor.
85
+
86
+ The ragged tensor has two axes: [word][token].
87
+
88
+ Caution:
89
+ We assume that each word has a unique pronunciation.
90
+
91
+ Args:
92
+ filename:
93
+ Filename of the lexicon. It has a format that can be read
94
+ by :func:`read_lexicon`.
95
+ word_table:
96
+ The word symbol table.
97
+ token_table:
98
+ The token symbol table.
99
+ Returns:
100
+ A k2 ragged tensor with two axes [word][token].
101
+ """
102
+ disambig_id = word_table["#0"]
103
+ # We reuse the same words.txt from the phone based lexicon
104
+ # so that we can share the same G.fst. Here, we have to
105
+ # exclude some words present only in the phone based lexicon.
106
+ excluded_words = ["<eps>", "!SIL", "<SPOKEN_NOISE>"]
107
+
108
+ # epsilon is not a word, but it occupies a position
109
+ #
110
+ row_splits = [0]
111
+ token_ids_list = []
112
+
113
+ lexicon_tmp = read_lexicon(filename)
114
+ lexicon = dict(lexicon_tmp)
115
+ if len(lexicon_tmp) != len(lexicon):
116
+ raise RuntimeError("It's assumed that each word has a unique pronunciation")
117
+
118
+ for i in range(disambig_id):
119
+ w = word_table[i]
120
+ if w in excluded_words:
121
+ row_splits.append(row_splits[-1])
122
+ continue
123
+ tokens = lexicon[w]
124
+ token_ids = [token_table[k] for k in tokens]
125
+
126
+ row_splits.append(row_splits[-1] + len(token_ids))
127
+ token_ids_list.extend(token_ids)
128
+
129
+ cached_tot_size = row_splits[-1]
130
+ row_splits = torch.tensor(row_splits, dtype=torch.int32)
131
+
132
+ shape = k2.ragged.create_ragged_shape2(
133
+ row_splits,
134
+ None,
135
+ cached_tot_size,
136
+ )
137
+ values = torch.tensor(token_ids_list, dtype=torch.int32)
138
+
139
+ return k2.RaggedTensor(shape, values)
140
+
141
+
142
+ class Lexicon(object):
143
+ """Phone based lexicon."""
144
+
145
+ def __init__(
146
+ self,
147
+ lang_dir: Path,
148
+ disambig_pattern: str = re.compile(r"^#\d+$"),
149
+ ):
150
+ """
151
+ Args:
152
+ lang_dir:
153
+ Path to the lang directory. It is expected to contain the following
154
+ files:
155
+ - tokens.txt
156
+ - words.txt
157
+ - L.pt
158
+ The above files are produced by the script `prepare.sh`. You
159
+ should have run that before running the training code.
160
+ disambig_pattern:
161
+ It contains the pattern for disambiguation symbols.
162
+ """
163
+ lang_dir = Path(lang_dir)
164
+
165
+ self.token_table = k2.SymbolTable.from_file(lang_dir / "tokens.txt")
166
+ self.word_table = k2.SymbolTable.from_file(lang_dir / "words.txt")
167
+
168
+ if (lang_dir / "Linv.pt").exists():
169
+ logging.info(f"Loading pre-compiled {lang_dir}/Linv.pt")
170
+ L_inv = k2.Fsa.from_dict(torch.load(lang_dir / "Linv.pt", weights_only=False))
171
+ else:
172
+ logging.info("Converting L.pt to Linv.pt")
173
+ L = k2.Fsa.from_dict(torch.load(lang_dir / "L.pt", weights_only=False))
174
+ L_inv = k2.arc_sort(L.invert())
175
+ torch.save(L_inv.as_dict(), lang_dir / "Linv.pt")
176
+
177
+ # We save L_inv instead of L because it will be used to intersect with
178
+ # transcript FSAs, both of whose labels are word IDs.
179
+ self.L_inv = L_inv
180
+ self.disambig_pattern = disambig_pattern
181
+
182
+ @property
183
+ def tokens(self) -> List[int]:
184
+ """Return a list of token IDs excluding those from
185
+ disambiguation symbols.
186
+
187
+ Caution:
188
+ 0 is not a token ID so it is excluded from the return value.
189
+ """
190
+ symbols = self.token_table.symbols
191
+ ans = []
192
+ for s in symbols:
193
+ if not self.disambig_pattern.match(s):
194
+ ans.append(self.token_table[s])
195
+ if 0 in ans:
196
+ ans.remove(0)
197
+ ans.sort()
198
+ return ans
199
+
200
+
201
+ class UniqLexicon(Lexicon):
202
+ def __init__(
203
+ self,
204
+ lang_dir: Path,
205
+ uniq_filename: str = "uniq_lexicon.txt",
206
+ disambig_pattern: str = re.compile(r"^#\d+$"),
207
+ ):
208
+ """
209
+ Refer to the help information in Lexicon.__init__.
210
+
211
+ uniq_filename: It is assumed to be inside the given `lang_dir`.
212
+
213
+ Each word in the lexicon is assumed to have a unique pronunciation.
214
+ """
215
+ lang_dir = Path(lang_dir)
216
+ super().__init__(lang_dir=lang_dir, disambig_pattern=disambig_pattern)
217
+
218
+ self.ragged_lexicon = convert_lexicon_to_ragged(
219
+ filename=lang_dir / uniq_filename,
220
+ word_table=self.word_table,
221
+ token_table=self.token_table,
222
+ )
223
+ # TODO: should we move it to a certain device ?
224
+
225
+ def texts_to_token_ids(
226
+ self, texts: List[str], oov: str = "<UNK>"
227
+ ) -> k2.RaggedTensor:
228
+ """
229
+ Args:
230
+ texts:
231
+ A list of transcripts. Each transcript contains space(s)
232
+ separated words. An example texts is::
233
+
234
+ ['HELLO k2', 'HELLO icefall']
235
+ oov:
236
+ The OOV word. If a word in `texts` is not in the lexicon, it is
237
+ replaced with `oov`.
238
+ Returns:
239
+ Return a ragged int tensor with 2 axes [utterance][token_id]
240
+ """
241
+ oov_id = self.word_table[oov]
242
+
243
+ word_ids_list = []
244
+ for text in texts:
245
+ word_ids = []
246
+ for word in text.split():
247
+ if word in self.word_table:
248
+ word_ids.append(self.word_table[word])
249
+ else:
250
+ word_ids.append(oov_id)
251
+ word_ids_list.append(word_ids)
252
+ ragged_indexes = k2.RaggedTensor(word_ids_list, dtype=torch.int32)
253
+ ans = self.ragged_lexicon.index(ragged_indexes)
254
+ ans = ans.remove_axis(ans.num_axes - 2)
255
+ return ans
256
+
257
+ def words_to_token_ids(self, words: List[str]) -> k2.RaggedTensor:
258
+ """Convert a list of words to a ragged tensor containing token IDs.
259
+
260
+ We assume there are no OOVs in "words".
261
+ """
262
+ word_ids = [self.word_table[w] for w in words]
263
+ word_ids = torch.tensor(word_ids, dtype=torch.int32)
264
+
265
+ ragged, _ = self.ragged_lexicon.index(
266
+ indexes=word_ids,
267
+ axis=0,
268
+ need_value_indexes=False,
269
+ )
270
+ return ragged
icefall/lm_wrapper.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 Xiaomi Corporation (authors: Xiaoyu Yang)
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
+ import argparse
18
+ import logging
19
+
20
+ import torch
21
+
22
+ from icefall.checkpoint import average_checkpoints, load_checkpoint
23
+ from icefall.rnn_lm.model import RnnLmModel
24
+ from icefall.transformer_lm.model import TransformerLM
25
+ from icefall.utils import AttributeDict, str2bool
26
+
27
+
28
+ class LmScorer(torch.nn.Module):
29
+ """This is a wrapper for NN LMs
30
+ The language models supported include:
31
+ RNN,
32
+ Transformer
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ lm_type: str,
38
+ params: AttributeDict,
39
+ device,
40
+ lm_scale: float = 0.3,
41
+ ):
42
+ super(LmScorer, self).__init__()
43
+ assert lm_type in ["rnn", "transformer"], f"{lm_type} is not supported"
44
+ self.lm_type = lm_type
45
+ self.lm = self.get_lm(lm_type, device, params)
46
+ self.lm_scale = lm_scale
47
+ self.params = params
48
+
49
+ @classmethod
50
+ def add_arguments(cls, parser):
51
+ # LM general arguments
52
+ parser.add_argument(
53
+ "--lm-vocab-size",
54
+ type=int,
55
+ default=500,
56
+ )
57
+
58
+ parser.add_argument(
59
+ "--lm-epoch",
60
+ type=int,
61
+ default=7,
62
+ help="""Which epoch to be used
63
+ """,
64
+ )
65
+
66
+ parser.add_argument(
67
+ "--lm-avg",
68
+ type=int,
69
+ default=1,
70
+ help="""Number of checkpoints to be averaged
71
+ """,
72
+ )
73
+
74
+ parser.add_argument("--lm-exp-dir", type=str, help="Path to LM experiments")
75
+
76
+ # Now RNNLM related arguments
77
+ parser.add_argument(
78
+ "--rnn-lm-embedding-dim",
79
+ type=int,
80
+ default=2048,
81
+ help="Embedding dim of the model",
82
+ )
83
+
84
+ parser.add_argument(
85
+ "--rnn-lm-hidden-dim",
86
+ type=int,
87
+ default=2048,
88
+ help="Hidden dim of the model",
89
+ )
90
+
91
+ parser.add_argument(
92
+ "--rnn-lm-num-layers",
93
+ type=int,
94
+ default=3,
95
+ help="Number of RNN layers the model",
96
+ )
97
+
98
+ parser.add_argument(
99
+ "--rnn-lm-tie-weights",
100
+ type=str2bool,
101
+ default=True,
102
+ help="""True to share the weights between the input embedding layer and the
103
+ last output linear layer
104
+ """,
105
+ )
106
+
107
+ # Now transformers
108
+ parser.add_argument(
109
+ "--transformer-lm-exp-dir", type=str, help="Directory of transformer LM exp"
110
+ )
111
+
112
+ parser.add_argument(
113
+ "--transformer-lm-dim-feedforward",
114
+ type=int,
115
+ default=2048,
116
+ help="Dimension of FFW module in transformer",
117
+ )
118
+
119
+ parser.add_argument(
120
+ "--transformer-lm-encoder-dim",
121
+ type=int,
122
+ default=768,
123
+ help="Encoder dimension of transformer",
124
+ )
125
+
126
+ parser.add_argument(
127
+ "--transformer-lm-embedding-dim",
128
+ type=int,
129
+ default=768,
130
+ help="Input embedding dimension of transformer",
131
+ )
132
+
133
+ parser.add_argument(
134
+ "--transformer-lm-nhead",
135
+ type=int,
136
+ default=8,
137
+ help="Number of attention heads in transformer",
138
+ )
139
+
140
+ parser.add_argument(
141
+ "--transformer-lm-num-layers",
142
+ type=int,
143
+ default=16,
144
+ help="Number of encoder layers in transformer",
145
+ )
146
+
147
+ parser.add_argument(
148
+ "--transformer-lm-tie-weights",
149
+ type=str2bool,
150
+ default=True,
151
+ help="If tie weights in transformer LM",
152
+ )
153
+
154
+ def get_lm(self, lm_type: str, device, params: AttributeDict) -> torch.nn.Module:
155
+ """Return the neural network LM
156
+
157
+ Args:
158
+ lm_type (str): Type name of NN LM
159
+ """
160
+ if lm_type == "rnn":
161
+ model = RnnLmModel(
162
+ vocab_size=params.lm_vocab_size,
163
+ embedding_dim=params.rnn_lm_embedding_dim,
164
+ hidden_dim=params.rnn_lm_hidden_dim,
165
+ num_layers=params.rnn_lm_num_layers,
166
+ tie_weights=params.rnn_lm_tie_weights,
167
+ )
168
+
169
+ if params.lm_avg == 1:
170
+ load_checkpoint(
171
+ f"{params.lm_exp_dir}/epoch-{params.lm_epoch}.pt", model
172
+ )
173
+ model.to(device)
174
+ else:
175
+ start = params.lm_epoch - params.lm_avg + 1
176
+ filenames = []
177
+ for i in range(start, params.lm_epoch + 1):
178
+ if start >= 0:
179
+ filenames.append(f"{params.lm_exp_dir}/epoch-{i}.pt")
180
+ logging.info(f"averaging {filenames}")
181
+ model.to(device)
182
+ model.load_state_dict(average_checkpoints(filenames, device=device))
183
+
184
+ elif lm_type == "transformer":
185
+ model = TransformerLM(
186
+ vocab_size=params.lm_vocab_size,
187
+ d_model=params.transformer_lm_encoder_dim,
188
+ embedding_dim=params.transformer_lm_embedding_dim,
189
+ dim_feedforward=params.transformer_lm_dim_feedforward,
190
+ nhead=params.transformer_lm_nhead,
191
+ num_layers=params.transformer_lm_num_layers,
192
+ tie_weights=params.transformer_lm_tie_weights,
193
+ params=params,
194
+ )
195
+
196
+ if params.lm_avg == 1:
197
+ load_checkpoint(
198
+ f"{params.lm_exp_dir}/epoch-{params.lm_epoch}.pt", model
199
+ )
200
+ model.to(device)
201
+ else:
202
+ start = params.lm_epoch - params.lm_avg + 1
203
+ filenames = []
204
+ for i in range(start, params.lm_epoch + 1):
205
+ if start >= 0:
206
+ filenames.append(f"{params.lm_exp_dir}/epoch-{i}.pt")
207
+ logging.info(f"averaging {filenames}")
208
+ model.to(device)
209
+ model.load_state_dict(average_checkpoints(filenames, device=device))
210
+ else:
211
+ raise NotImplementedError()
212
+
213
+ return model
214
+
215
+ def score_token(self, x: torch.Tensor, x_lens: torch.Tensor, state=None):
216
+ """Score the input and return the prediction
217
+ This requires the lm to have the method `score_token`
218
+ Args:
219
+ x (torch.Tensor): Input tokens
220
+ x_lens (torch.Tensor): Length of the input tokens
221
+ state (optional): LM states
222
+
223
+ """
224
+ return self.lm.score_token(x, x_lens, state)
225
+
226
+
227
+ if __name__ == "__main__":
228
+ parser = argparse.ArgumentParser()
229
+ LmScorer.add_arguments(parser)
230
+ args = parser.parse_args()
231
+
232
+ params = AttributeDict()
233
+ params.update(vars(args))
234
+
235
+ device = torch.device("cpu")
236
+ if torch.cuda.is_available():
237
+ device = torch.device("cuda", 0)
238
+
239
+ Scorer = LmScorer(params=params, device=device)
240
+ Scorer.eval()
241
+
242
+ x = (
243
+ torch.tensor([[1, 4, 19, 256, 77], [1, 4, 19, 256, 77]])
244
+ .to(device)
245
+ .to(torch.int64)
246
+ )
247
+ x_lens = torch.tensor([5, 5]).to(device)
248
+
249
+ state = None
250
+
251
+ score, state = Scorer.score(x, x_lens)
252
+ print(score.shape)
253
+ print(score[0])
254
+ print(score[1])
icefall/mmi.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ import k2
4
+ import torch
5
+ from torch import nn
6
+
7
+ from icefall.mmi_graph_compiler import MmiTrainingGraphCompiler
8
+
9
+
10
+ def _compute_mmi_loss_exact_optimized(
11
+ dense_fsa_vec: k2.DenseFsaVec,
12
+ texts: List[str],
13
+ graph_compiler: MmiTrainingGraphCompiler,
14
+ den_scale: float = 1.0,
15
+ beam_size: float = 8.0,
16
+ ) -> torch.Tensor:
17
+ """
18
+ The function name contains `exact`, which means it uses a version of
19
+ intersection without pruning.
20
+
21
+ `optimized` in the function name means this function is optimized
22
+ in that it calls k2.intersect_dense only once
23
+
24
+ Note:
25
+ It is faster at the cost of using more memory.
26
+
27
+ Args:
28
+ dense_fsa_vec:
29
+ It contains the neural network output.
30
+ texts:
31
+ The transcript. Each element consists of space(s) separated words.
32
+ graph_compiler:
33
+ Used to build num_graphs and den_graphs
34
+ den_scale:
35
+ The scale applied to the denominator tot_scores.
36
+ Returns:
37
+ Return a scalar loss. It is the sum over utterances in a batch,
38
+ without normalization.
39
+ """
40
+ num_graphs, den_graphs = graph_compiler.compile(texts, replicate_den=False)
41
+
42
+ device = num_graphs.device
43
+
44
+ num_fsas = num_graphs.shape[0]
45
+ assert dense_fsa_vec.dim0() == num_fsas
46
+
47
+ assert den_graphs.shape[0] == 1
48
+
49
+ # The motivation to concatenate num_graphs and den_graphs
50
+ # is to reduce the number of calls to k2.intersect_dense.
51
+ num_den_graphs = k2.cat([num_graphs, den_graphs])
52
+
53
+ # NOTE: The a_to_b_map in k2.intersect_dense must be sorted
54
+ # so the following reorders num_den_graphs.
55
+ #
56
+ # The following code computes a_to_b_map
57
+
58
+ # [0, 1, 2, ... ]
59
+ num_graphs_indexes = torch.arange(num_fsas, dtype=torch.int32)
60
+
61
+ # [num_fsas, num_fsas, num_fsas, ... ]
62
+ den_graphs_indexes = torch.tensor([num_fsas] * num_fsas, dtype=torch.int32)
63
+
64
+ # [0, num_fsas, 1, num_fsas, 2, num_fsas, ... ]
65
+ num_den_graphs_indexes = (
66
+ torch.stack([num_graphs_indexes, den_graphs_indexes]).t().reshape(-1).to(device)
67
+ )
68
+
69
+ num_den_reordered_graphs = k2.index(num_den_graphs, num_den_graphs_indexes)
70
+
71
+ # [[0, 1, 2, ...]]
72
+ a_to_b_map = torch.arange(num_fsas, dtype=torch.int32).reshape(1, -1)
73
+
74
+ # [[0, 1, 2, ...]] -> [0, 0, 1, 1, 2, 2, ... ]
75
+ a_to_b_map = a_to_b_map.repeat(2, 1).t().reshape(-1).to(device)
76
+
77
+ num_den_lats = k2.intersect_dense(
78
+ num_den_reordered_graphs,
79
+ dense_fsa_vec,
80
+ output_beam=beam_size,
81
+ a_to_b_map=a_to_b_map,
82
+ )
83
+
84
+ num_den_tot_scores = num_den_lats.get_tot_scores(
85
+ log_semiring=True, use_double_scores=True
86
+ )
87
+
88
+ num_tot_scores = num_den_tot_scores[::2]
89
+ den_tot_scores = num_den_tot_scores[1::2]
90
+
91
+ tot_scores = num_tot_scores - den_scale * den_tot_scores
92
+ loss = -1 * tot_scores.sum()
93
+ return loss
94
+
95
+
96
+ def _compute_mmi_loss_exact_non_optimized(
97
+ dense_fsa_vec: k2.DenseFsaVec,
98
+ texts: List[str],
99
+ graph_compiler: MmiTrainingGraphCompiler,
100
+ den_scale: float = 1.0,
101
+ beam_size: float = 8.0,
102
+ ) -> torch.Tensor:
103
+ """
104
+ See :func:`_compute_mmi_loss_exact_optimized` for the meaning
105
+ of the arguments.
106
+
107
+ It's more readable, though it invokes k2.intersect_dense twice.
108
+
109
+ Note:
110
+ It uses less memory at the cost of speed. It is slower.
111
+ """
112
+ num_graphs, den_graphs = graph_compiler.compile(texts, replicate_den=True)
113
+
114
+ # TODO: pass output_beam as function argument
115
+ num_lats = k2.intersect_dense(
116
+ num_graphs, dense_fsa_vec, output_beam=beam_size, max_arcs=2147483600
117
+ )
118
+ den_lats = k2.intersect_dense(
119
+ den_graphs, dense_fsa_vec, output_beam=beam_size, max_arcs=2147483600
120
+ )
121
+
122
+ num_tot_scores = num_lats.get_tot_scores(log_semiring=True, use_double_scores=True)
123
+
124
+ den_tot_scores = den_lats.get_tot_scores(log_semiring=True, use_double_scores=True)
125
+
126
+ tot_scores = num_tot_scores - den_scale * den_tot_scores
127
+ tot_scores = tot_scores.masked_fill(torch.isinf(tot_scores), 0.0)
128
+
129
+ loss = -1 * tot_scores.sum()
130
+ return loss
131
+
132
+
133
+ def _compute_mmi_loss_pruned(
134
+ dense_fsa_vec: k2.DenseFsaVec,
135
+ texts: List[str],
136
+ graph_compiler: MmiTrainingGraphCompiler,
137
+ den_scale: float = 1.0,
138
+ beam_size: float = 8.0,
139
+ ) -> torch.Tensor:
140
+ """
141
+ See :func:`_compute_mmi_loss_exact_optimized` for the meaning
142
+ of the arguments.
143
+
144
+ `pruned` means it uses k2.intersect_dense_pruned
145
+
146
+ Note:
147
+ It uses the least amount of memory, but the loss is not exact due
148
+ to pruning.
149
+ """
150
+ num_graphs, den_graphs = graph_compiler.compile(texts, replicate_den=False)
151
+
152
+ num_lats = k2.intersect_dense(num_graphs, dense_fsa_vec, output_beam=8.0)
153
+
154
+ # the values for search_beam/output_beam/min_active_states/max_active_states
155
+ # are not tuned. You may want to tune them.
156
+ den_lats = k2.intersect_dense_pruned(
157
+ den_graphs,
158
+ dense_fsa_vec,
159
+ search_beam=20.0,
160
+ output_beam=beam_size,
161
+ min_active_states=30,
162
+ max_active_states=10000,
163
+ )
164
+
165
+ num_tot_scores = num_lats.get_tot_scores(log_semiring=True, use_double_scores=True)
166
+
167
+ den_tot_scores = den_lats.get_tot_scores(log_semiring=True, use_double_scores=True)
168
+
169
+ tot_scores = num_tot_scores - den_scale * den_tot_scores
170
+
171
+ loss = -1 * tot_scores.sum()
172
+ return loss
173
+
174
+
175
+ class LFMMILoss(nn.Module):
176
+ """
177
+ Computes Lattice-Free Maximum Mutual Information (LFMMI) loss.
178
+
179
+ TODO: more detailed description
180
+ """
181
+
182
+ def __init__(
183
+ self,
184
+ graph_compiler: MmiTrainingGraphCompiler,
185
+ use_pruned_intersect: bool = False,
186
+ den_scale: float = 1.0,
187
+ beam_size: float = 8.0,
188
+ ):
189
+ super().__init__()
190
+ self.graph_compiler = graph_compiler
191
+ self.den_scale = den_scale
192
+ self.use_pruned_intersect = use_pruned_intersect
193
+ self.beam_size = beam_size
194
+
195
+ def forward(
196
+ self,
197
+ dense_fsa_vec: k2.DenseFsaVec,
198
+ texts: List[str],
199
+ ) -> torch.Tensor:
200
+ """
201
+ Args:
202
+ dense_fsa_vec:
203
+ It contains the neural network output.
204
+ texts:
205
+ A list of strings. Each string contains space(s) separated words.
206
+ Returns:
207
+ Return a scalar loss. It is the sum over utterances in a batch,
208
+ without normalization.
209
+ """
210
+ if self.use_pruned_intersect:
211
+ func = _compute_mmi_loss_pruned
212
+ else:
213
+ func = _compute_mmi_loss_exact_non_optimized
214
+ # func = _compute_mmi_loss_exact_optimized
215
+
216
+ return func(
217
+ dense_fsa_vec=dense_fsa_vec,
218
+ texts=texts,
219
+ graph_compiler=self.graph_compiler,
220
+ den_scale=self.den_scale,
221
+ beam_size=self.beam_size,
222
+ )
icefall/mmi_graph_compiler.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import Iterable, List, Tuple, Union
4
+
5
+ import k2
6
+ import torch
7
+
8
+ from icefall.lexicon import UniqLexicon
9
+
10
+
11
+ class MmiTrainingGraphCompiler(object):
12
+ def __init__(
13
+ self,
14
+ lang_dir: Path,
15
+ uniq_filename: str = "uniq_lexicon.txt",
16
+ device: Union[str, torch.device] = "cpu",
17
+ oov: str = "<UNK>",
18
+ sos_id: int = 1,
19
+ eos_id: int = 1,
20
+ ):
21
+ """
22
+ Args:
23
+ lang_dir:
24
+ Path to the lang directory. It is expected to contain the
25
+ following files::
26
+
27
+ - tokens.txt
28
+ - words.txt
29
+ - P.fst.txt
30
+
31
+ The above files are generated by the script `prepare.sh`. You
32
+ should have run it before running the training code.
33
+ uniq_filename:
34
+ File name to the lexicon in which every word has exactly one
35
+ pronunciation. We assume this file is inside the given `lang_dir`.
36
+
37
+ device:
38
+ It indicates CPU or CUDA.
39
+ oov:
40
+ Out of vocabulary word. When a word in the transcript
41
+ does not exist in the lexicon, it is replaced with `oov`.
42
+ """
43
+ self.lang_dir = Path(lang_dir)
44
+ self.lexicon = UniqLexicon(lang_dir, uniq_filename=uniq_filename)
45
+ self.device = torch.device(device)
46
+
47
+ self.L_inv = self.lexicon.L_inv.to(self.device)
48
+
49
+ self.oov_id = self.lexicon.word_table[oov]
50
+ self.sos_id = sos_id
51
+ self.eos_id = eos_id
52
+
53
+ self.build_ctc_topo_P()
54
+
55
+ def build_ctc_topo_P(self):
56
+ """Built ctc_topo_P, the composition result of
57
+ ctc_topo and P, where P is a pre-trained bigram
58
+ word piece LM.
59
+ """
60
+ # Note: there is no need to save a pre-compiled P and ctc_topo
61
+ # as it is very fast to generate them.
62
+ logging.info(f"Loading P from {self.lang_dir/'P.fst.txt'}")
63
+ with open(self.lang_dir / "P.fst.txt") as f:
64
+ # P is not an acceptor because there is
65
+ # a back-off state, whose incoming arcs
66
+ # have label #0 and aux_label 0 (i.e., <eps>).
67
+ P = k2.Fsa.from_openfst(f.read(), acceptor=False)
68
+
69
+ first_token_disambig_id = self.lexicon.token_table["#0"]
70
+
71
+ # P.aux_labels is not needed in later computations, so
72
+ # remove it here.
73
+ del P.aux_labels
74
+ # CAUTION: The following line is crucial.
75
+ # Arcs entering the back-off state have label equal to #0.
76
+ # We have to change it to 0 here.
77
+ labels = P.labels.clone()
78
+ labels[labels >= first_token_disambig_id] = 0
79
+ P.labels = labels
80
+
81
+ P = k2.remove_epsilon(P)
82
+ P = k2.arc_sort(P)
83
+ P = P.to(self.device)
84
+ # Add epsilon self-loops to P because we want the
85
+ # following operation "k2.intersect" to run on GPU.
86
+ P_with_self_loops = k2.add_epsilon_self_loops(P)
87
+
88
+ max_token_id = max(self.lexicon.tokens)
89
+ logging.info(
90
+ f"Building ctc_topo (modified=False). max_token_id: {max_token_id}"
91
+ )
92
+ ctc_topo = k2.ctc_topo(max_token_id, modified=False, device=self.device)
93
+
94
+ ctc_topo_inv = k2.arc_sort(ctc_topo.invert_())
95
+
96
+ logging.info("Building ctc_topo_P")
97
+ ctc_topo_P = k2.intersect(
98
+ ctc_topo_inv, P_with_self_loops, treat_epsilons_specially=False
99
+ ).invert()
100
+
101
+ self.ctc_topo_P = k2.arc_sort(ctc_topo_P)
102
+ logging.info(f"ctc_topo_P num_arcs: {self.ctc_topo_P.num_arcs}")
103
+
104
+ def compile(
105
+ self, texts: Iterable[str], replicate_den: bool = True
106
+ ) -> Tuple[k2.Fsa, k2.Fsa]:
107
+ """Create numerator and denominator graphs from transcripts
108
+ and the bigram phone LM.
109
+
110
+ Args:
111
+ texts:
112
+ A list of transcripts. Within a transcript, words are
113
+ separated by spaces. An example `texts` is given below::
114
+
115
+ ["Hello icefall", "LF-MMI training with icefall using k2"]
116
+
117
+ replicate_den:
118
+ If True, the returned den_graph is replicated to match the number
119
+ of FSAs in the returned num_graph; if False, the returned den_graph
120
+ contains only a single FSA
121
+ Returns:
122
+ A tuple (num_graph, den_graph), where
123
+
124
+ - `num_graph` is the numerator graph. It is an FsaVec with
125
+ shape `(len(texts), None, None)`.
126
+
127
+ - `den_graph` is the denominator graph. It is an FsaVec
128
+ with the same shape of the `num_graph` if replicate_den is
129
+ True; otherwise, it is an FsaVec containing only a single FSA.
130
+ """
131
+ transcript_fsa = self.build_transcript_fsa(texts)
132
+
133
+ # remove word IDs from transcript_fsa since it is not needed
134
+ del transcript_fsa.aux_labels
135
+ # NOTE: You can comment out the above statement
136
+ # if you want to run test/test_mmi_graph_compiler.py
137
+
138
+ transcript_fsa_with_self_loops = k2.remove_epsilon_and_add_self_loops(
139
+ transcript_fsa
140
+ )
141
+
142
+ transcript_fsa_with_self_loops = k2.arc_sort(transcript_fsa_with_self_loops)
143
+
144
+ num = k2.compose(
145
+ self.ctc_topo_P,
146
+ transcript_fsa_with_self_loops,
147
+ treat_epsilons_specially=False,
148
+ )
149
+
150
+ # CAUTION: Due to the presence of P,
151
+ # the resulting `num` may not be connected
152
+ num = k2.connect(num)
153
+
154
+ num = k2.arc_sort(num)
155
+
156
+ ctc_topo_P_vec = k2.create_fsa_vec([self.ctc_topo_P])
157
+ if replicate_den:
158
+ indexes = torch.zeros(len(texts), dtype=torch.int32, device=self.device)
159
+ den = k2.index_fsa(ctc_topo_P_vec, indexes)
160
+ else:
161
+ den = ctc_topo_P_vec
162
+
163
+ return num, den
164
+
165
+ def build_transcript_fsa(self, texts: List[str]) -> k2.Fsa:
166
+ """Convert transcripts to an FsaVec with the help of a lexicon
167
+ and word symbol table.
168
+
169
+ Args:
170
+ texts:
171
+ Each element is a transcript containing words separated by space(s).
172
+ For instance, it may be 'HELLO icefall', which contains
173
+ two words.
174
+
175
+ Returns:
176
+ Return an FST (FsaVec) corresponding to the transcript.
177
+ Its `labels` is token IDs and `aux_labels` is word IDs.
178
+ """
179
+ word_ids_list = []
180
+ for text in texts:
181
+ word_ids = []
182
+ for word in text.split():
183
+ if word in self.lexicon.word_table:
184
+ word_ids.append(self.lexicon.word_table[word])
185
+ else:
186
+ word_ids.append(self.oov_id)
187
+ word_ids_list.append(word_ids)
188
+
189
+ fsa = k2.linear_fsa(word_ids_list, self.device)
190
+ fsa = k2.add_epsilon_self_loops(fsa)
191
+
192
+ # The reason to use `invert_()` at the end is as follows:
193
+ #
194
+ # (1) The `labels` of L_inv is word IDs and `aux_labels` is token IDs
195
+ # (2) `fsa.labels` is word IDs
196
+ # (3) after intersection, the `labels` is still word IDs
197
+ # (4) after `invert_()`, the `labels` is token IDs
198
+ # and `aux_labels` is word IDs
199
+ transcript_fsa = k2.intersect(
200
+ self.L_inv, fsa, treat_epsilons_specially=False
201
+ ).invert_()
202
+ transcript_fsa = k2.arc_sort(transcript_fsa)
203
+ return transcript_fsa
204
+
205
+ def texts_to_ids(self, texts: List[str]) -> List[List[int]]:
206
+ """Convert a list of texts to a list-of-list of piece IDs.
207
+
208
+ Args:
209
+ texts:
210
+ It is a list of strings. Each string consists of space(s)
211
+ separated words. An example containing two strings is given below:
212
+
213
+ ['HELLO ICEFALL', 'HELLO k2']
214
+ We assume it contains no OOVs. Otherwise, it will raise an
215
+ exception.
216
+ Returns:
217
+ Return a list-of-list of token IDs.
218
+ """
219
+ return self.lexicon.texts_to_token_ids(texts).tolist()
icefall/ngram_lm.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 collections import defaultdict
18
+ from typing import List, Optional, Tuple
19
+
20
+ from icefall.utils import is_module_available
21
+
22
+
23
+ class NgramLm:
24
+ def __init__(
25
+ self,
26
+ fst_filename: str,
27
+ backoff_id: int,
28
+ is_binary: bool = False,
29
+ ):
30
+ """
31
+ Args:
32
+ fst_filename:
33
+ Path to the FST.
34
+ backoff_id:
35
+ ID of the backoff symbol.
36
+ is_binary:
37
+ True if the given file is a binary FST.
38
+ """
39
+ if not is_module_available("kaldifst"):
40
+ raise ValueError("Please 'pip install kaldifst' first.")
41
+
42
+ import kaldifst
43
+
44
+ if is_binary:
45
+ lm = kaldifst.StdVectorFst.read(fst_filename)
46
+ else:
47
+ with open(fst_filename, "r") as f:
48
+ lm = kaldifst.compile(f.read(), acceptor=False)
49
+
50
+ if not lm.is_ilabel_sorted:
51
+ kaldifst.arcsort(lm, sort_type="ilabel")
52
+
53
+ self.lm = lm
54
+ self.backoff_id = backoff_id
55
+
56
+ def _process_backoff_arcs(
57
+ self,
58
+ state: int,
59
+ cost: float,
60
+ ) -> List[Tuple[int, float]]:
61
+ """Similar to ProcessNonemitting() from Kaldi, this function
62
+ returns the list of states reachable from the given state via
63
+ backoff arcs.
64
+
65
+ Args:
66
+ state:
67
+ The input state.
68
+ cost:
69
+ The cost of reaching the given state from the start state.
70
+ Returns:
71
+ Return a list, where each element contains a tuple with two entries:
72
+ - next_state
73
+ - cost of next_state
74
+ If there is no backoff arc leaving the input state, then return
75
+ an empty list.
76
+ """
77
+ ans = []
78
+
79
+ next_state, next_cost = self._get_next_state_and_cost_without_backoff(
80
+ state=state,
81
+ label=self.backoff_id,
82
+ )
83
+ if next_state is None:
84
+ return ans
85
+ ans.append((next_state, next_cost + cost))
86
+ ans += self._process_backoff_arcs(next_state, next_cost + cost)
87
+ return ans
88
+
89
+ def _get_next_state_and_cost_without_backoff(
90
+ self, state: int, label: int
91
+ ) -> Tuple[int, float]:
92
+ """TODO: Add doc."""
93
+ import kaldifst
94
+
95
+ arc_iter = kaldifst.ArcIterator(self.lm, state)
96
+ num_arcs = self.lm.num_arcs(state)
97
+
98
+ # The LM is arc sorted by ilabel, so we use binary search below.
99
+ left = 0
100
+ right = num_arcs - 1
101
+ while left <= right:
102
+ mid = (left + right) // 2
103
+ arc_iter.seek(mid)
104
+ arc = arc_iter.value
105
+ if arc.ilabel < label:
106
+ left = mid + 1
107
+ elif arc.ilabel > label:
108
+ right = mid - 1
109
+ else:
110
+ return arc.nextstate, arc.weight.value
111
+
112
+ return None, None
113
+
114
+ def get_next_state_and_cost(
115
+ self,
116
+ state: int,
117
+ label: int,
118
+ ) -> Tuple[List[int], List[float]]:
119
+ states = [state]
120
+ costs = [0]
121
+
122
+ extra_states_costs = self._process_backoff_arcs(
123
+ state=state,
124
+ cost=0,
125
+ )
126
+
127
+ for s, c in extra_states_costs:
128
+ states.append(s)
129
+ costs.append(c)
130
+
131
+ next_states = []
132
+ next_costs = []
133
+ for s, c in zip(states, costs):
134
+ ns, nc = self._get_next_state_and_cost_without_backoff(s, label)
135
+ if ns:
136
+ next_states.append(ns)
137
+ next_costs.append(c + nc)
138
+
139
+ return next_states, next_costs
140
+
141
+
142
+ class NgramLmStateCost:
143
+ def __init__(self, ngram_lm: NgramLm, state_cost: Optional[dict] = None):
144
+ assert ngram_lm.lm.start == 0, ngram_lm.lm.start
145
+ self.ngram_lm = ngram_lm
146
+ if state_cost is not None:
147
+ self.state_cost = state_cost
148
+ else:
149
+ self.state_cost = defaultdict(lambda: float("inf"))
150
+
151
+ # At the very beginning, we are at the start state with cost 0
152
+ self.state_cost[0] = 0.0
153
+
154
+ def forward_one_step(self, label: int) -> "NgramLmStateCost":
155
+ state_cost = defaultdict(lambda: float("inf"))
156
+ for s, c in self.state_cost.items():
157
+ next_states, next_costs = self.ngram_lm.get_next_state_and_cost(
158
+ s,
159
+ label,
160
+ )
161
+ for ns, nc in zip(next_states, next_costs):
162
+ state_cost[ns] = min(state_cost[ns], c + nc)
163
+
164
+ return NgramLmStateCost(ngram_lm=self.ngram_lm, state_cost=state_cost)
165
+
166
+ @property
167
+ def lm_score(self) -> float:
168
+ if len(self.state_cost) == 0:
169
+ return float("-inf")
170
+
171
+ return -1 * min(self.state_cost.values())
icefall/otc_graph_compiler.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
2
+ # 2023 Johns Hopkins University (author: Dongji Gao)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ from pathlib import Path
20
+ from typing import List, Union
21
+
22
+ import k2
23
+ import sentencepiece as spm
24
+ import torch
25
+
26
+ from icefall.utils import str2bool
27
+
28
+
29
+ class OtcTrainingGraphCompiler(object):
30
+ def __init__(
31
+ self,
32
+ lang_dir: Path,
33
+ otc_token: str,
34
+ device: Union[str, torch.device] = "cpu",
35
+ sos_token: str = "<sos/eos>",
36
+ eos_token: str = "<sos/eos>",
37
+ initial_bypass_weight: float = 0.0,
38
+ initial_self_loop_weight: float = 0.0,
39
+ bypass_weight_decay: float = 0.0,
40
+ self_loop_weight_decay: float = 0.0,
41
+ ) -> None:
42
+ """
43
+ Args:
44
+ lang_dir:
45
+ This directory is expected to contain the following files:
46
+
47
+ - bpe.model
48
+ - words.txt
49
+ otc_token:
50
+ The special token in OTC that represent all non-blank tokens
51
+ device:
52
+ It indicates CPU or CUDA.
53
+ sos_token:
54
+ The word piece that represents sos.
55
+ eos_token:
56
+ The word piece that represents eos.
57
+ """
58
+ lang_dir = Path(lang_dir)
59
+ bpe_model_file = lang_dir / "bpe.model"
60
+ sp = spm.SentencePieceProcessor()
61
+ sp.load(str(bpe_model_file))
62
+ self.sp = sp
63
+ self.token_table = k2.SymbolTable.from_file(lang_dir / "tokens.txt")
64
+
65
+ self.otc_token = otc_token
66
+ assert self.otc_token in self.token_table
67
+
68
+ self.device = device
69
+
70
+ self.sos_id = self.sp.piece_to_id(sos_token)
71
+ self.eos_id = self.sp.piece_to_id(eos_token)
72
+
73
+ assert self.sos_id != self.sp.unk_id()
74
+ assert self.eos_id != self.sp.unk_id()
75
+
76
+ max_token_id = self.get_max_token_id()
77
+ ctc_topo = k2.ctc_topo(max_token_id, modified=False)
78
+ self.ctc_topo = ctc_topo.to(self.device)
79
+
80
+ self.initial_bypass_weight = initial_bypass_weight
81
+ self.initial_self_loop_weight = initial_self_loop_weight
82
+ self.bypass_weight_decay = bypass_weight_decay
83
+ self.self_loop_weight_decay = self_loop_weight_decay
84
+
85
+ def get_max_token_id(self):
86
+ max_token_id = 0
87
+ for symbol in self.token_table.symbols:
88
+ if not symbol.startswith("#"):
89
+ max_token_id = max(self.token_table[symbol], max_token_id)
90
+ assert max_token_id > 0
91
+
92
+ return max_token_id
93
+
94
+ def make_arc(
95
+ self,
96
+ from_state: int,
97
+ to_state: int,
98
+ symbol: Union[str, int],
99
+ weight: float,
100
+ ):
101
+ return f"{from_state} {to_state} {symbol} {weight}"
102
+
103
+ def texts_to_ids(self, texts: List[str]) -> List[List[int]]:
104
+ """Convert a list of texts to a list-of-list of piece IDs.
105
+
106
+ Args:
107
+ texts:
108
+ It is a list of strings. Each string consists of space(s)
109
+ separated words. An example containing two strings is given below:
110
+
111
+ ['HELLO ICEFALL', 'HELLO k2']
112
+ Returns:
113
+ Return a list-of-list of piece IDs.
114
+ """
115
+ return self.sp.encode(texts, out_type=int)
116
+
117
+ def compile(
118
+ self,
119
+ texts: List[str],
120
+ allow_bypass_arc: str2bool = True,
121
+ allow_self_loop_arc: str2bool = True,
122
+ bypass_weight: float = 0.0,
123
+ self_loop_weight: float = 0.0,
124
+ ) -> k2.Fsa:
125
+ """Build a OTC graph from a texts (list of words).
126
+
127
+ Args:
128
+ texts:
129
+ A list of strings. Each string contains a sentence for an utterance.
130
+ A sentence consists of spaces separated words. An example `texts`
131
+ looks like:
132
+ ['hello icefall', 'CTC training with k2']
133
+ allow_bypass_arc:
134
+ Whether to add bypass arc to training graph for substitution
135
+ and insertion errors (wrong or extra words in the transcript).
136
+ allow_self_loop_arc:
137
+ Whether to add self-loop arc to training graph for deletion
138
+ errors (missing words in the transcript).
139
+ bypass_weight:
140
+ Weight associated with bypass arc.
141
+ self_loop_weight:
142
+ Weight associated with self-loop arc.
143
+
144
+ Return:
145
+ Return an FsaVec, which is the result of composing a
146
+ CTC topology with OTC FSAs constructed from the given texts.
147
+ """
148
+
149
+ transcript_fsa = self.convert_transcript_to_fsa(
150
+ texts,
151
+ self.otc_token,
152
+ allow_bypass_arc,
153
+ allow_self_loop_arc,
154
+ bypass_weight,
155
+ self_loop_weight,
156
+ )
157
+ transcript_fsa = transcript_fsa.to(self.device)
158
+ fsa_with_self_loop = k2.remove_epsilon_and_add_self_loops(transcript_fsa)
159
+ fsa_with_self_loop = k2.arc_sort(fsa_with_self_loop)
160
+
161
+ graph = k2.compose(
162
+ self.ctc_topo,
163
+ fsa_with_self_loop,
164
+ treat_epsilons_specially=False,
165
+ )
166
+ assert graph.requires_grad is False
167
+
168
+ return graph
169
+
170
+ def convert_transcript_to_fsa(
171
+ self,
172
+ texts: List[str],
173
+ otc_token: str,
174
+ allow_bypass_arc: str2bool = True,
175
+ allow_self_loop_arc: str2bool = True,
176
+ bypass_weight: float = 0.0,
177
+ self_loop_weight: float = 0.0,
178
+ ):
179
+ otc_token_id = self.token_table[otc_token]
180
+
181
+ transcript_fsa_list = []
182
+ for text in texts:
183
+ text_piece_ids = []
184
+
185
+ for word in text.split():
186
+ piece_ids = self.sp.encode(word, out_type=int)
187
+ text_piece_ids.append(piece_ids)
188
+
189
+ arcs = []
190
+ start_state = 0
191
+ cur_state = start_state
192
+ next_state = 1
193
+
194
+ for piece_ids in text_piece_ids:
195
+ bypass_cur_state = cur_state
196
+
197
+ if allow_self_loop_arc:
198
+ self_loop_arc = self.make_arc(
199
+ cur_state,
200
+ cur_state,
201
+ otc_token_id,
202
+ self_loop_weight,
203
+ )
204
+ arcs.append(self_loop_arc)
205
+
206
+ for piece_id in piece_ids:
207
+ arc = self.make_arc(cur_state, next_state, piece_id, 0.0)
208
+ arcs.append(arc)
209
+
210
+ cur_state = next_state
211
+ next_state += 1
212
+
213
+ bypass_next_state = cur_state
214
+ if allow_bypass_arc:
215
+ bypass_arc = self.make_arc(
216
+ bypass_cur_state,
217
+ bypass_next_state,
218
+ otc_token_id,
219
+ bypass_weight,
220
+ )
221
+ arcs.append(bypass_arc)
222
+ bypass_cur_state = cur_state
223
+
224
+ if allow_self_loop_arc:
225
+ self_loop_arc = self.make_arc(
226
+ cur_state,
227
+ cur_state,
228
+ otc_token_id,
229
+ self_loop_weight,
230
+ )
231
+ arcs.append(self_loop_arc)
232
+
233
+ # Deal with final state
234
+ final_state = next_state
235
+ final_arc = self.make_arc(cur_state, final_state, -1, 0.0)
236
+ arcs.append(final_arc)
237
+ arcs.append(f"{final_state}")
238
+ sorted_arcs = sorted(arcs, key=lambda a: int(a.split()[0]))
239
+
240
+ transcript_fsa = k2.Fsa.from_str("\n".join(sorted_arcs))
241
+ transcript_fsa = k2.arc_sort(transcript_fsa)
242
+ transcript_fsa_list.append(transcript_fsa)
243
+
244
+ transcript_fsa_vec = k2.create_fsa_vec(transcript_fsa_list)
245
+
246
+ return transcript_fsa_vec
icefall/otc_phone_graph_compiler.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
2
+ # 2023 Johns Hopkins University (author: Dongji Gao)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+
19
+ from pathlib import Path
20
+ from typing import List, Union
21
+
22
+ import k2
23
+ import torch
24
+
25
+ from icefall.lexicon import Lexicon
26
+ from icefall.utils import str2bool
27
+
28
+
29
+ class OtcPhoneTrainingGraphCompiler(object):
30
+ def __init__(
31
+ self,
32
+ lexicon: Lexicon,
33
+ otc_token: str,
34
+ oov: str = "<UNK>",
35
+ device: Union[str, torch.device] = "cpu",
36
+ initial_bypass_weight: float = 0.0,
37
+ initial_self_loop_weight: float = 0.0,
38
+ bypass_weight_decay: float = 0.0,
39
+ self_loop_weight_decay: float = 0.0,
40
+ ) -> None:
41
+ """
42
+ Args:
43
+ lexicon:
44
+ It is built from `data/lang/lexicon.txt`.
45
+ otc_token:
46
+ The special token in OTC that represent all non-blank tokens
47
+ device:
48
+ It indicates CPU or CUDA.
49
+ """
50
+ self.device = device
51
+ L_inv = lexicon.L_inv.to(self.device)
52
+ assert L_inv.requires_grad is False
53
+ assert oov in lexicon.word_table
54
+
55
+ self.L_inv = k2.arc_sort(L_inv)
56
+ self.oov_id = lexicon.word_table[oov]
57
+ self.otc_id = lexicon.word_table[otc_token]
58
+ self.word_table = lexicon.word_table
59
+
60
+ max_token_id = max(lexicon.tokens)
61
+ ctc_topo = k2.ctc_topo(max_token_id, modified=False)
62
+ self.ctc_topo = ctc_topo.to(self.device)
63
+ self.max_token_id = max_token_id
64
+
65
+ self.initial_bypass_weight = initial_bypass_weight
66
+ self.initial_self_loop_weight = initial_self_loop_weight
67
+ self.bypass_weight_decay = bypass_weight_decay
68
+ self.self_loop_weight_decay = self_loop_weight_decay
69
+
70
+ def get_max_token_id(self):
71
+ return self.max_token_id
72
+
73
+ def make_arc(
74
+ self,
75
+ from_state: int,
76
+ to_state: int,
77
+ symbol: Union[str, int],
78
+ weight: float,
79
+ ):
80
+ return f"{from_state} {to_state} {symbol} {weight}"
81
+
82
+ def texts_to_ids(self, texts: List[str]) -> List[List[int]]:
83
+ """Convert a list of texts to a list-of-list of word IDs.
84
+
85
+ Args:
86
+ texts:
87
+ It is a list of strings. Each string consists of space(s)
88
+ separated words. An example containing two strings is given below:
89
+
90
+ ['HELLO ICEFALL', 'HELLO k2']
91
+ Returns:
92
+ Return a list-of-list of word IDs.
93
+ """
94
+ word_ids_list = []
95
+ for text in texts:
96
+ word_ids = []
97
+ for word in text.split():
98
+ if word in self.word_table:
99
+ word_ids.append(self.word_table[word])
100
+ else:
101
+ word_ids.append(self.oov_id)
102
+ word_ids_list.append(word_ids)
103
+ return word_ids_list
104
+
105
+ def compile(
106
+ self,
107
+ texts: List[str],
108
+ allow_bypass_arc: str2bool = True,
109
+ allow_self_loop_arc: str2bool = True,
110
+ bypass_weight: float = 0.0,
111
+ self_loop_weight: float = 0.0,
112
+ ) -> k2.Fsa:
113
+ """Build a OTC graph from a texts (list of words).
114
+
115
+ Args:
116
+ texts:
117
+ A list of strings. Each string contains a sentence for an utterance.
118
+ A sentence consists of spaces separated words. An example `texts`
119
+ looks like:
120
+ ['hello icefall', 'CTC training with k2']
121
+ allow_bypass_arc:
122
+ Whether to add bypass arc to training graph for substitution
123
+ and insertion errors (wrong or extra words in the transcript).
124
+ allow_self_loop_arc:
125
+ Whether to add self-loop arc to training graph for deletion
126
+ errors (missing words in the transcript).
127
+ bypass_weight:
128
+ Weight associated with bypass arc.
129
+ self_loop_weight:
130
+ Weight associated with self-loop arc.
131
+
132
+ Return:
133
+ Return an FsaVec, which is the result of composing a
134
+ CTC topology with OTC FSAs constructed from the given texts.
135
+ """
136
+
137
+ transcript_fsa = self.convert_transcript_to_fsa(
138
+ texts,
139
+ allow_bypass_arc,
140
+ allow_self_loop_arc,
141
+ bypass_weight,
142
+ self_loop_weight,
143
+ )
144
+ fsa_with_self_loop = k2.remove_epsilon_and_add_self_loops(transcript_fsa)
145
+ fsa_with_self_loop = k2.arc_sort(fsa_with_self_loop)
146
+
147
+ graph = k2.compose(
148
+ self.ctc_topo,
149
+ fsa_with_self_loop,
150
+ treat_epsilons_specially=False,
151
+ )
152
+ assert graph.requires_grad is False
153
+
154
+ return graph
155
+
156
+ def convert_transcript_to_fsa(
157
+ self,
158
+ texts: List[str],
159
+ allow_bypass_arc: str2bool = True,
160
+ allow_self_loop_arc: str2bool = True,
161
+ bypass_weight: float = 0.0,
162
+ self_loop_weight: float = 0.0,
163
+ ):
164
+
165
+ word_fsa_list = []
166
+ for text in texts:
167
+ word_ids = []
168
+
169
+ for word in text.split():
170
+ if word in self.word_table:
171
+ word_ids.append(self.word_table[word])
172
+ else:
173
+ word_ids.append(self.oov_id)
174
+
175
+ arcs = []
176
+ start_state = 0
177
+ cur_state = start_state
178
+ next_state = 1
179
+
180
+ for word_id in word_ids:
181
+ if allow_self_loop_arc:
182
+ self_loop_arc = self.make_arc(
183
+ cur_state,
184
+ cur_state,
185
+ self.otc_id,
186
+ self_loop_weight,
187
+ )
188
+ arcs.append(self_loop_arc)
189
+
190
+ arc = self.make_arc(cur_state, next_state, word_id, 0.0)
191
+ arcs.append(arc)
192
+
193
+ if allow_bypass_arc:
194
+ bypass_arc = self.make_arc(
195
+ cur_state,
196
+ next_state,
197
+ self.otc_id,
198
+ bypass_weight,
199
+ )
200
+ arcs.append(bypass_arc)
201
+
202
+ cur_state = next_state
203
+ next_state += 1
204
+
205
+ if allow_self_loop_arc:
206
+ self_loop_arc = self.make_arc(
207
+ cur_state,
208
+ cur_state,
209
+ self.otc_id,
210
+ self_loop_weight,
211
+ )
212
+ arcs.append(self_loop_arc)
213
+
214
+ # Deal with final state
215
+ final_state = next_state
216
+ final_arc = self.make_arc(cur_state, final_state, -1, 0.0)
217
+ arcs.append(final_arc)
218
+ arcs.append(f"{final_state}")
219
+ sorted_arcs = sorted(arcs, key=lambda a: int(a.split()[0]))
220
+
221
+ word_fsa = k2.Fsa.from_str("\n".join(sorted_arcs))
222
+ word_fsa = k2.arc_sort(word_fsa)
223
+ word_fsa_list.append(word_fsa)
224
+
225
+ word_fsa_vec = k2.create_fsa_vec(word_fsa_list).to(self.device)
226
+ word_fsa_vec_with_self_loop = k2.add_epsilon_self_loops(word_fsa_vec)
227
+
228
+ fsa = k2.intersect(
229
+ self.L_inv, word_fsa_vec_with_self_loop, treat_epsilons_specially=False
230
+ )
231
+ ans_fsa = fsa.invert_()
232
+ return k2.arc_sort(ans_fsa)
icefall/profiler.py ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ # This is modified from https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/profiling/flops_profiler/profiler.py
7
+
8
+ from collections import OrderedDict
9
+ from functools import partial
10
+ from typing import List, Optional
11
+
12
+ import k2
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+
18
+ Tensor = torch.Tensor
19
+
20
+ module_flop_count = []
21
+ old_functions = {}
22
+
23
+
24
+ class FlopsProfiler(object):
25
+ """Measures the latency, number of estimated floating-point operations and parameters of each module in a PyTorch model.
26
+
27
+ The flops-profiler profiles the forward pass of a PyTorch model and prints the model graph with the measured profile attached to each module. It shows how latency, flops and parameters are spent in the model and which modules or layers could be the bottleneck. It also outputs the names of the top k modules in terms of aggregated latency, flops, and parameters at depth l with k and l specified by the user. The output profile is computed for each batch of input.
28
+
29
+ To profile a trained model in inference, use the `get_model_profile` API.
30
+
31
+ Args:
32
+ object (torch.nn.Module): The PyTorch model to profile.
33
+ """
34
+
35
+ def __init__(self, model, module_hoop_mapping=None):
36
+ self.model = model
37
+ self.started = False
38
+ self.func_patched = False
39
+ self.module_hoop_mapping = (
40
+ module_hoop_mapping
41
+ if module_hoop_mapping is not None
42
+ else MODULE_HOOK_MAPPING
43
+ )
44
+
45
+ def start_profile(self, ignore_list=None):
46
+ """Starts profiling.
47
+
48
+ Extra attributes are added recursively to all the modules and the profiled torch.nn.functionals are monkey patched.
49
+
50
+ Args:
51
+ ignore_list (list, optional): the list of modules to ignore while profiling. Defaults to None.
52
+ """
53
+ self.reset_profile()
54
+ _patch_functionals()
55
+ _patch_tensor_methods()
56
+
57
+ def register_module_hooks(module, ignore_list):
58
+ if ignore_list and type(module) in ignore_list:
59
+ return
60
+
61
+ # if computing the flops of a module directly
62
+ if type(module) in self.module_hoop_mapping:
63
+ if not hasattr(module, "__flops_handle__"):
64
+ module.__flops_handle__ = module.register_forward_hook(
65
+ self.module_hoop_mapping[type(module)]
66
+ )
67
+ return
68
+
69
+ # if computing the flops of the functionals in a module
70
+ def pre_hook(module, input):
71
+ module_flop_count.append([])
72
+
73
+ if not hasattr(module, "__pre_hook_handle__"):
74
+ module.__pre_hook_handle__ = module.register_forward_pre_hook(pre_hook)
75
+
76
+ def post_hook(module, input, output):
77
+ if module_flop_count:
78
+ module.__flops__ += sum([elem[1] for elem in module_flop_count[-1]])
79
+ module_flop_count.pop()
80
+
81
+ if not hasattr(module, "__post_hook_handle__"):
82
+ module.__post_hook_handle__ = module.register_forward_hook(post_hook)
83
+
84
+ self.model.apply(partial(register_module_hooks, ignore_list=ignore_list))
85
+ self.started = True
86
+ self.func_patched = True
87
+
88
+ def stop_profile(self):
89
+ """Stop profiling.
90
+
91
+ All torch.nn.functionals are restored to their originals.
92
+ """
93
+ if self.started and self.func_patched:
94
+ _reload_functionals()
95
+ _reload_tensor_methods()
96
+ self.func_patched = False
97
+
98
+ def remove_profile_attrs(module):
99
+ if hasattr(module, "__pre_hook_handle__"):
100
+ module.__pre_hook_handle__.remove()
101
+ del module.__pre_hook_handle__
102
+ if hasattr(module, "__post_hook_handle__"):
103
+ module.__post_hook_handle__.remove()
104
+ del module.__post_hook_handle__
105
+ if hasattr(module, "__flops_handle__"):
106
+ module.__flops_handle__.remove()
107
+ del module.__flops_handle__
108
+
109
+ self.model.apply(remove_profile_attrs)
110
+
111
+ def reset_profile(self):
112
+ """Resets the profiling.
113
+
114
+ Adds or resets the extra attributes.
115
+ """
116
+
117
+ def add_or_reset_attrs(module):
118
+ module.__flops__ = 0
119
+ module.__params__ = sum(p.numel() for p in module.parameters())
120
+
121
+ self.model.apply(add_or_reset_attrs)
122
+
123
+ def end_profile(self):
124
+ """Ends profiling.
125
+
126
+ The added attributes and handles are removed recursively on all the modules.
127
+ """
128
+ if not self.started:
129
+ return
130
+ self.stop_profile()
131
+ self.started = False
132
+
133
+ def remove_profile_attrs(module):
134
+ if hasattr(module, "__flops__"):
135
+ del module.__flops__
136
+ if hasattr(module, "__params__"):
137
+ del module.__params__
138
+
139
+ self.model.apply(remove_profile_attrs)
140
+
141
+ def get_total_flops(self, as_string=False):
142
+ """Returns the total flops of the model.
143
+
144
+ Args:
145
+ as_string (bool, optional): whether to output the flops as string. Defaults to False.
146
+
147
+ Returns:
148
+ The number of multiply-accumulate operations of the model forward pass.
149
+ """
150
+ total_flops = get_module_flops(self.model)
151
+ return num_to_string(total_flops) if as_string else total_flops
152
+
153
+ def get_total_params(self, as_string=False):
154
+ """Returns the total parameters of the model.
155
+
156
+ Args:
157
+ as_string (bool, optional): whether to output the parameters as string. Defaults to False.
158
+
159
+ Returns:
160
+ The number of parameters in the model.
161
+ """
162
+ return (
163
+ params_to_string(self.model.__params__)
164
+ if as_string
165
+ else self.model.__params__
166
+ )
167
+
168
+
169
+ def _prod(dims):
170
+ p = 1
171
+ for v in dims:
172
+ p *= v
173
+ return p
174
+
175
+
176
+ def _linear_flops_compute(input, weight, bias=None):
177
+ out_features = weight.shape[0]
178
+ macs = input.numel() * out_features
179
+ return 2 * macs
180
+
181
+
182
+ def _relu_flops_compute(input, inplace=False):
183
+ return input.numel()
184
+
185
+
186
+ def _prelu_flops_compute(input: Tensor, weight: Tensor):
187
+ return input.numel()
188
+
189
+
190
+ def _elu_flops_compute(input: Tensor, alpha: float = 1.0, inplace: bool = False):
191
+ return input.numel()
192
+
193
+
194
+ def _leaky_relu_flops_compute(
195
+ input: Tensor, negative_slope: float = 0.01, inplace: bool = False
196
+ ):
197
+ return input.numel()
198
+
199
+
200
+ def _relu6_flops_compute(input: Tensor, inplace: bool = False):
201
+ return input.numel()
202
+
203
+
204
+ def _silu_flops_compute(input: Tensor, inplace: bool = False):
205
+ return input.numel()
206
+
207
+
208
+ def _gelu_flops_compute(input, **kwargs):
209
+ return input.numel()
210
+
211
+
212
+ def _pool_flops_compute(
213
+ input,
214
+ kernel_size,
215
+ stride=None,
216
+ padding=0,
217
+ dilation=None,
218
+ ceil_mode=False,
219
+ count_include_pad=True,
220
+ divisor_override=None,
221
+ return_indices=None,
222
+ ):
223
+ return input.numel()
224
+
225
+
226
+ def _conv_flops_compute(
227
+ input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1
228
+ ):
229
+ assert weight.shape[1] * groups == input.shape[1]
230
+
231
+ batch_size = input.shape[0]
232
+ in_channels = input.shape[1]
233
+ out_channels = weight.shape[0]
234
+ kernel_dims = list(weight.shape[2:])
235
+ input_dims = list(input.shape[2:])
236
+
237
+ length = len(input_dims)
238
+
239
+ paddings = padding if type(padding) is tuple else (padding,) * length
240
+ strides = stride if type(stride) is tuple else (stride,) * length
241
+ dilations = dilation if type(dilation) is tuple else (dilation,) * length
242
+
243
+ output_dims = []
244
+ for idx, input_dim in enumerate(input_dims):
245
+ output_dim = (
246
+ input_dim
247
+ + 2 * paddings[idx]
248
+ - (dilations[idx] * (kernel_dims[idx] - 1) + 1)
249
+ ) // strides[idx] + 1
250
+ output_dims.append(output_dim)
251
+
252
+ filters_per_channel = out_channels // groups
253
+ conv_per_position_macs = int(_prod(kernel_dims)) * in_channels * filters_per_channel
254
+ active_elements_count = batch_size * int(_prod(output_dims))
255
+ overall_conv_macs = conv_per_position_macs * active_elements_count
256
+ overall_conv_flops = 2 * overall_conv_macs
257
+
258
+ bias_flops = 0
259
+ if bias is not None:
260
+ bias_flops = out_channels * active_elements_count
261
+
262
+ return int(overall_conv_flops + bias_flops)
263
+
264
+
265
+ def _conv_trans_flops_compute(
266
+ input,
267
+ weight,
268
+ bias=None,
269
+ stride=1,
270
+ padding=0,
271
+ output_padding=0,
272
+ groups=1,
273
+ dilation=1,
274
+ ):
275
+ batch_size = input.shape[0]
276
+ in_channels = input.shape[1]
277
+ out_channels = weight.shape[0]
278
+ kernel_dims = list(weight.shape[2:])
279
+ input_dims = list(input.shape[2:])
280
+
281
+ length = len(input_dims)
282
+
283
+ paddings = padding if type(padding) is tuple else (padding,) * length
284
+ strides = stride if type(stride) is tuple else (stride,) * length
285
+ dilations = dilation if type(dilation) is tuple else (dilation,) * length
286
+
287
+ output_dims = []
288
+ for idx, input_dim in enumerate(input_dims):
289
+ output_dim = (
290
+ input_dim
291
+ + 2 * paddings[idx]
292
+ - (dilations[idx] * (kernel_dims[idx] - 1) + 1)
293
+ ) // strides[idx] + 1
294
+ output_dims.append(output_dim)
295
+
296
+ paddings = padding if type(padding) is tuple else (padding, padding)
297
+ strides = stride if type(stride) is tuple else (stride, stride)
298
+ dilations = dilation if type(dilation) is tuple else (dilation, dilation)
299
+
300
+ filters_per_channel = out_channels // groups
301
+ conv_per_position_macs = int(_prod(kernel_dims)) * in_channels * filters_per_channel
302
+ active_elements_count = batch_size * int(_prod(input_dims))
303
+ overall_conv_macs = conv_per_position_macs * active_elements_count
304
+ overall_conv_flops = 2 * overall_conv_macs
305
+
306
+ bias_flops = 0
307
+ if bias is not None:
308
+ bias_flops = out_channels * batch_size * int(_prod(output_dims))
309
+
310
+ return int(overall_conv_flops + bias_flops)
311
+
312
+
313
+ def _batch_norm_flops_compute(
314
+ input,
315
+ running_mean,
316
+ running_var,
317
+ weight=None,
318
+ bias=None,
319
+ training=False,
320
+ momentum=0.1,
321
+ eps=1e-05,
322
+ ):
323
+ has_affine = weight is not None
324
+ if training:
325
+ # estimation
326
+ return input.numel() * (5 if has_affine else 4), 0
327
+ flops = input.numel() * (2 if has_affine else 1)
328
+ return flops
329
+
330
+
331
+ def _layer_norm_flops_compute(
332
+ input: Tensor,
333
+ normalized_shape: List[int],
334
+ weight: Optional[Tensor] = None,
335
+ bias: Optional[Tensor] = None,
336
+ eps: float = 1e-5,
337
+ ):
338
+ has_affine = weight is not None
339
+ # estimation
340
+ return input.numel() * (5 if has_affine else 4)
341
+
342
+
343
+ def _group_norm_flops_compute(
344
+ input: Tensor,
345
+ num_groups: int,
346
+ weight: Optional[Tensor] = None,
347
+ bias: Optional[Tensor] = None,
348
+ eps: float = 1e-5,
349
+ ):
350
+ has_affine = weight is not None
351
+ # estimation
352
+ return input.numel() * (5 if has_affine else 4)
353
+
354
+
355
+ def _instance_norm_flops_compute(
356
+ input: Tensor,
357
+ running_mean: Optional[Tensor] = None,
358
+ running_var: Optional[Tensor] = None,
359
+ weight: Optional[Tensor] = None,
360
+ bias: Optional[Tensor] = None,
361
+ use_input_stats: bool = True,
362
+ momentum: float = 0.1,
363
+ eps: float = 1e-5,
364
+ ):
365
+ has_affine = weight is not None
366
+ # estimation
367
+ return input.numel() * (5 if has_affine else 4)
368
+
369
+
370
+ def _upsample_flops_compute(input, **kwargs):
371
+ size = kwargs.get("size", None)
372
+ if size is not None:
373
+ if isinstance(size, tuple) or isinstance(size, list):
374
+ return int(_prod(size)), 0
375
+ else:
376
+ return int(size), 0
377
+ scale_factor = kwargs.get("scale_factor", None)
378
+ assert scale_factor is not None, "either size or scale_factor should be defined"
379
+ flops = input.numel()
380
+ if isinstance(scale_factor, tuple) and len(scale_factor) == len(input):
381
+ flops * int(_prod(scale_factor))
382
+ else:
383
+ flops * scale_factor ** len(input)
384
+ return flops
385
+
386
+
387
+ def _softmax_flops_compute(input, dim=None, _stacklevel=3, dtype=None):
388
+ return input.numel()
389
+
390
+
391
+ def _sigmoid_flops_compute(input):
392
+ return input.numel()
393
+
394
+
395
+ def _embedding_flops_compute(
396
+ input,
397
+ weight,
398
+ padding_idx=None,
399
+ max_norm=None,
400
+ norm_type=2.0,
401
+ scale_grad_by_freq=False,
402
+ sparse=False,
403
+ ):
404
+ return 0
405
+
406
+
407
+ def _dropout_flops_compute(input, p=0.5, training=True, inplace=False):
408
+ return 0
409
+
410
+
411
+ def _matmul_flops_compute(input, other, *, out=None):
412
+ """
413
+ Count flops for the matmul operation.
414
+ """
415
+ macs = _prod(input.shape) * other.shape[-1]
416
+ return 2 * macs
417
+
418
+
419
+ def _addmm_flops_compute(input, mat1, mat2, *, beta=1, alpha=1, out=None):
420
+ """
421
+ Count flops for the addmm operation.
422
+ """
423
+ macs = _prod(mat1.shape) * mat2.shape[-1]
424
+ return 2 * macs + _prod(input.shape)
425
+
426
+
427
+ def _einsum_flops_compute(equation, *operands):
428
+ """
429
+ Count flops for the einsum operation.
430
+ """
431
+ equation = equation.replace(" ", "")
432
+ input_shapes = [o.shape for o in operands]
433
+
434
+ # Re-map equation so that same equation with different alphabet
435
+ # representations will look the same.
436
+ letter_order = OrderedDict((k, 0) for k in equation if k.isalpha()).keys()
437
+ mapping = {ord(x): 97 + i for i, x in enumerate(letter_order)}
438
+ equation = equation.translate(mapping)
439
+
440
+ np_arrs = [np.zeros(s) for s in input_shapes]
441
+ optim = np.einsum_path(equation, *np_arrs, optimize="optimal")[1]
442
+ for line in optim.split("\n"):
443
+ if "optimized flop" in line.lower():
444
+ flop = int(float(line.split(":")[-1]))
445
+ return flop
446
+ raise NotImplementedError("Unsupported einsum operation.")
447
+
448
+
449
+ def _tensor_addmm_flops_compute(self, mat1, mat2, *, beta=1, alpha=1, out=None):
450
+ """
451
+ Count flops for the tensor addmm operation.
452
+ """
453
+ macs = _prod(mat1.shape) * mat2.shape[-1]
454
+ return 2 * macs + _prod(self.shape)
455
+
456
+
457
+ def _mul_flops_compute(input, other, *, out=None):
458
+ print("mul")
459
+ return _elementwise_flops_compute(input, other)
460
+
461
+
462
+ def _add_flops_compute(input, other, *, alpha=1, out=None):
463
+ print("add")
464
+ return _elementwise_flops_compute(input, other)
465
+
466
+
467
+ def _sum_flops_compute(input, dim, keepdim=False):
468
+ return input.numel()
469
+
470
+
471
+ def _elementwise_flops_compute(input, other):
472
+ if not torch.is_tensor(input):
473
+ if torch.is_tensor(other):
474
+ return _prod(other.shape)
475
+ else:
476
+ return 1
477
+ elif not torch.is_tensor(other):
478
+ return _prod(input.shape)
479
+ else:
480
+ dim_input = len(input.shape)
481
+ dim_other = len(other.shape)
482
+ max_dim = max(dim_input, dim_other)
483
+
484
+ final_shape = []
485
+ for i in range(max_dim):
486
+ in_i = input.shape[i] if i < dim_input else 1
487
+ ot_i = other.shape[i] if i < dim_other else 1
488
+ if in_i > ot_i:
489
+ final_shape.append(in_i)
490
+ else:
491
+ final_shape.append(ot_i)
492
+ flops = _prod(final_shape)
493
+ return flops
494
+
495
+
496
+ def _tanh_flops_compute(input):
497
+ return input.numel()
498
+
499
+
500
+ def _k2_swoosh_flops_compute(input):
501
+ # For SwooshLForward and SwooshRForward
502
+ # estimate as swish/silu
503
+ return input.numel()
504
+
505
+
506
+ def wrapFunc(func, funcFlopCompute):
507
+ oldFunc = func
508
+ name = func.__str__
509
+ old_functions[name] = oldFunc
510
+
511
+ def newFunc(*args, **kwds):
512
+ flops = funcFlopCompute(*args, **kwds)
513
+ if module_flop_count:
514
+ module_flop_count[-1].append((name, flops))
515
+ return oldFunc(*args, **kwds)
516
+
517
+ newFunc.__str__ = func.__str__
518
+
519
+ return newFunc
520
+
521
+
522
+ def _patch_functionals():
523
+ # FC
524
+ F.linear = wrapFunc(F.linear, _linear_flops_compute)
525
+
526
+ # convolutions
527
+ F.conv1d = wrapFunc(F.conv1d, _conv_flops_compute)
528
+ F.conv2d = wrapFunc(F.conv2d, _conv_flops_compute)
529
+ F.conv3d = wrapFunc(F.conv3d, _conv_flops_compute)
530
+
531
+ # conv transposed
532
+ F.conv_transpose1d = wrapFunc(F.conv_transpose1d, _conv_trans_flops_compute)
533
+ F.conv_transpose2d = wrapFunc(F.conv_transpose2d, _conv_trans_flops_compute)
534
+ F.conv_transpose3d = wrapFunc(F.conv_transpose3d, _conv_trans_flops_compute)
535
+
536
+ # activations
537
+ F.relu = wrapFunc(F.relu, _relu_flops_compute)
538
+ F.prelu = wrapFunc(F.prelu, _prelu_flops_compute)
539
+ F.elu = wrapFunc(F.elu, _elu_flops_compute)
540
+ F.leaky_relu = wrapFunc(F.leaky_relu, _leaky_relu_flops_compute)
541
+ F.relu6 = wrapFunc(F.relu6, _relu6_flops_compute)
542
+ if hasattr(F, "silu"):
543
+ F.silu = wrapFunc(F.silu, _silu_flops_compute)
544
+ F.gelu = wrapFunc(F.gelu, _gelu_flops_compute)
545
+
546
+ # Normalizations
547
+ F.batch_norm = wrapFunc(F.batch_norm, _batch_norm_flops_compute)
548
+ F.layer_norm = wrapFunc(F.layer_norm, _layer_norm_flops_compute)
549
+ F.instance_norm = wrapFunc(F.instance_norm, _instance_norm_flops_compute)
550
+ F.group_norm = wrapFunc(F.group_norm, _group_norm_flops_compute)
551
+
552
+ # poolings
553
+ F.avg_pool1d = wrapFunc(F.avg_pool1d, _pool_flops_compute)
554
+ F.avg_pool2d = wrapFunc(F.avg_pool2d, _pool_flops_compute)
555
+ F.avg_pool3d = wrapFunc(F.avg_pool3d, _pool_flops_compute)
556
+ F.max_pool1d = wrapFunc(F.max_pool1d, _pool_flops_compute)
557
+ F.max_pool2d = wrapFunc(F.max_pool2d, _pool_flops_compute)
558
+ F.max_pool3d = wrapFunc(F.max_pool3d, _pool_flops_compute)
559
+ F.adaptive_avg_pool1d = wrapFunc(F.adaptive_avg_pool1d, _pool_flops_compute)
560
+ F.adaptive_avg_pool2d = wrapFunc(F.adaptive_avg_pool2d, _pool_flops_compute)
561
+ F.adaptive_avg_pool3d = wrapFunc(F.adaptive_avg_pool3d, _pool_flops_compute)
562
+ F.adaptive_max_pool1d = wrapFunc(F.adaptive_max_pool1d, _pool_flops_compute)
563
+ F.adaptive_max_pool2d = wrapFunc(F.adaptive_max_pool2d, _pool_flops_compute)
564
+ F.adaptive_max_pool3d = wrapFunc(F.adaptive_max_pool3d, _pool_flops_compute)
565
+
566
+ # upsample
567
+ F.upsample = wrapFunc(F.upsample, _upsample_flops_compute)
568
+ F.interpolate = wrapFunc(F.interpolate, _upsample_flops_compute)
569
+
570
+ # softmax
571
+ F.softmax = wrapFunc(F.softmax, _softmax_flops_compute)
572
+
573
+ # sigmoid
574
+ F.sigmoid = wrapFunc(F.sigmoid, _sigmoid_flops_compute)
575
+
576
+ # embedding
577
+ F.embedding = wrapFunc(F.embedding, _embedding_flops_compute)
578
+
579
+ # swoosh functions in k2
580
+ k2.swoosh_l_forward = wrapFunc(k2.swoosh_l_forward, _k2_swoosh_flops_compute)
581
+ k2.swoosh_r_forward = wrapFunc(k2.swoosh_r_forward, _k2_swoosh_flops_compute)
582
+ k2.swoosh_l = wrapFunc(k2.swoosh_l, _k2_swoosh_flops_compute)
583
+ k2.swoosh_r = wrapFunc(k2.swoosh_r, _k2_swoosh_flops_compute)
584
+
585
+
586
+ def _patch_tensor_methods():
587
+ torch.matmul = wrapFunc(torch.matmul, _matmul_flops_compute)
588
+ torch.Tensor.matmul = wrapFunc(torch.Tensor.matmul, _matmul_flops_compute)
589
+ torch.mm = wrapFunc(torch.mm, _matmul_flops_compute)
590
+ torch.Tensor.mm = wrapFunc(torch.Tensor.mm, _matmul_flops_compute)
591
+ torch.bmm = wrapFunc(torch.bmm, _matmul_flops_compute)
592
+ torch.Tensor.bmm = wrapFunc(torch.Tensor.bmm, _matmul_flops_compute)
593
+
594
+ torch.addmm = wrapFunc(torch.addmm, _addmm_flops_compute)
595
+ torch.Tensor.addmm = wrapFunc(torch.Tensor.addmm, _tensor_addmm_flops_compute)
596
+
597
+ torch.mul = wrapFunc(torch.mul, _mul_flops_compute)
598
+ torch.Tensor.mul = wrapFunc(torch.Tensor.mul, _mul_flops_compute)
599
+
600
+ torch.add = wrapFunc(torch.add, _add_flops_compute)
601
+ torch.Tensor.add = wrapFunc(torch.Tensor.add, _add_flops_compute)
602
+
603
+ torch.sum = wrapFunc(torch.sum, _sum_flops_compute)
604
+ torch.Tensor.sum = wrapFunc(torch.Tensor.sum, _sum_flops_compute)
605
+
606
+ torch.einsum = wrapFunc(torch.einsum, _einsum_flops_compute)
607
+
608
+ torch.baddbmm = wrapFunc(torch.baddbmm, _tensor_addmm_flops_compute)
609
+
610
+ torch.tanh = wrapFunc(torch.tanh, _tanh_flops_compute)
611
+
612
+ torch.Tensor.softmax = wrapFunc(torch.Tensor.softmax, _softmax_flops_compute)
613
+
614
+ torch.sigmoid = wrapFunc(torch.sigmoid, _sigmoid_flops_compute)
615
+ torch.Tensor.sigmoid = wrapFunc(torch.Tensor.sigmoid, _sigmoid_flops_compute)
616
+
617
+
618
+ def _reload_functionals():
619
+ # torch.nn.functional does not support importlib.reload()
620
+ F.linear = old_functions[F.linear.__str__]
621
+ F.conv1d = old_functions[F.conv1d.__str__]
622
+ F.conv2d = old_functions[F.conv2d.__str__]
623
+ F.conv3d = old_functions[F.conv3d.__str__]
624
+ F.conv_transpose1d = old_functions[F.conv_transpose1d.__str__]
625
+ F.conv_transpose2d = old_functions[F.conv_transpose2d.__str__]
626
+ F.conv_transpose3d = old_functions[F.conv_transpose3d.__str__]
627
+ F.relu = old_functions[F.relu.__str__]
628
+ F.prelu = old_functions[F.prelu.__str__]
629
+ F.elu = old_functions[F.elu.__str__]
630
+ F.leaky_relu = old_functions[F.leaky_relu.__str__]
631
+ F.relu6 = old_functions[F.relu6.__str__]
632
+ if hasattr(F, "silu"):
633
+ F.silu = old_functions[F.silu.__str__]
634
+ F.gelu = old_functions[F.gelu.__str__]
635
+ F.batch_norm = old_functions[F.batch_norm.__str__]
636
+ F.layer_norm = old_functions[F.layer_norm.__str__]
637
+ F.instance_norm = old_functions[F.instance_norm.__str__]
638
+ F.group_norm = old_functions[F.group_norm.__str__]
639
+ F.avg_pool1d = old_functions[F.avg_pool1d.__str__]
640
+ F.avg_pool2d = old_functions[F.avg_pool2d.__str__]
641
+ F.avg_pool3d = old_functions[F.avg_pool3d.__str__]
642
+ F.max_pool1d = old_functions[F.max_pool1d.__str__]
643
+ F.max_pool2d = old_functions[F.max_pool2d.__str__]
644
+ F.max_pool3d = old_functions[F.max_pool3d.__str__]
645
+ F.adaptive_avg_pool1d = old_functions[F.adaptive_avg_pool1d.__str__]
646
+ F.adaptive_avg_pool2d = old_functions[F.adaptive_avg_pool2d.__str__]
647
+ F.adaptive_avg_pool3d = old_functions[F.adaptive_avg_pool3d.__str__]
648
+ F.adaptive_max_pool1d = old_functions[F.adaptive_max_pool1d.__str__]
649
+ F.adaptive_max_pool2d = old_functions[F.adaptive_max_pool2d.__str__]
650
+ F.adaptive_max_pool3d = old_functions[F.adaptive_max_pool3d.__str__]
651
+ F.upsample = old_functions[F.upsample.__str__]
652
+ F.interpolate = old_functions[F.interpolate.__str__]
653
+ F.softmax = old_functions[F.softmax.__str__]
654
+ F.sigmoid = old_functions[F.sigmoid.__str__]
655
+ F.embedding = old_functions[F.embedding.__str__]
656
+ # swoosh functions in k2
657
+ k2.swoosh_l = old_functions[k2.swoosh_l.__str__]
658
+ k2.swoosh_r = old_functions[k2.swoosh_r.__str__]
659
+ k2.swoosh_l_forward = old_functions[k2.swoosh_l_forward.__str__]
660
+ k2.swoosh_r_forward = old_functions[k2.swoosh_r_forward.__str__]
661
+
662
+
663
+ def _reload_tensor_methods():
664
+ torch.matmul = old_functions[torch.matmul.__str__]
665
+ torch.Tensor.matmul = old_functions[torch.Tensor.matmul.__str__]
666
+ torch.mm = old_functions[torch.mm.__str__]
667
+ torch.Tensor.mm = old_functions[torch.Tensor.mm.__str__]
668
+ torch.bmm = old_functions[torch.matmul.__str__]
669
+ torch.Tensor.bmm = old_functions[torch.Tensor.bmm.__str__]
670
+ torch.addmm = old_functions[torch.addmm.__str__]
671
+ torch.Tensor.addmm = old_functions[torch.Tensor.addmm.__str__]
672
+ torch.mul = old_functions[torch.mul.__str__]
673
+ torch.Tensor.mul = old_functions[torch.Tensor.mul.__str__]
674
+ torch.add = old_functions[torch.add.__str__]
675
+ torch.Tensor.add = old_functions[torch.Tensor.add.__str__]
676
+ torch.sum = old_functions[torch.sum.__str__]
677
+ torch.Tensor.sum = old_functions[torch.Tensor.sum.__str__]
678
+
679
+ torch.einsum = old_functions[torch.einsum.__str__]
680
+
681
+ torch.baddbmm = old_functions[torch.baddbmm.__str__]
682
+
683
+ torch.Tensor.softmax = old_functions[torch.Tensor.softmax.__str__]
684
+
685
+ torch.sigmoid = old_functions[torch.sigmoid.__str__]
686
+ torch.Tensor.sigmoid = old_functions[torch.Tensor.sigmoid.__str__]
687
+
688
+
689
+ def _rnn_flops(flops, rnn_module, w_ih, w_hh, input_size):
690
+ # matrix matrix mult ih state and internal state
691
+ flops += w_ih.shape[0] * w_ih.shape[1]
692
+ # matrix matrix mult hh state and internal state
693
+ flops += w_hh.shape[0] * w_hh.shape[1]
694
+ if isinstance(rnn_module, (nn.RNN, nn.RNNCell)):
695
+ # add both operations
696
+ flops += rnn_module.hidden_size
697
+ elif isinstance(rnn_module, (nn.GRU, nn.GRUCell)):
698
+ # hadamard of r
699
+ flops += rnn_module.hidden_size
700
+ # adding operations from both states
701
+ flops += rnn_module.hidden_size * 3
702
+ # last two hadamard _product and add
703
+ flops += rnn_module.hidden_size * 3
704
+ elif isinstance(rnn_module, (nn.LSTM, nn.LSTMCell)):
705
+ # adding operations from both states
706
+ flops += rnn_module.hidden_size * 4
707
+ # two hadamard _product and add for C state
708
+ flops += (
709
+ rnn_module.hidden_size + rnn_module.hidden_size + rnn_module.hidden_size
710
+ )
711
+ # final hadamard
712
+ flops += (
713
+ rnn_module.hidden_size + rnn_module.hidden_size + rnn_module.hidden_size
714
+ )
715
+ return flops
716
+
717
+
718
+ def _rnn_forward_hook(rnn_module, input, output):
719
+ flops = 0
720
+ # input is a tuple containing a sequence to process and (optionally) hidden state
721
+ inp = input[0]
722
+ batch_size = inp.shape[0]
723
+ seq_length = inp.shape[1]
724
+ num_layers = rnn_module.num_layers
725
+
726
+ for i in range(num_layers):
727
+ w_ih = rnn_module.__getattr__("weight_ih_l" + str(i))
728
+ w_hh = rnn_module.__getattr__("weight_hh_l" + str(i))
729
+ if i == 0:
730
+ input_size = rnn_module.input_size
731
+ else:
732
+ input_size = rnn_module.hidden_size
733
+ flops = _rnn_flops(flops, rnn_module, w_ih, w_hh, input_size)
734
+ if rnn_module.bias:
735
+ b_ih = rnn_module.__getattr__("bias_ih_l" + str(i))
736
+ b_hh = rnn_module.__getattr__("bias_hh_l" + str(i))
737
+ flops += b_ih.shape[0] + b_hh.shape[0]
738
+
739
+ flops *= batch_size
740
+ flops *= seq_length
741
+ if rnn_module.bidirectional:
742
+ flops *= 2
743
+ rnn_module.__flops__ += int(flops)
744
+
745
+
746
+ def _rnn_cell_forward_hook(rnn_cell_module, input, output):
747
+ flops = 0
748
+ inp = input[0]
749
+ batch_size = inp.shape[0]
750
+ w_ih = rnn_cell_module.__getattr__("weight_ih")
751
+ w_hh = rnn_cell_module.__getattr__("weight_hh")
752
+ input_size = inp.shape[1]
753
+ flops = _rnn_flops(flops, rnn_cell_module, w_ih, w_hh, input_size)
754
+ if rnn_cell_module.bias:
755
+ b_ih = rnn_cell_module.__getattr__("bias_ih")
756
+ b_hh = rnn_cell_module.__getattr__("bias_hh")
757
+ flops += b_ih.shape[0] + b_hh.shape[0]
758
+
759
+ flops *= batch_size
760
+ rnn_cell_module.__flops__ += int(flops)
761
+
762
+
763
+ MODULE_HOOK_MAPPING = {
764
+ # RNN
765
+ nn.RNN: _rnn_forward_hook,
766
+ nn.GRU: _rnn_forward_hook,
767
+ nn.LSTM: _rnn_forward_hook,
768
+ nn.RNNCell: _rnn_cell_forward_hook,
769
+ nn.LSTMCell: _rnn_cell_forward_hook,
770
+ nn.GRUCell: _rnn_cell_forward_hook,
771
+ }
772
+
773
+
774
+ def num_to_string(num, precision=2):
775
+ if num // 10**9 > 0:
776
+ return str(round(num / 10.0**9, precision)) + " G"
777
+ elif num // 10**6 > 0:
778
+ return str(round(num / 10.0**6, precision)) + " M"
779
+ elif num // 10**3 > 0:
780
+ return str(round(num / 10.0**3, precision)) + " K"
781
+ else:
782
+ return str(num)
783
+
784
+
785
+ def number_to_string(num, units=None, precision=2):
786
+ if units is None:
787
+ if num // 10**9 > 0:
788
+ return str(round(num / 10.0**9, precision)) + " G"
789
+ elif num // 10**6 > 0:
790
+ return str(round(num / 10.0**6, precision)) + " M"
791
+ elif num // 10**3 > 0:
792
+ return str(round(num / 10.0**3, precision)) + " K"
793
+ else:
794
+ return str(num) + " "
795
+ else:
796
+ if units == "G":
797
+ return str(round(num / 10.0**9, precision)) + " " + units
798
+ elif units == "M":
799
+ return str(round(num / 10.0**6, precision)) + " " + units
800
+ elif units == "K":
801
+ return str(round(num / 10.0**3, precision)) + " " + units
802
+ else:
803
+ return str(num) + " "
804
+
805
+
806
+ def flops_to_string(flops, units=None, precision=2):
807
+ if units is None:
808
+ if flops // 10**12 > 0:
809
+ return str(round(flops / 10.0**12, precision)) + " TFLOPS"
810
+ if flops // 10**9 > 0:
811
+ return str(round(flops / 10.0**9, precision)) + " GFLOPS"
812
+ elif flops // 10**6 > 0:
813
+ return str(round(flops / 10.0**6, precision)) + " MFLOPS"
814
+ elif flops // 10**3 > 0:
815
+ return str(round(flops / 10.0**3, precision)) + " KFLOPS"
816
+ else:
817
+ return str(flops) + " FLOPS"
818
+ else:
819
+ if units == "TFLOPS":
820
+ return str(round(flops / 10.0**12, precision)) + " " + units
821
+ if units == "GFLOPS":
822
+ return str(round(flops / 10.0**9, precision)) + " " + units
823
+ elif units == "MFLOPS":
824
+ return str(round(flops / 10.0**6, precision)) + " " + units
825
+ elif units == "KFLOPS":
826
+ return str(round(flops / 10.0**3, precision)) + " " + units
827
+ else:
828
+ return str(flops) + " FLOPS"
829
+
830
+
831
+ def params_to_string(params_num, units=None, precision=2):
832
+ if units is None:
833
+ if params_num // 10**6 > 0:
834
+ return str(round(params_num / 10**6, 2)) + " M"
835
+ elif params_num // 10**3:
836
+ return str(round(params_num / 10**3, 2)) + " k"
837
+ else:
838
+ return str(params_num)
839
+ else:
840
+ if units == "M":
841
+ return str(round(params_num / 10.0**6, precision)) + " " + units
842
+ elif units == "K":
843
+ return str(round(params_num / 10.0**3, precision)) + " " + units
844
+ else:
845
+ return str(params_num)
846
+
847
+
848
+ def get_module_flops(module):
849
+ sum = module.__flops__
850
+ # iterate over immediate children modules
851
+ for child in module.children():
852
+ sum += get_module_flops(child)
853
+ return sum
854
+
855
+
856
+ def get_module_duration(module):
857
+ duration = module.__duration__
858
+ if duration == 0: # e.g. ModuleList
859
+ for m in module.children():
860
+ duration += m.__duration__
861
+ return duration
862
+
863
+
864
+ def get_model_profile(
865
+ model,
866
+ args=[],
867
+ as_string=True,
868
+ ignore_modules=None,
869
+ module_hoop_mapping=None,
870
+ ):
871
+ """Returns the total floating-point operations, MACs, and parameters of a model.
872
+
873
+ Example:
874
+
875
+ .. code-block:: python
876
+
877
+ model = torchvision.models.alexnet()
878
+ batch_size = 256
879
+ flops, params = get_model_profile(model=model, args=(feature, feature_lens))
880
+
881
+ Args:
882
+ model ([torch.nn.Module]): the PyTorch model to be profiled.
883
+ args (list): list of positional arguments to the model.
884
+ top_modules (int, optional): the number of top modules to print in the aggregated profile. Defaults to 3.
885
+ as_string (bool, optional): whether to print the output as string. Defaults to True.
886
+ ignore_modules ([type], optional): the list of modules to ignore during profiling. Defaults to None.
887
+
888
+ Returns:
889
+ The number of floating-point operations, multiply-accumulate operations (MACs), and parameters in the model.
890
+ """
891
+ assert isinstance(model, nn.Module), "model must be a PyTorch module"
892
+ prof = FlopsProfiler(model, module_hoop_mapping=module_hoop_mapping)
893
+ model.eval()
894
+
895
+ assert len(args) > 0, "input args must be specified"
896
+
897
+ prof.start_profile(ignore_list=ignore_modules)
898
+
899
+ _ = model(*args)
900
+
901
+ flops = prof.get_total_flops()
902
+ params = prof.get_total_params()
903
+
904
+ prof.end_profile()
905
+ if as_string:
906
+ return (
907
+ number_to_string(flops),
908
+ params_to_string(params),
909
+ )
910
+
911
+ return flops, params