dlxj commited on
Commit
7965430
·
1 Parent(s): c80256c

add nemo 2.2.1 源码

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +10 -1
  2. .vscode/settings.json +3 -0
  3. common_voice_ja_25372057.wav +3 -0
  4. data/common_voice_11_0/transcript/ja/dev.tsv +2 -2
  5. data/common_voice_11_0/transcript/ja/invalidated.tsv +2 -2
  6. data/common_voice_11_0/transcript/ja/other.tsv +2 -2
  7. data/common_voice_11_0/transcript/ja/test.tsv +2 -2
  8. data/common_voice_11_0/transcript/ja/train.tsv +2 -2
  9. examples/asr/asr_ctc/speech_to_text_ctc_bpe.py +4 -0
  10. examples/asr/asr_eou/speech_to_text_rnnt_eou_train.py +4 -0
  11. examples/asr/asr_streaming_inference/README.md +1 -1
  12. harvard_16k.wav +3 -0
  13. nemo/__init__.py +28 -0
  14. nemo/collections/__init__.py +13 -0
  15. nemo/collections/asr/__init__.py +25 -0
  16. nemo/collections/asr/data/__init__.py +13 -0
  17. nemo/collections/asr/data/audio_to_ctm_dataset.py +95 -0
  18. nemo/collections/asr/data/audio_to_diar_label.py +1379 -0
  19. nemo/collections/asr/data/audio_to_diar_label_lhotse.py +82 -0
  20. nemo/collections/asr/data/audio_to_label.py +1420 -0
  21. nemo/collections/asr/data/audio_to_label_dataset.py +304 -0
  22. nemo/collections/asr/data/audio_to_text.py +1404 -0
  23. nemo/collections/asr/data/audio_to_text_dali.py +772 -0
  24. nemo/collections/asr/data/audio_to_text_dataset.py +983 -0
  25. nemo/collections/asr/data/audio_to_text_lhotse.py +68 -0
  26. nemo/collections/asr/data/audio_to_text_lhotse_prompted.py +136 -0
  27. nemo/collections/asr/data/data_simulation.py +1700 -0
  28. nemo/collections/asr/data/feature_to_label.py +497 -0
  29. nemo/collections/asr/data/feature_to_label_dataset.py +68 -0
  30. nemo/collections/asr/data/feature_to_text.py +487 -0
  31. nemo/collections/asr/data/feature_to_text_dataset.py +94 -0
  32. nemo/collections/asr/data/huggingface/__init__.py +13 -0
  33. nemo/collections/asr/data/huggingface/hf_audio_to_text.py +694 -0
  34. nemo/collections/asr/data/huggingface/hf_audio_to_text_dataset.py +132 -0
  35. nemo/collections/asr/data/ssl_dataset.py +705 -0
  36. nemo/collections/asr/data/text_to_text.py +482 -0
  37. nemo/collections/asr/losses/__init__.py +22 -0
  38. nemo/collections/asr/losses/angularloss.py +68 -0
  39. nemo/collections/asr/losses/bce_loss.py +135 -0
  40. nemo/collections/asr/losses/ctc.py +82 -0
  41. nemo/collections/asr/losses/lattice_losses.py +184 -0
  42. nemo/collections/asr/losses/rnnt.py +508 -0
  43. nemo/collections/asr/losses/rnnt_pytorch.py +374 -0
  44. nemo/collections/asr/losses/ssl_losses/__init__.py +15 -0
  45. nemo/collections/asr/losses/ssl_losses/contrastive.py +304 -0
  46. nemo/collections/asr/losses/ssl_losses/ctc.py +57 -0
  47. nemo/collections/asr/losses/ssl_losses/mlm.py +138 -0
  48. nemo/collections/asr/losses/ssl_losses/rnnt.py +58 -0
  49. nemo/collections/asr/metrics/__init__.py +16 -0
  50. nemo/collections/asr/metrics/bleu.py +212 -0
.gitignore CHANGED
@@ -1,10 +1,18 @@
1
  # log and data files
2
  # common_voice_11_0/
 
 
3
  common_voice_11_0/audio/
4
  common_voice_11_0/ja/
5
- # data/common_voice_11_0/audio/
 
6
  data/common_voice_11_0/ja/
 
7
  Common Voice Scripted Speech 25.0 - Japanese/
 
 
 
 
8
  *.model
9
  *.pkl
10
  #*.ipynb
@@ -198,3 +206,4 @@ node_modules/
198
  bot_server.*
199
  audio_logs/
200
  eval_results/
 
 
1
  # log and data files
2
  # common_voice_11_0/
3
+ # nemo/
4
+ nemotron-speech-streaming-en-0.6b/
5
  common_voice_11_0/audio/
6
  common_voice_11_0/ja/
7
+ common_voice_11_0/eo/
8
+ data/common_voice_11_0/audio/
9
  data/common_voice_11_0/ja/
10
+ data/common_voice_11_0/eo/
11
  Common Voice Scripted Speech 25.0 - Japanese/
12
+ results/
13
+ results__ja/
14
+ data__ja/
15
+ transcripts.json
16
  *.model
17
  *.pkl
18
  #*.ipynb
 
206
  bot_server.*
207
  audio_logs/
208
  eval_results/
209
+
.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "git.ignoreLimitWarning": true
3
+ }
common_voice_ja_25372057.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cc63eaf4bfd5822ce2f862963aed974b5011029298f57375c65f344bb0ffccb
3
+ size 109484
data/common_voice_11_0/transcript/ja/dev.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d55fb0f1620a80f4c60d37da95199b11119f3d2508ad9b3f900dc30a8ebc0c3d
3
- size 1107150
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43446a3f7fd7f418258a9f8cc170b632ab146e59e53c630ae8ea857eb7d8817d
3
+ size 296
data/common_voice_11_0/transcript/ja/invalidated.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c51e1ec9c5c3fd2eb8a3c91673f63ac2a9d137329c15d1e9864b8fe0c10ba12f
3
- size 638492
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43446a3f7fd7f418258a9f8cc170b632ab146e59e53c630ae8ea857eb7d8817d
3
+ size 296
data/common_voice_11_0/transcript/ja/other.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:24a4e2ce8306879f866124ede472a074c4ea7dab0cdb40f731aef965d74eef73
3
- size 283969
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43446a3f7fd7f418258a9f8cc170b632ab146e59e53c630ae8ea857eb7d8817d
3
+ size 296
data/common_voice_11_0/transcript/ja/test.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ae722b5a68c5e56ca667aced836061e2375de26301eb0285b5b1f0a76efb0b93
3
- size 1122112
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43446a3f7fd7f418258a9f8cc170b632ab146e59e53c630ae8ea857eb7d8817d
3
+ size 296
data/common_voice_11_0/transcript/ja/train.tsv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:34b534ad4c3c0e76ad416095cefed0d8cc73c4a0273c1e16331a0f2f2cdee416
3
- size 1729826
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6daf7d3220aad6fcf8636361aca0d5365d8720a917a61a37e6e86c286485666a
3
+ size 297
examples/asr/asr_ctc/speech_to_text_ctc_bpe.py CHANGED
@@ -64,6 +64,10 @@ https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/results.ht
64
 
65
  """
66
 
 
 
 
 
67
  import lightning.pytorch as pl
68
  from omegaconf import OmegaConf
69
 
 
64
 
65
  """
66
 
67
+ import os
68
+ import sys
69
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
70
+
71
  import lightning.pytorch as pl
72
  from omegaconf import OmegaConf
73
 
examples/asr/asr_eou/speech_to_text_rnnt_eou_train.py CHANGED
@@ -76,6 +76,10 @@ CUDA_VISIBLE_DEVICES=0 python $SCRIPT \
76
 
77
  """
78
 
 
 
 
 
79
  from dataclasses import is_dataclass
80
  from typing import Optional
81
 
 
76
 
77
  """
78
 
79
+ import os
80
+ import sys
81
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
82
+
83
  from dataclasses import is_dataclass
84
  from typing import Optional
85
 
examples/asr/asr_streaming_inference/README.md CHANGED
@@ -9,4 +9,4 @@ Beyond streaming ASR, the script also supports:
9
  * **Streaming Speech Translation (requires vLLM installation)**
10
  * **Word-level and Segment-level Output**
11
 
12
- All related configurations can be found in the `../conf/asr_streaming_inference/` directory.
 
9
  * **Streaming Speech Translation (requires vLLM installation)**
10
  * **Word-level and Segment-level Output**
11
 
12
+ All related configurations can be found in the `../conf/asr_streaming_inference/` directory.
harvard_16k.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa5b415ee7caf6606a04f739a9fe8490fae3d726157cc080060426ead07dfb8b
3
+ size 587496
nemo/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from nemo.package_info import (
17
+ __contact_emails__,
18
+ __contact_names__,
19
+ __description__,
20
+ __download_url__,
21
+ __homepage__,
22
+ __keywords__,
23
+ __license__,
24
+ __package_name__,
25
+ __repository_url__,
26
+ __shortversion__,
27
+ __version__,
28
+ )
nemo/collections/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
nemo/collections/asr/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr import data, losses, models, modules
16
+ from nemo.package_info import __version__
17
+
18
+ # Set collection version equal to NeMo version.
19
+ __version = __version__
20
+
21
+ # Authorship.
22
+ __author__ = "NVIDIA Corporation"
23
+
24
+ # Set collection name.
25
+ __description__ = "Automatic Speech Recognition collection"
nemo/collections/asr/data/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
nemo/collections/asr/data/audio_to_ctm_dataset.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import os
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, List, Tuple
20
+
21
+ from nemo.collections.asr.data.audio_to_text_dataset import ASRPredictionWriter
22
+ from nemo.utils import logging
23
+
24
+
25
+ @dataclass
26
+ class FrameCtmUnit:
27
+ """A container class for one CTM unit with start and length countable in frames.
28
+ """
29
+
30
+ label: str
31
+ start_frame: int
32
+ length: int
33
+ probability: float
34
+
35
+ def __repr__(self) -> str:
36
+ return f"{self.label}\t({self.probability:1.3f}): [{self.start_frame:6d}, {self.length:6d}]"
37
+
38
+ @property
39
+ def end_frame(self):
40
+ return self.start_frame + self.length
41
+
42
+ def to_ctm_str(self, time_per_frame: int) -> str:
43
+ """Represents the data as part of the CTM line.
44
+
45
+ The CTM line format is
46
+ <utterance_name> <channel> <start_time> <duration> <label_str> <probability>
47
+ This method prepares the last four entities."""
48
+ return f"{self.start_frame * time_per_frame :.3f} {self.length * time_per_frame :.3f} {self.label} {self.probability :1.3f}"
49
+
50
+
51
+ class ASRCTMPredictionWriter(ASRPredictionWriter):
52
+ def __init__(self, dataset, output_file: str, output_ctm_dir: str, time_per_frame: float):
53
+ super().__init__(dataset, output_file)
54
+ self.output_ctm_dir = output_ctm_dir
55
+ self.time_per_frame = time_per_frame
56
+ os.makedirs(self.output_ctm_dir, exist_ok=True)
57
+
58
+ def write_ctm(self, name, filepath, frameCtmUnits):
59
+ with open(filepath, "tw", encoding="utf-8") as f:
60
+ for unit in frameCtmUnits:
61
+ f.write(f"{name} 1 {unit.to_ctm_str(self.time_per_frame)}\n")
62
+
63
+ def write_on_batch_end(
64
+ self,
65
+ trainer,
66
+ pl_module: 'LightningModule',
67
+ prediction: Tuple[int, List[FrameCtmUnit]],
68
+ batch_indices: List[int],
69
+ batch: Any,
70
+ batch_idx: int,
71
+ dataloader_idx: int,
72
+ ):
73
+ for sample_id, units in prediction:
74
+ sample = self.dataset.get_manifest_sample(sample_id)
75
+ with_ctm = True
76
+ if len(units) == 0:
77
+ logging.warning(
78
+ f"""Do not producing CTM output for item `{sample.audio_file}`.
79
+ Check if text is empty or if duration is too short: `{sample.text_raw}`, {sample.duration}"""
80
+ )
81
+ with_ctm = False
82
+ item = {}
83
+ item["audio_filepath"] = sample.audio_file
84
+ item["duration"] = sample.duration
85
+ item["text"] = sample.text_raw
86
+ if with_ctm:
87
+ utt_name = Path(sample.audio_file).stem
88
+ ctm_filepath = os.path.join(self.output_ctm_dir, utt_name) + ".ctm"
89
+ self.write_ctm(utt_name, ctm_filepath, units)
90
+ item["ctm_filepath"] = ctm_filepath
91
+ else:
92
+ item["ctm_filepath"] = ""
93
+ self.outf.write(json.dumps(item) + "\n")
94
+ self.samples_num += 1
95
+ return
nemo/collections/asr/data/audio_to_diar_label.py ADDED
@@ -0,0 +1,1379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ from collections import OrderedDict
17
+ from statistics import mode
18
+ from typing import Dict, List, Optional, Tuple
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from nemo.collections.asr.parts.utils.offline_clustering import get_argmin_mat
24
+ from nemo.collections.asr.parts.utils.speaker_utils import convert_rttm_line, get_subsegments, prepare_split_data
25
+ from nemo.collections.common.parts.preprocessing.collections import (
26
+ DiarizationSpeechLabel,
27
+ EndtoEndDiarizationSpeechLabel,
28
+ )
29
+ from nemo.core.classes import Dataset
30
+ from nemo.core.neural_types import AudioSignal, EncodedRepresentation, LengthsType, NeuralType, ProbsType
31
+ from nemo.utils import logging
32
+
33
+
34
+ def get_scale_mapping_list(uniq_timestamps):
35
+ """
36
+ Call get_argmin_mat function to find the index of the non-base-scale segment that is closest to the
37
+ given base-scale segment. For each scale and each segment, a base-scale segment is assigned.
38
+
39
+ Args:
40
+ uniq_timestamps: (dict)
41
+ The dictionary containing embeddings, timestamps and multiscale weights.
42
+ If uniq_timestamps contains only one scale, single scale diarization is performed.
43
+
44
+ Returns:
45
+ scale_mapping_argmat (torch.tensor):
46
+
47
+ The element at the m-th row and the n-th column of the scale mapping matrix indicates the (m+1)-th scale
48
+ segment index which has the closest center distance with (n+1)-th segment in the base scale.
49
+
50
+ - Example:
51
+ `scale_mapping_argmat[2][101] = 85`
52
+
53
+ In the above example, the code snippet means that 86-th segment in the 3rd scale (python index is 2) is
54
+ mapped to the 102-th segment in the base scale. Thus, the longer segments bound to have more repeating
55
+ numbers since multiple base scale segments (since the base scale has the shortest length) fall into the
56
+ range of the longer segments. At the same time, each row contains N numbers of indices where N is number
57
+ of segments in the base-scale (i.e., the finest scale).
58
+ """
59
+ timestamps_in_scales = []
60
+ for key, val in uniq_timestamps['scale_dict'].items():
61
+ timestamps_in_scales.append(torch.tensor(val['time_stamps']))
62
+ session_scale_mapping_list = get_argmin_mat(timestamps_in_scales)
63
+ scale_mapping_argmat = [[] for _ in range(len(uniq_timestamps['scale_dict'].keys()))]
64
+ for scale_idx in range(len(session_scale_mapping_list)):
65
+ scale_mapping_argmat[scale_idx] = session_scale_mapping_list[scale_idx]
66
+ scale_mapping_argmat = torch.stack(scale_mapping_argmat)
67
+ return scale_mapping_argmat
68
+
69
+
70
+ def extract_seg_info_from_rttm(rttm_lines, mapping_dict=None, target_spks=None):
71
+ """
72
+ Get RTTM lines containing speaker labels, start time and end time. target_spks contains two targeted
73
+ speaker indices for creating groundtruth label files. Only speakers in target_spks variable will be
74
+ included in the output lists.
75
+
76
+ Args:
77
+ uniq_id (str):
78
+ Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file.
79
+ rttm_lines (list):
80
+ List containing RTTM lines in str format.
81
+ mapping_dict (dict):
82
+ Mapping between the estimated speakers and the speakers in the ground-truth annotation.
83
+ `mapping_dict` variable is only provided when the inference mode is running in sequence-eval mode.
84
+ Sequence eval mode uses the mapping between the estimated speakers and the speakers
85
+ in ground-truth annotation.
86
+ Returns:
87
+ rttm_tup (tuple):
88
+ Tuple containing lists of start time, end time and speaker labels.
89
+
90
+ """
91
+ stt_list, end_list, speaker_list, pairwise_infer_spks = [], [], [], []
92
+ if target_spks:
93
+ inv_map = {v: k for k, v in mapping_dict.items()}
94
+ for spk_idx in target_spks:
95
+ spk_str = f'speaker_{spk_idx}'
96
+ if spk_str in inv_map:
97
+ pairwise_infer_spks.append(inv_map[spk_str])
98
+ for rttm_line in rttm_lines:
99
+ start, end, speaker = convert_rttm_line(rttm_line)
100
+ if target_spks is None or speaker in pairwise_infer_spks:
101
+ end_list.append(end)
102
+ stt_list.append(start)
103
+ speaker_list.append(speaker)
104
+ rttm_tup = (stt_list, end_list, speaker_list)
105
+ return rttm_tup
106
+
107
+
108
+ def assign_frame_level_spk_vector(rttm_timestamps, round_digits, frame_per_sec, target_spks, min_spks=2):
109
+ """
110
+ Create a multi-dimensional vector sequence containing speaker timestamp information in RTTM.
111
+ The unit-length is the frame shift length of the acoustic feature. The feature-level annotations
112
+ `fr_level_target` will later be converted to base-segment level diarization label.
113
+
114
+ Args:
115
+ rttm_timestamps (list):
116
+ List containing start and end time for each speaker segment label.
117
+ `stt_list`, `end_list` and `speaker_list` are contained.
118
+ frame_per_sec (int):
119
+ Number of feature frames per second. This quantity is determined by
120
+ `window_stride` variable in preprocessing module.
121
+ target_spks (tuple):
122
+ Speaker indices that are generated from combinations.
123
+ If there are only one or two speakers,
124
+ only a single `target_spks` variable is generated.
125
+
126
+ Returns:
127
+ fr_level_target (torch.tensor):
128
+ Tensor containing label for each feature level frame.
129
+ """
130
+ stt_list, end_list, speaker_list = rttm_timestamps
131
+ if len(speaker_list) == 0:
132
+ return None
133
+ else:
134
+ sorted_speakers = sorted(list(set(speaker_list)))
135
+ total_fr_len = int(max(end_list) * (10**round_digits))
136
+ spk_num = max(len(sorted_speakers), min_spks)
137
+ speaker_mapping_dict = {rttm_key: x_int for x_int, rttm_key in enumerate(sorted_speakers)}
138
+ fr_level_target = torch.zeros(total_fr_len, spk_num)
139
+
140
+ # If RTTM is not provided, then there is no speaker mapping dict in target_spks.
141
+ # Thus, return a zero-filled tensor as a placeholder.
142
+ for count, (stt, end, spk_rttm_key) in enumerate(zip(stt_list, end_list, speaker_list)):
143
+ stt, end = round(stt, round_digits), round(end, round_digits)
144
+ spk = speaker_mapping_dict[spk_rttm_key]
145
+ stt_fr, end_fr = int(round(stt, 2) * frame_per_sec), int(round(end, round_digits) * frame_per_sec)
146
+ fr_level_target[stt_fr:end_fr, spk] = 1
147
+ return fr_level_target
148
+
149
+
150
+ def get_subsegments_to_timestamps(
151
+ subsegments: List[Tuple[float, float]], feat_per_sec: int = 100, max_end_ts: float = None, decimals=2
152
+ ):
153
+ """
154
+ Convert subsegment timestamps to scale timestamps by multiplying with the feature rate (`feat_per_sec`)
155
+ and rounding. Segment is consisted of many subsegments and sugsegments are equivalent to `frames`
156
+ in end-to-end speaker diarization models.
157
+
158
+ Args:
159
+ subsegments (List[Tuple[float, float]]):
160
+ A list of tuples where each tuple contains the start and end times of a subsegment
161
+ (frames in end-to-end models).
162
+ >>> subsegments = [[t0_start, t0_duration], [t1_start, t1_duration],..., [tN_start, tN_duration]]
163
+ feat_per_sec (int, optional):
164
+ The number of feature frames per second. Defaults to 100.
165
+ max_end_ts (float, optional):
166
+ The maximum end timestamp to clip the results. If None, no clipping is applied. Defaults to None.
167
+ decimals (int, optional):
168
+ The number of decimal places to round the timestamps. Defaults to 2.
169
+
170
+ Example:
171
+ Segments starting from 0.0 and ending at 69.2 seconds.
172
+ If hop-length is 0.08 and the subsegment (frame) length is 0.16 seconds,
173
+ there are 864 = (69.2 - 0.16)/0.08 + 1 subsegments (frames in end-to-end models) in this segment.
174
+ >>> subsegments = [[[0.0, 0.16], [0.08, 0.16], ..., [69.04, 0.16], [69.12, 0.08]]
175
+
176
+ Returns:
177
+ ts (torch.tensor):
178
+ A tensor containing the scaled and rounded timestamps for each subsegment.
179
+ """
180
+ seg_ts = (torch.tensor(subsegments) * feat_per_sec).float()
181
+ ts_round = torch.round(seg_ts, decimals=decimals)
182
+ ts = ts_round.long()
183
+ ts[:, 1] = ts[:, 0] + ts[:, 1]
184
+ if max_end_ts is not None:
185
+ ts = np.clip(ts, 0, int(max_end_ts * feat_per_sec))
186
+ return ts
187
+
188
+
189
+ def extract_frame_info_from_rttm(offset, duration, rttm_lines, round_digits=3):
190
+ """
191
+ Extracts RTTM lines containing speaker labels, start time, and end time for a given audio segment.
192
+
193
+ Args:
194
+ uniq_id (str): Unique identifier for the audio file and corresponding RTTM file.
195
+ offset (float): The starting time offset for the segment of interest.
196
+ duration (float): The duration of the segment of interest.
197
+ rttm_lines (list): List of RTTM lines in string format.
198
+ round_digits (int, optional): Number of decimal places to round the start and end times. Defaults to 3.
199
+
200
+ Returns:
201
+ rttm_mat (tuple): A tuple containing lists of start times, end times, and speaker labels.
202
+ sess_to_global_spkids (dict): A mapping from session-specific speaker indices to global speaker identifiers.
203
+ """
204
+ rttm_stt, rttm_end = offset, offset + duration
205
+ stt_list, end_list, speaker_list, speaker_set = [], [], [], []
206
+ sess_to_global_spkids = dict()
207
+
208
+ for rttm_line in rttm_lines:
209
+ start, end, speaker = convert_rttm_line(rttm_line)
210
+
211
+ # Skip invalid RTTM lines where the start time is greater than the end time.
212
+ if start > end:
213
+ continue
214
+
215
+ # Check if the RTTM segment overlaps with the specified segment of interest.
216
+ if (end > rttm_stt and start < rttm_end) or (start < rttm_end and end > rttm_stt):
217
+ # Adjust the start and end times to fit within the segment of interest.
218
+ start, end = max(start, rttm_stt), min(end, rttm_end)
219
+ else:
220
+ continue
221
+
222
+ # Round the start and end times to the specified number of decimal places.
223
+ end_list.append(round(end, round_digits))
224
+ stt_list.append(round(start, round_digits))
225
+
226
+ # Assign a unique index to each speaker and maintain a mapping.
227
+ if speaker not in speaker_set:
228
+ speaker_set.append(speaker)
229
+ speaker_list.append(speaker_set.index(speaker))
230
+ sess_to_global_spkids.update({speaker_set.index(speaker): speaker})
231
+
232
+ rttm_mat = (stt_list, end_list, speaker_list)
233
+ return rttm_mat, sess_to_global_spkids
234
+
235
+
236
+ def get_frame_targets_from_rttm(
237
+ rttm_timestamps: list,
238
+ offset: float,
239
+ duration: float,
240
+ round_digits: int,
241
+ feat_per_sec: int,
242
+ max_spks: int,
243
+ ):
244
+ """
245
+ Create a multi-dimensional vector sequence containing speaker timestamp information in RTTM.
246
+ The unit-length is the frame shift length of the acoustic feature. The feature-level annotations
247
+ `feat_level_target` will later be converted to base-segment level diarization label.
248
+
249
+ Args:
250
+ rttm_timestamps (list):
251
+ List containing start and end time for each speaker segment label.
252
+ stt_list, end_list and speaker_list are contained.
253
+ feat_per_sec (int):
254
+ Number of feature frames per second.
255
+ This quantity is determined by window_stride variable in preprocessing module.
256
+ target_spks (tuple):
257
+ Speaker indices that are generated from combinations. If there are only one or two speakers,
258
+ only a single target_spks variable is generated.
259
+
260
+ Returns:
261
+ feat_level_target (torch.tensor):
262
+ Tensor containing label for each feature level frame.
263
+ """
264
+ stt_list, end_list, speaker_list = rttm_timestamps
265
+ sorted_speakers = sorted(list(set(speaker_list)))
266
+ total_fr_len = int(duration * feat_per_sec)
267
+ if len(sorted_speakers) > max_spks:
268
+ logging.warning(
269
+ f"Number of speakers in RTTM file {len(sorted_speakers)} exceeds the maximum number of speakers: "
270
+ f"{max_spks}! Only {max_spks} first speakers remain, and this will affect frame metrics!"
271
+ )
272
+ feat_level_target = torch.zeros(total_fr_len, max_spks)
273
+ for count, (stt, end, spk_rttm_key) in enumerate(zip(stt_list, end_list, speaker_list)):
274
+ if end < offset or stt > offset + duration:
275
+ continue
276
+ stt, end = max(offset, stt), min(offset + duration, end)
277
+ spk = spk_rttm_key
278
+ if spk < max_spks:
279
+ stt_fr, end_fr = int((stt - offset) * feat_per_sec), int((end - offset) * feat_per_sec)
280
+ feat_level_target[stt_fr:end_fr, spk] = 1
281
+ return feat_level_target
282
+
283
+
284
+ class _AudioMSDDTrainDataset(Dataset):
285
+ """
286
+ Dataset class that loads a json file containing paths to audio files,
287
+ RTTM files and number of speakers. This Dataset class is designed for
288
+ training or fine-tuning speaker embedding extractor and diarization decoder
289
+ at the same time.
290
+
291
+ Example:
292
+ {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2,
293
+ "rttm_filepath": "/path/to/diar_label_0.rttm}
294
+ ...
295
+ {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2,
296
+ "rttm_filepath": "/path/to/diar_label_n.rttm}
297
+
298
+ Args:
299
+ manifest_filepath (str):
300
+ Path to input manifest json files.
301
+ multiscale_args_dict (dict):
302
+ Dictionary containing the parameters for multiscale segmentation and clustering.
303
+ emb_dir (str):
304
+ Path to a temporary folder where segmentation information for embedding extraction is saved.
305
+ soft_label_thres (float):
306
+ Threshold that determines the label of each segment based on RTTM file information.
307
+ featurizer:
308
+ Featurizer instance for generating features from the raw waveform.
309
+ window_stride (float):
310
+ Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames.
311
+ emb_batch_size (int):
312
+ Number of embedding vectors that are trained with attached computational graphs.
313
+ pairwise_infer (bool):
314
+ This variable should be True if dataloader is created for an inference task.
315
+ random_flip (bool):
316
+ If True, the two labels and input signals are randomly flipped per every epoch while training.
317
+ """
318
+
319
+ @property
320
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
321
+ """Returns definitions of module output ports."""
322
+ output_types = {
323
+ "features": NeuralType(('B', 'T'), AudioSignal()),
324
+ "feature_length": NeuralType(('B'), LengthsType()),
325
+ "ms_seg_timestamps": NeuralType(('B', 'C', 'T', 'D'), LengthsType()),
326
+ "ms_seg_counts": NeuralType(('B', 'C'), LengthsType()),
327
+ "clus_label_index": NeuralType(('B', 'T'), LengthsType()),
328
+ "scale_mapping": NeuralType(('B', 'C', 'T'), LengthsType()),
329
+ "targets": NeuralType(('B', 'T', 'C'), ProbsType()),
330
+ }
331
+
332
+ return output_types
333
+
334
+ def __init__(
335
+ self,
336
+ *,
337
+ manifest_filepath: str,
338
+ multiscale_args_dict: str,
339
+ emb_dir: str,
340
+ soft_label_thres: float,
341
+ featurizer,
342
+ window_stride,
343
+ emb_batch_size,
344
+ pairwise_infer: bool,
345
+ random_flip: bool = True,
346
+ global_rank: int = 0,
347
+ ):
348
+ super().__init__()
349
+ self.collection = DiarizationSpeechLabel(
350
+ manifests_files=manifest_filepath.split(','),
351
+ emb_dict=None,
352
+ clus_label_dict=None,
353
+ pairwise_infer=pairwise_infer,
354
+ )
355
+ self.featurizer = featurizer
356
+ self.multiscale_args_dict = multiscale_args_dict
357
+ self.emb_dir = emb_dir
358
+ self.round_digits = 2
359
+ self.decim = 10**self.round_digits
360
+ self.soft_label_thres = soft_label_thres
361
+ self.pairwise_infer = pairwise_infer
362
+ self.max_spks = 2
363
+ self.frame_per_sec = int(1 / window_stride)
364
+ self.emb_batch_size = emb_batch_size
365
+ self.random_flip = random_flip
366
+ self.global_rank = global_rank
367
+ self.manifest_filepath = manifest_filepath
368
+ self.multiscale_timestamp_dict = prepare_split_data(
369
+ self.manifest_filepath,
370
+ self.emb_dir,
371
+ self.multiscale_args_dict,
372
+ self.global_rank,
373
+ )
374
+
375
+ def __len__(self):
376
+ return len(self.collection)
377
+
378
+ def assign_labels_to_longer_segs(self, uniq_id, base_scale_clus_label):
379
+ """
380
+ Assign the generated speaker labels from the base scale (the finest scale) to the longer scales.
381
+ This process is needed to get the cluster labels for each scale. The cluster labels are needed to
382
+ calculate the cluster-average speaker embedding for each scale.
383
+
384
+ Args:
385
+ uniq_id (str):
386
+ Unique sample ID for training.
387
+ base_scale_clus_label (torch.tensor):
388
+ Tensor variable containing the speaker labels for the base-scale segments.
389
+
390
+ Returns:
391
+ per_scale_clus_label (torch.tensor):
392
+ Tensor variable containing the speaker labels for each segment in each scale.
393
+ Note that the total length of the speaker label sequence differs over scale since
394
+ each scale has a different number of segments for the same session.
395
+
396
+ scale_mapping (torch.tensor):
397
+ Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the
398
+ multiscale embeddings to form an input matrix for the MSDD model.
399
+ """
400
+ per_scale_clus_label = []
401
+ self.scale_n = len(self.multiscale_timestamp_dict[uniq_id]['scale_dict'])
402
+ uniq_scale_mapping = get_scale_mapping_list(self.multiscale_timestamp_dict[uniq_id])
403
+ for scale_index in range(self.scale_n):
404
+ new_clus_label = []
405
+ scale_seq_len = len(self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_index]["time_stamps"])
406
+ for seg_idx in range(scale_seq_len):
407
+ if seg_idx in uniq_scale_mapping[scale_index]:
408
+ seg_clus_label = mode(base_scale_clus_label[uniq_scale_mapping[scale_index] == seg_idx])
409
+ else:
410
+ seg_clus_label = 0 if len(new_clus_label) == 0 else new_clus_label[-1]
411
+ new_clus_label.append(seg_clus_label)
412
+ per_scale_clus_label.extend(new_clus_label)
413
+ per_scale_clus_label = torch.tensor(per_scale_clus_label)
414
+ return per_scale_clus_label, uniq_scale_mapping
415
+
416
+ def get_diar_target_labels(self, uniq_id, sample, fr_level_target):
417
+ """
418
+ Convert frame-level diarization target variable into segment-level target variable.
419
+ Since the granularity is reduced from frame level (10ms) to segment level (100ms~500ms),
420
+ we need a threshold value, `soft_label_thres`, which determines the label of each segment
421
+ based on the overlap between a segment range (start and end time) and the frame-level target variable.
422
+
423
+ Args:
424
+ uniq_id (str):
425
+ Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file.
426
+ sample:
427
+ `DiarizationSpeechLabel` instance containing sample information such as
428
+ audio filepath and RTTM filepath.
429
+ fr_level_target (torch.tensor):
430
+ Tensor containing label for each feature-level frame.
431
+
432
+ Returns:
433
+ seg_target (torch.tensor):
434
+ Tensor containing binary speaker labels for base-scale segments.
435
+ base_clus_label (torch.tensor):
436
+ Representative speaker label for each segment. This variable only has one speaker label
437
+ for each base-scale segment.
438
+ -1 means that there is no corresponding speaker in the target_spks tuple.
439
+ """
440
+ seg_target_list, base_clus_label = [], []
441
+ self.scale_n = len(self.multiscale_timestamp_dict[uniq_id]['scale_dict'])
442
+ subseg_time_stamp_list = self.multiscale_timestamp_dict[uniq_id]["scale_dict"][self.scale_n - 1]["time_stamps"]
443
+ for seg_stt, seg_end in subseg_time_stamp_list:
444
+ seg_stt_fr, seg_end_fr = int(seg_stt * self.frame_per_sec), int(seg_end * self.frame_per_sec)
445
+ soft_label_vec_sess = torch.sum(fr_level_target[seg_stt_fr:seg_end_fr, :], axis=0) / (
446
+ seg_end_fr - seg_stt_fr
447
+ )
448
+ label_int_sess = torch.argmax(soft_label_vec_sess)
449
+ soft_label_vec = soft_label_vec_sess.unsqueeze(0)[:, sample.target_spks].squeeze()
450
+ if label_int_sess in sample.target_spks and torch.sum(soft_label_vec_sess) > 0:
451
+ label_int = sample.target_spks.index(label_int_sess)
452
+ else:
453
+ label_int = -1
454
+ label_vec = (soft_label_vec > self.soft_label_thres).float()
455
+ seg_target_list.append(label_vec.detach())
456
+ base_clus_label.append(label_int)
457
+ seg_target = torch.stack(seg_target_list)
458
+ base_clus_label = torch.tensor(base_clus_label)
459
+ return seg_target, base_clus_label
460
+
461
+ def parse_rttm_for_ms_targets(self, sample):
462
+ """
463
+ Generate target tensor variable by extracting groundtruth diarization labels from an RTTM file.
464
+ This function converts (start, end, speaker_id) format into base-scale (the finest scale) segment level
465
+ diarization label in a matrix form.
466
+
467
+ Example of seg_target:
468
+ [[0., 1.], [0., 1.], [1., 1.], [1., 0.], [1., 0.], ..., [0., 1.]]
469
+
470
+ Args:
471
+ sample:
472
+ `DiarizationSpeechLabel` instance containing sample information such as
473
+ audio filepath and RTTM filepath.
474
+ target_spks (tuple):
475
+ Speaker indices that are generated from combinations. If there are only one or two speakers,
476
+ only a single target_spks tuple is generated.
477
+
478
+ Returns:
479
+ clus_label_index (torch.tensor):
480
+ Groundtruth clustering label (cluster index for each segment) from RTTM files for training purpose.
481
+ seg_target (torch.tensor):
482
+ Tensor variable containing hard-labels of speaker activity in each base-scale segment.
483
+ scale_mapping (torch.tensor):
484
+ Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the
485
+ multiscale embeddings to form an input matrix for the MSDD model.
486
+
487
+ """
488
+ with open(sample.rttm_file, 'r') as file:
489
+ rttm_lines = file.readlines()
490
+ uniq_id = self.get_uniq_id_with_range(sample)
491
+ rttm_timestamps = extract_seg_info_from_rttm(rttm_lines)
492
+ fr_level_target = assign_frame_level_spk_vector(
493
+ rttm_timestamps, self.round_digits, self.frame_per_sec, target_spks=sample.target_spks
494
+ )
495
+ seg_target, base_clus_label = self.get_diar_target_labels(uniq_id, sample, fr_level_target)
496
+ clus_label_index, scale_mapping = self.assign_labels_to_longer_segs(uniq_id, base_clus_label)
497
+ return clus_label_index, seg_target, scale_mapping
498
+
499
+ def get_uniq_id_with_range(self, sample, deci=3):
500
+ """
501
+ Generate unique training sample ID from unique file ID, offset and duration. The start-end time added
502
+ unique ID is required for identifying the sample since multiple short audio samples are generated from a single
503
+ audio file. The start time and end time of the audio stream uses millisecond units if `deci=3`.
504
+
505
+ Args:
506
+ sample:
507
+ `DiarizationSpeechLabel` instance from collections.
508
+
509
+ Returns:
510
+ uniq_id (str):
511
+ Unique sample ID which includes start and end time of the audio stream.
512
+ Example: abc1001_3122_6458
513
+
514
+ """
515
+ bare_uniq_id = os.path.splitext(os.path.basename(sample.rttm_file))[0]
516
+ offset = str(int(round(sample.offset, deci) * pow(10, deci)))
517
+ endtime = str(int(round(sample.offset + sample.duration, deci) * pow(10, deci)))
518
+ uniq_id = f"{bare_uniq_id}_{offset}_{endtime}"
519
+ return uniq_id
520
+
521
+ def get_ms_seg_timestamps(self, sample):
522
+ """
523
+ Get start and end time of each diarization frame.
524
+
525
+ Args:
526
+ sample:
527
+ `DiarizationSpeechLabel` instance from preprocessing.collections
528
+ Returns:
529
+ ms_seg_timestamps (torch.tensor):
530
+ Tensor containing timestamps for each frame.
531
+ ms_seg_counts (torch.tensor):
532
+ Number of segments for each scale. This information is used for reshaping embedding batch
533
+ during forward propagation.
534
+ """
535
+ uniq_id = self.get_uniq_id_with_range(sample)
536
+ ms_seg_timestamps_list = []
537
+ max_seq_len = len(self.multiscale_timestamp_dict[uniq_id]["scale_dict"][self.scale_n - 1]["time_stamps"])
538
+ ms_seg_counts = [0 for _ in range(self.scale_n)]
539
+ for scale_idx in range(self.scale_n):
540
+ scale_ts_list = []
541
+ for k, (seg_stt, seg_end) in enumerate(
542
+ self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_idx]["time_stamps"]
543
+ ):
544
+ stt, end = (
545
+ int((seg_stt - sample.offset) * self.frame_per_sec),
546
+ int((seg_end - sample.offset) * self.frame_per_sec),
547
+ )
548
+ scale_ts_list.append(torch.tensor([stt, end]).detach())
549
+ ms_seg_counts[scale_idx] = len(
550
+ self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_idx]["time_stamps"]
551
+ )
552
+ scale_ts = torch.stack(scale_ts_list)
553
+ scale_ts_padded = torch.cat([scale_ts, torch.zeros(max_seq_len - len(scale_ts_list), 2)], dim=0)
554
+ ms_seg_timestamps_list.append(scale_ts_padded.detach())
555
+ ms_seg_timestamps = torch.stack(ms_seg_timestamps_list)
556
+ ms_seg_counts = torch.tensor(ms_seg_counts)
557
+ return ms_seg_timestamps, ms_seg_counts
558
+
559
+ def __getitem__(self, index):
560
+ sample = self.collection[index]
561
+ if sample.offset is None:
562
+ sample.offset = 0
563
+ clus_label_index, targets, scale_mapping = self.parse_rttm_for_ms_targets(sample)
564
+ features = self.featurizer.process(sample.audio_file, offset=sample.offset, duration=sample.duration)
565
+ feature_length = torch.tensor(features.shape[0]).long()
566
+ ms_seg_timestamps, ms_seg_counts = self.get_ms_seg_timestamps(sample)
567
+ if self.random_flip:
568
+ torch.manual_seed(index)
569
+ flip = torch.cat([torch.randperm(self.max_spks), torch.tensor(-1).unsqueeze(0)])
570
+ clus_label_index, targets = flip[clus_label_index], targets[:, flip[: self.max_spks]]
571
+ return features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets
572
+
573
+
574
+ class _AudioMSDDInferDataset(Dataset):
575
+ """
576
+ Dataset class that loads a json file containing paths to audio files,
577
+ RTTM files and number of speakers. This Dataset class is built for diarization inference and
578
+ evaluation. Speaker embedding sequences, segment timestamps, cluster-average speaker embeddings
579
+ are loaded from memory and fed into the dataloader.
580
+
581
+ Example:
582
+ {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2,
583
+ "rttm_filepath": "/path/to/diar_label_0.rttm}
584
+ ...
585
+ {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2,
586
+ "rttm_filepath": "/path/to/diar_label_n.rttm}
587
+
588
+ Args:
589
+ manifest_filepath (str):
590
+ Path to input manifest json files.
591
+ emb_dict (dict):
592
+ Dictionary containing cluster-average embeddings and speaker mapping information.
593
+ emb_seq (dict):
594
+ Dictionary containing multiscale speaker embedding sequence,
595
+ scale mapping and corresponding segment timestamps.
596
+ clus_label_dict (dict):
597
+ Subsegment-level (from base-scale) speaker labels from clustering results.
598
+ soft_label_thres (float):
599
+ A threshold that determines the label of each segment based on RTTM file information.
600
+ featurizer:
601
+ Featurizer instance for generating features from raw waveform.
602
+ seq_eval_mode (bool):
603
+ If True, F1 score will be calculated for each speaker pair during inference mode.
604
+ window_stride (float):
605
+ Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames.
606
+ use_single_scale_clus (bool):
607
+ Use only one scale for clustering instead of using multiple scales of embeddings for clustering.
608
+ pairwise_infer (bool):
609
+ This variable should be True if dataloader is created for an inference task.
610
+ """
611
+
612
+ @property
613
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
614
+ """Returns definitions of module output ports."""
615
+ output_types = OrderedDict(
616
+ {
617
+ "ms_emb_seq": NeuralType(('B', 'T', 'C', 'D'), SpectrogramType()),
618
+ "length": NeuralType(tuple('B'), LengthsType()),
619
+ "ms_avg_embs": NeuralType(('B', 'C', 'D', 'C'), EncodedRepresentation()),
620
+ "targets": NeuralType(('B', 'T', 'C'), ProbsType()),
621
+ }
622
+ )
623
+ return output_types
624
+
625
+ def __init__(
626
+ self,
627
+ *,
628
+ manifest_filepath: str,
629
+ emb_dict: Dict,
630
+ emb_seq: Dict,
631
+ clus_label_dict: Dict,
632
+ soft_label_thres: float,
633
+ seq_eval_mode: bool,
634
+ window_stride: float,
635
+ use_single_scale_clus: bool,
636
+ pairwise_infer: bool,
637
+ ):
638
+ super().__init__()
639
+ self.collection = DiarizationSpeechLabel(
640
+ manifests_files=manifest_filepath.split(','),
641
+ emb_dict=emb_dict,
642
+ clus_label_dict=clus_label_dict,
643
+ seq_eval_mode=seq_eval_mode,
644
+ pairwise_infer=pairwise_infer,
645
+ )
646
+ self.emb_dict = emb_dict
647
+ self.emb_seq = emb_seq
648
+ self.clus_label_dict = clus_label_dict
649
+ self.round_digits = 2
650
+ self.decim = 10**self.round_digits
651
+ self.frame_per_sec = int(1 / window_stride)
652
+ self.soft_label_thres = soft_label_thres
653
+ self.pairwise_infer = pairwise_infer
654
+ self.max_spks = 2
655
+ self.use_single_scale_clus = use_single_scale_clus
656
+ self.seq_eval_mode = seq_eval_mode
657
+
658
+ def __len__(self):
659
+ return len(self.collection)
660
+
661
+ def parse_rttm_multiscale(self, sample):
662
+ """
663
+ Generate target tensor variable by extracting groundtruth diarization labels from an RTTM file.
664
+ This function is only used when ``self.seq_eval_mode=True`` and RTTM files are provided. This function converts
665
+ (start, end, speaker_id) format into base-scale (the finest scale) segment level diarization label in a matrix
666
+ form to create target matrix.
667
+
668
+ Args:
669
+ sample:
670
+ DiarizationSpeechLabel instance containing sample information such as audio filepath and RTTM filepath.
671
+ target_spks (tuple):
672
+ Two Indices of targeted speakers for evaluation.
673
+ Example of target_spks: (2, 3)
674
+ Returns:
675
+ seg_target (torch.tensor):
676
+ Tensor variable containing hard-labels of speaker activity in each base-scale segment.
677
+ """
678
+ if sample.rttm_file is None:
679
+ raise ValueError(f"RTTM file is not provided for this sample {sample}")
680
+ rttm_lines = open(sample.rttm_file).readlines()
681
+ uniq_id = os.path.splitext(os.path.basename(sample.rttm_file))[0]
682
+ mapping_dict = self.emb_dict[max(self.emb_dict.keys())][uniq_id]['mapping']
683
+ rttm_timestamps = extract_seg_info_from_rttm(rttm_lines, mapping_dict, sample.target_spks)
684
+ fr_level_target = assign_frame_level_spk_vector(
685
+ rttm_timestamps, self.round_digits, self.frame_per_sec, sample.target_spks
686
+ )
687
+ seg_target = self.get_diar_target_labels_from_fr_target(uniq_id, fr_level_target)
688
+ return seg_target
689
+
690
+ def get_diar_target_labels_from_fr_target(self, uniq_id: str, fr_level_target: torch.Tensor) -> torch.Tensor:
691
+ """
692
+ Generate base-scale level binary diarization label from frame-level target matrix. For the given frame-level
693
+ speaker target matrix fr_level_target, we count the number of frames that belong to each speaker and calculate
694
+ ratios for each speaker into the `soft_label_vec` variable. Finally, `soft_label_vec` variable is compared
695
+ with `soft_label_thres` to determine whether a label vector should contain 0 or 1 for each speaker bin.
696
+ Note that seg_target variable has dimension of (number of base-scale segments x 2) dimension.
697
+
698
+ Example of seg_target:
699
+ [[0., 1.], [0., 1.], [1., 1.], [1., 0.], [1., 0.], ..., [0., 1.]]
700
+
701
+ Args:
702
+ uniq_id (str):
703
+ Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file.
704
+ fr_level_target (torch.tensor):
705
+ frame-level binary speaker annotation (1: exist 0: non-exist) generated from RTTM file.
706
+
707
+ Returns:
708
+ seg_target (torch.tensor):
709
+ Tensor variable containing binary hard-labels of speaker activity in each base-scale segment.
710
+
711
+ """
712
+ if fr_level_target is None:
713
+ return None
714
+ else:
715
+ seg_target_list = []
716
+ for seg_stt, seg_end, label_int in self.clus_label_dict[uniq_id]:
717
+ seg_stt_fr, seg_end_fr = int(seg_stt * self.frame_per_sec), int(seg_end * self.frame_per_sec)
718
+ soft_label_vec = torch.sum(fr_level_target[seg_stt_fr:seg_end_fr, :], axis=0) / (
719
+ seg_end_fr - seg_stt_fr
720
+ )
721
+ label_vec = (soft_label_vec > self.soft_label_thres).int()
722
+ seg_target_list.append(label_vec)
723
+ seg_target = torch.stack(seg_target_list)
724
+ return seg_target
725
+
726
+ def __getitem__(self, index):
727
+ sample = self.collection[index]
728
+ if sample.offset is None:
729
+ sample.offset = 0
730
+
731
+ uniq_id = os.path.splitext(os.path.basename(sample.audio_file))[0]
732
+ scale_n = len(self.emb_dict.keys())
733
+ _avg_embs = torch.stack([self.emb_dict[scale_index][uniq_id]['avg_embs'] for scale_index in range(scale_n)])
734
+
735
+ if self.pairwise_infer:
736
+ avg_embs = _avg_embs[:, :, self.collection[index].target_spks]
737
+ else:
738
+ avg_embs = _avg_embs
739
+
740
+ if avg_embs.shape[2] > self.max_spks:
741
+ raise ValueError(
742
+ f" avg_embs.shape[2] {avg_embs.shape[2]} should be less than or equal to "
743
+ f"self.max_num_speakers {self.max_spks}"
744
+ )
745
+
746
+ feats = []
747
+ for scale_index in range(scale_n):
748
+ repeat_mat = self.emb_seq["session_scale_mapping"][uniq_id][scale_index]
749
+ feats.append(self.emb_seq[scale_index][uniq_id][repeat_mat, :])
750
+ feats_out = torch.stack(feats).permute(1, 0, 2)
751
+ feats_len = feats_out.shape[0]
752
+
753
+ if self.seq_eval_mode:
754
+ targets = self.parse_rttm_multiscale(sample)
755
+ else:
756
+ targets = torch.zeros(feats_len, 2).float()
757
+
758
+ return feats_out, feats_len, targets, avg_embs
759
+
760
+
761
+ def _msdd_train_collate_fn(self, batch):
762
+ """
763
+ Collate batch of variables that are needed for raw waveform to diarization label training.
764
+ The following variables are included in training/validation batch:
765
+
766
+ Args:
767
+ batch (tuple):
768
+ Batch tuple containing the variables for the diarization training.
769
+ Returns:
770
+ features (torch.tensor):
771
+ Raw waveform samples (time series) loaded from the audio_filepath in the input manifest file.
772
+ feature lengths (time series sample length):
773
+ A list of lengths of the raw waveform samples.
774
+ ms_seg_timestamps (torch.tensor):
775
+ Matrix containing the start time and end time (timestamps) for each segment and each scale.
776
+ ms_seg_timestamps is needed for extracting acoustic features from raw waveforms.
777
+ ms_seg_counts (torch.tensor):
778
+ Matrix containing The number of segments for each scale. ms_seg_counts is necessary for reshaping
779
+ the input matrix for the MSDD model.
780
+ clus_label_index (torch.tensor):
781
+ Groundtruth Clustering label (cluster index for each segment) from RTTM files for training purpose.
782
+ clus_label_index is necessary for calculating cluster-average embedding.
783
+ scale_mapping (torch.tensor):
784
+ Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the
785
+ multiscale embeddings to form an input matrix for the MSDD model.
786
+ targets (torch.tensor):
787
+ Groundtruth Speaker label for the given input embedding sequence.
788
+ """
789
+ packed_batch = list(zip(*batch))
790
+ features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets = packed_batch
791
+ features_list, feature_length_list = [], []
792
+ ms_seg_timestamps_list, ms_seg_counts_list, scale_clus_label_list, scale_mapping_list, targets_list = (
793
+ [],
794
+ [],
795
+ [],
796
+ [],
797
+ [],
798
+ )
799
+
800
+ max_raw_feat_len = max([x.shape[0] for x in features])
801
+ max_target_len = max([x.shape[0] for x in targets])
802
+ max_total_seg_len = max([x.shape[0] for x in clus_label_index])
803
+
804
+ for feat, feat_len, ms_seg_ts, ms_seg_ct, scale_clus, scl_map, tgt in batch:
805
+ seq_len = tgt.shape[0]
806
+ pad_feat = (0, max_raw_feat_len - feat_len)
807
+ pad_tgt = (0, 0, 0, max_target_len - seq_len)
808
+ pad_sm = (0, max_target_len - seq_len)
809
+ pad_ts = (0, 0, 0, max_target_len - seq_len)
810
+ pad_sc = (0, max_total_seg_len - scale_clus.shape[0])
811
+ padded_feat = torch.nn.functional.pad(feat, pad_feat)
812
+ padded_tgt = torch.nn.functional.pad(tgt, pad_tgt)
813
+ padded_sm = torch.nn.functional.pad(scl_map, pad_sm)
814
+ padded_ms_seg_ts = torch.nn.functional.pad(ms_seg_ts, pad_ts)
815
+ padded_scale_clus = torch.nn.functional.pad(scale_clus, pad_sc)
816
+
817
+ features_list.append(padded_feat)
818
+ feature_length_list.append(feat_len.clone().detach())
819
+ ms_seg_timestamps_list.append(padded_ms_seg_ts)
820
+ ms_seg_counts_list.append(ms_seg_ct.clone().detach())
821
+ scale_clus_label_list.append(padded_scale_clus)
822
+ scale_mapping_list.append(padded_sm)
823
+ targets_list.append(padded_tgt)
824
+
825
+ features = torch.stack(features_list)
826
+ feature_length = torch.stack(feature_length_list)
827
+ ms_seg_timestamps = torch.stack(ms_seg_timestamps_list)
828
+ clus_label_index = torch.stack(scale_clus_label_list)
829
+ ms_seg_counts = torch.stack(ms_seg_counts_list)
830
+ scale_mapping = torch.stack(scale_mapping_list)
831
+ targets = torch.stack(targets_list)
832
+ return features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets
833
+
834
+
835
+ def _msdd_infer_collate_fn(self, batch):
836
+ """
837
+ Collate batch of feats (speaker embeddings), feature lengths, target label sequences
838
+ and cluster-average embeddings.
839
+
840
+ Args:
841
+ batch (tuple):
842
+ Batch tuple containing feats, feats_len, targets and ms_avg_embs.
843
+ Returns:
844
+ feats (torch.tensor):
845
+ Collated speaker embedding with unified length.
846
+ feats_len (torch.tensor):
847
+ The actual length of each embedding sequence without zero padding.
848
+ targets (torch.tensor):
849
+ Groundtruth Speaker label for the given input embedding sequence.
850
+ ms_avg_embs (torch.tensor):
851
+ Cluster-average speaker embedding vectors.
852
+ """
853
+
854
+ packed_batch = list(zip(*batch))
855
+ feats, feats_len, targets, ms_avg_embs = packed_batch
856
+ feats_list, flen_list, targets_list, ms_avg_embs_list = [], [], [], []
857
+ max_audio_len = max(feats_len)
858
+ max_target_len = max([x.shape[0] for x in targets])
859
+
860
+ for feature, feat_len, target, ivector in batch:
861
+ flen_list.append(feat_len)
862
+ ms_avg_embs_list.append(ivector)
863
+ if feat_len < max_audio_len:
864
+ pad_a = (0, 0, 0, 0, 0, max_audio_len - feat_len)
865
+ pad_t = (0, 0, 0, max_target_len - target.shape[0])
866
+ padded_feature = torch.nn.functional.pad(feature, pad_a)
867
+ padded_target = torch.nn.functional.pad(target, pad_t)
868
+ feats_list.append(padded_feature)
869
+ targets_list.append(padded_target)
870
+ else:
871
+ targets_list.append(target.clone().detach())
872
+ feats_list.append(feature.clone().detach())
873
+
874
+ feats = torch.stack(feats_list)
875
+ feats_len = torch.tensor(flen_list)
876
+ targets = torch.stack(targets_list)
877
+ ms_avg_embs = torch.stack(ms_avg_embs_list)
878
+ return feats, feats_len, targets, ms_avg_embs
879
+
880
+
881
+ class AudioToSpeechMSDDTrainDataset(_AudioMSDDTrainDataset):
882
+ """
883
+ Dataset class that loads a json file containing paths to audio files,
884
+ rttm files and number of speakers. This Dataset class is designed for
885
+ training or fine-tuning speaker embedding extractor and diarization decoder
886
+ at the same time.
887
+
888
+ Example:
889
+ {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2,
890
+ "rttm_filepath": "/path/to/diar_label_0.rttm}
891
+ ...
892
+ {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2,
893
+ "rttm_filepath": "/path/to/diar_label_n.rttm}
894
+
895
+ Args:
896
+ manifest_filepath (str):
897
+ Path to input manifest json files.
898
+ multiscale_args_dict (dict):
899
+ Dictionary containing the parameters for multiscale segmentation and clustering.
900
+ emb_dir (str):
901
+ Path to a temporary folder where segmentation information for embedding extraction is saved.
902
+ soft_label_thres (float):
903
+ A threshold that determines the label of each segment based on RTTM file information.
904
+ featurizer:
905
+ Featurizer instance for generating features from the raw waveform.
906
+ window_stride (float):
907
+ Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames.
908
+ emb_batch_size (int):
909
+ Number of embedding vectors that are trained with attached computational graphs.
910
+ pairwise_infer (bool):
911
+ This variable should be True if dataloader is created for an inference task.
912
+ """
913
+
914
+ def __init__(
915
+ self,
916
+ *,
917
+ manifest_filepath: str,
918
+ multiscale_args_dict: Dict,
919
+ emb_dir: str,
920
+ soft_label_thres: float,
921
+ featurizer,
922
+ window_stride,
923
+ emb_batch_size,
924
+ pairwise_infer: bool,
925
+ global_rank: int,
926
+ ):
927
+ super().__init__(
928
+ manifest_filepath=manifest_filepath,
929
+ multiscale_args_dict=multiscale_args_dict,
930
+ emb_dir=emb_dir,
931
+ soft_label_thres=soft_label_thres,
932
+ featurizer=featurizer,
933
+ window_stride=window_stride,
934
+ emb_batch_size=emb_batch_size,
935
+ pairwise_infer=pairwise_infer,
936
+ global_rank=global_rank,
937
+ )
938
+
939
+ def msdd_train_collate_fn(self, batch):
940
+ """Collate batch of audio features, feature lengths, target label sequences for training."""
941
+ return _msdd_train_collate_fn(self, batch)
942
+
943
+
944
+ class AudioToSpeechMSDDInferDataset(_AudioMSDDInferDataset):
945
+ """
946
+ Dataset class that loads a json file containing paths to audio files,
947
+ rttm files and number of speakers. The created labels are used for diarization inference.
948
+
949
+ Example:
950
+ {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2,
951
+ "rttm_filepath": "/path/to/diar_label_0.rttm}
952
+ ...
953
+ {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2,
954
+ "rttm_filepath": "/path/to/diar_label_n.rttm}
955
+
956
+ Args:
957
+ manifest_filepath (str):
958
+ Path to input manifest json files.
959
+ emb_dict (dict):
960
+ Dictionary containing cluster-average embeddings and speaker mapping information.
961
+ emb_seq (dict):
962
+ Dictionary containing multiscale speaker embedding sequence, scale mapping
963
+ and corresponding segment timestamps.
964
+ clus_label_dict (dict):
965
+ Subsegment-level (from base-scale) speaker labels from clustering results.
966
+ soft_label_thres (float):
967
+ Threshold that determines speaker labels of segments depending on the overlap
968
+ with groundtruth speaker timestamps.
969
+ featurizer:
970
+ Featurizer instance for generating features from raw waveform.
971
+ use_single_scale_clus (bool):
972
+ Use only one scale for clustering instead of using multiple scales of embeddings for clustering.
973
+ seq_eval_mode (bool):
974
+ If True, F1 score will be calculated for each speaker pair during inference mode.
975
+ window_stride (float):
976
+ Window stride for acoustic feature. This value is used for calculating the numbers of
977
+ feature-level frames.
978
+ pairwise_infer (bool):
979
+ If True, this Dataset class operates in inference mode. In inference mode, a set of speakers
980
+ in the input audio is split into multiple pairs of speakers and speaker tuples
981
+ (e.g. 3 speakers: [(0,1), (1,2), (0,2)]) and then fed into the MSDD to merge the individual results.
982
+ """
983
+
984
+ def __init__(
985
+ self,
986
+ *,
987
+ manifest_filepath: str,
988
+ emb_dict: Dict,
989
+ emb_seq: Dict,
990
+ clus_label_dict: Dict,
991
+ soft_label_thres: float,
992
+ use_single_scale_clus: bool,
993
+ seq_eval_mode: bool,
994
+ window_stride: float,
995
+ pairwise_infer: bool,
996
+ ):
997
+ super().__init__(
998
+ manifest_filepath=manifest_filepath,
999
+ emb_dict=emb_dict,
1000
+ emb_seq=emb_seq,
1001
+ clus_label_dict=clus_label_dict,
1002
+ soft_label_thres=soft_label_thres,
1003
+ use_single_scale_clus=use_single_scale_clus,
1004
+ window_stride=window_stride,
1005
+ seq_eval_mode=seq_eval_mode,
1006
+ pairwise_infer=pairwise_infer,
1007
+ )
1008
+
1009
+ def msdd_infer_collate_fn(self, batch):
1010
+ """Collate batch of audio features, feature lengths, target label sequences for inference."""
1011
+ return _msdd_infer_collate_fn(self, batch)
1012
+
1013
+
1014
+ class _AudioToSpeechE2ESpkDiarDataset(Dataset):
1015
+ """
1016
+ Dataset class that loads a json file containing paths to audio files,
1017
+ RTTM files and number of speakers. This Dataset class is designed for
1018
+ training or fine-tuning speaker embedding extractor and diarization decoder
1019
+ at the same time.
1020
+
1021
+ Example:
1022
+ {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2,
1023
+ "rttm_filepath": "/path/to/diar_label_0.rttm}
1024
+ ...
1025
+ {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2,
1026
+ "rttm_filepath": "/path/to/diar_label_n.rttm}
1027
+
1028
+ Args:
1029
+ manifest_filepath (str):
1030
+ Path to input manifest json files.
1031
+ multiargs_dict (dict):
1032
+ Dictionary containing the parameters for multiscale segmentation and clustering.
1033
+ soft_label_thres (float):
1034
+ Threshold that determines the label of each segment based on RTTM file information.
1035
+ featurizer:
1036
+ Featurizer instance for generating audio_signal from the raw waveform.
1037
+ window_stride (float):
1038
+ Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames.
1039
+ """
1040
+
1041
+ @property
1042
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
1043
+ """Returns definitions of module output ports."""
1044
+ output_types = {
1045
+ "audio_signal": NeuralType(('B', 'T'), AudioSignal()),
1046
+ "audio_length": NeuralType(('B'), LengthsType()),
1047
+ "targets": NeuralType(('B', 'T', 'C'), ProbsType()),
1048
+ "target_len": NeuralType(('B'), LengthsType()),
1049
+ }
1050
+
1051
+ return output_types
1052
+
1053
+ def __init__(
1054
+ self,
1055
+ *,
1056
+ manifest_filepath: str,
1057
+ soft_label_thres: float,
1058
+ session_len_sec: float,
1059
+ num_spks: int,
1060
+ featurizer,
1061
+ window_stride: float,
1062
+ min_subsegment_duration: float = 0.03,
1063
+ global_rank: int = 0,
1064
+ dtype=torch.float16,
1065
+ round_digits: int = 2,
1066
+ soft_targets: bool = False,
1067
+ subsampling_factor: int = 8,
1068
+ device: str = 'cpu',
1069
+ ):
1070
+ super().__init__()
1071
+ self.collection = EndtoEndDiarizationSpeechLabel(
1072
+ manifests_files=manifest_filepath.split(','),
1073
+ round_digits=round_digits,
1074
+ )
1075
+ self.featurizer = featurizer
1076
+ self.round_digits = round_digits
1077
+ self.feat_per_sec = int(1 / window_stride)
1078
+ self.diar_frame_length = round(subsampling_factor * window_stride, round_digits)
1079
+ self.session_len_sec = session_len_sec
1080
+ self.soft_label_thres = soft_label_thres
1081
+ self.max_spks = num_spks
1082
+ self.min_subsegment_duration = min_subsegment_duration
1083
+ self.dtype = dtype
1084
+ self.use_asr_style_frame_count = True
1085
+ self.soft_targets = soft_targets
1086
+ self.round_digits = 2
1087
+ self.floor_decimal = 10**self.round_digits
1088
+ self.device = device
1089
+
1090
+ def __len__(self):
1091
+ return len(self.collection)
1092
+
1093
+ def get_uniq_id_with_range(self, sample, deci=3):
1094
+ """
1095
+ Generate unique training sample ID from unique file ID, offset and duration. The start-end time added
1096
+ unique ID is required for identifying the sample since multiple short audio samples are generated from a single
1097
+ audio file. The start time and end time of the audio stream uses millisecond units if `deci=3`.
1098
+
1099
+ Args:
1100
+ sample:
1101
+ `DiarizationSpeechLabel` instance from collections.
1102
+
1103
+ Returns:
1104
+ uniq_id (str):
1105
+ Unique sample ID which includes start and end time of the audio stream.
1106
+ Example: abc1001_3122_6458
1107
+ """
1108
+ bare_uniq_id = os.path.splitext(os.path.basename(sample.rttm_file))[0]
1109
+ offset = str(int(round(sample.offset, deci) * pow(10, deci)))
1110
+ endtime = str(int(round(sample.offset + sample.duration, deci) * pow(10, deci)))
1111
+ uniq_id = f"{bare_uniq_id}_{offset}_{endtime}"
1112
+ return uniq_id
1113
+
1114
+ def parse_rttm_for_targets_and_lens(self, rttm_file, offset, duration, target_len):
1115
+ """
1116
+ Generate target tensor variable by extracting groundtruth diarization labels from an RTTM file.
1117
+ This function converts (start, end, speaker_id) format into base-scale (the finest scale) segment level
1118
+ diarization label in a matrix form.
1119
+
1120
+ Example of seg_target:
1121
+ [[0., 1.], [0., 1.], [1., 1.], [1., 0.], [1., 0.], ..., [0., 1.]]
1122
+ """
1123
+ if rttm_file in [None, '']:
1124
+ num_seg = torch.max(target_len)
1125
+ targets = torch.zeros(num_seg, self.max_spks)
1126
+ return targets
1127
+
1128
+ with open(rttm_file, 'r') as f:
1129
+ rttm_lines = f.readlines()
1130
+
1131
+ rttm_timestamps, sess_to_global_spkids = extract_frame_info_from_rttm(offset, duration, rttm_lines)
1132
+
1133
+ fr_level_target = get_frame_targets_from_rttm(
1134
+ rttm_timestamps=rttm_timestamps,
1135
+ offset=offset,
1136
+ duration=duration,
1137
+ round_digits=self.round_digits,
1138
+ feat_per_sec=self.feat_per_sec,
1139
+ max_spks=self.max_spks,
1140
+ )
1141
+
1142
+ soft_target_seg = self.get_soft_targets_seg(feat_level_target=fr_level_target, target_len=target_len)
1143
+ if self.soft_targets:
1144
+ step_target = soft_target_seg
1145
+ else:
1146
+ step_target = (soft_target_seg >= self.soft_label_thres).float()
1147
+ return step_target
1148
+
1149
+ def get_soft_targets_seg(self, feat_level_target, target_len):
1150
+ """
1151
+ Generate the final targets for the actual diarization step.
1152
+ Here, frame level means step level which is also referred to as segments.
1153
+ We follow the original paper and refer to the step level as "frames".
1154
+
1155
+ Args:
1156
+ feat_level_target (torch.tensor):
1157
+ Tensor variable containing hard-labels of speaker activity in each feature-level segment.
1158
+ target_len (torch.tensor):
1159
+ Numbers of ms segments
1160
+
1161
+ Returns:
1162
+ soft_target_seg (torch.tensor):
1163
+ Tensor variable containing soft-labels of speaker activity in each step-level segment.
1164
+ """
1165
+ num_seg = torch.max(target_len)
1166
+ targets = torch.zeros(num_seg, self.max_spks)
1167
+ stride = int(self.feat_per_sec * self.diar_frame_length)
1168
+ for index in range(num_seg):
1169
+ if index == 0:
1170
+ seg_stt_feat = 0
1171
+ else:
1172
+ seg_stt_feat = stride * index - 1 - int(stride / 2)
1173
+ if index == num_seg - 1:
1174
+ seg_end_feat = feat_level_target.shape[0]
1175
+ else:
1176
+ seg_end_feat = stride * index - 1 + int(stride / 2)
1177
+ targets[index] = torch.mean(feat_level_target[seg_stt_feat : seg_end_feat + 1, :], axis=0)
1178
+ return targets
1179
+
1180
+ def get_segment_timestamps(
1181
+ self,
1182
+ duration: float,
1183
+ offset: float = 0,
1184
+ sample_rate: int = 16000,
1185
+ ):
1186
+ """
1187
+ Get start and end time of segments in each scale.
1188
+
1189
+ Args:
1190
+ sample:
1191
+ `DiarizationSpeechLabel` instance from preprocessing.collections
1192
+ Returns:
1193
+ segment_timestamps (torch.tensor):
1194
+ Tensor containing Multiscale segment timestamps.
1195
+ target_len (torch.tensor):
1196
+ Number of segments for each scale. This information is used for reshaping embedding batch
1197
+ during forward propagation.
1198
+ """
1199
+ subsegments = get_subsegments(
1200
+ offset=offset,
1201
+ window=round(self.diar_frame_length * 2, self.round_digits),
1202
+ shift=self.diar_frame_length,
1203
+ duration=duration,
1204
+ min_subsegment_duration=self.min_subsegment_duration,
1205
+ use_asr_style_frame_count=self.use_asr_style_frame_count,
1206
+ sample_rate=sample_rate,
1207
+ feat_per_sec=self.feat_per_sec,
1208
+ )
1209
+ if self.use_asr_style_frame_count:
1210
+ effective_dur = (
1211
+ np.ceil((1 + duration * sample_rate) / int(sample_rate / self.feat_per_sec)).astype(int)
1212
+ / self.feat_per_sec
1213
+ )
1214
+ else:
1215
+ effective_dur = duration
1216
+ ts_tensor = get_subsegments_to_timestamps(
1217
+ subsegments, self.feat_per_sec, decimals=2, max_end_ts=(offset + effective_dur)
1218
+ )
1219
+ target_len = torch.tensor([ts_tensor.shape[0]])
1220
+ return target_len
1221
+
1222
+ def __getitem__(self, index):
1223
+ sample = self.collection[index]
1224
+ if sample.offset is None:
1225
+ sample.offset = 0
1226
+ offset = sample.offset
1227
+ if self.session_len_sec < 0:
1228
+ session_len_sec = sample.duration
1229
+ else:
1230
+ session_len_sec = min(sample.duration, self.session_len_sec)
1231
+
1232
+ audio_signal = self.featurizer.process(sample.audio_file, offset=offset, duration=session_len_sec)
1233
+
1234
+ # We should resolve the length mis-match from the round-off errors between these two variables:
1235
+ # `session_len_sec` and `audio_signal.shape[0]`
1236
+ session_len_sec = (
1237
+ np.floor(audio_signal.shape[0] / self.featurizer.sample_rate * self.floor_decimal) / self.floor_decimal
1238
+ )
1239
+ audio_signal = audio_signal[: round(self.featurizer.sample_rate * session_len_sec)]
1240
+ audio_signal_length = torch.tensor(audio_signal.shape[0]).long()
1241
+ target_len = self.get_segment_timestamps(duration=session_len_sec, sample_rate=self.featurizer.sample_rate)
1242
+ targets = self.parse_rttm_for_targets_and_lens(
1243
+ rttm_file=sample.rttm_file, offset=offset, duration=session_len_sec, target_len=target_len
1244
+ )
1245
+ return audio_signal, audio_signal_length, targets, target_len
1246
+
1247
+
1248
+ def _eesd_train_collate_fn(self, batch):
1249
+ """
1250
+ Collate a batch of variables needed for training the end-to-end speaker diarization (EESD) model
1251
+ from raw waveforms to diarization labels. The following variables are included in the training/validation batch:
1252
+
1253
+ Args:
1254
+ batch (tuple):
1255
+ A tuple containing the variables for diarization training.
1256
+
1257
+ Returns:
1258
+ audio_signal (torch.Tensor):
1259
+ A tensor containing the raw waveform samples (time series) loaded from the `audio_filepath`
1260
+ in the input manifest file.
1261
+ feature_length (torch.Tensor):
1262
+ A tensor containing the lengths of the raw waveform samples.
1263
+ targets (torch.Tensor):
1264
+ Groundtruth speaker labels for the given input embedding sequence.
1265
+ target_lens (torch.Tensor):
1266
+ A tensor containing the number of segments for each sample in the batch, necessary for
1267
+ reshaping inputs to the EESD model.
1268
+ """
1269
+ packed_batch = list(zip(*batch))
1270
+ audio_signal, feature_length, targets, target_len = packed_batch
1271
+ audio_signal_list, feature_length_list = [], []
1272
+ target_len_list, targets_list = [], []
1273
+
1274
+ max_raw_feat_len = max([x.shape[0] for x in audio_signal])
1275
+ max_target_len = max([x.shape[0] for x in targets])
1276
+ if max([len(feat.shape) for feat in audio_signal]) > 1:
1277
+ max_ch = max([feat.shape[1] for feat in audio_signal])
1278
+ else:
1279
+ max_ch = 1
1280
+ for feat, feat_len, tgt, segment_ct in batch:
1281
+ seq_len = tgt.shape[0]
1282
+ if len(feat.shape) > 1:
1283
+ pad_feat = (0, 0, 0, max_raw_feat_len - feat.shape[0])
1284
+ else:
1285
+ pad_feat = (0, max_raw_feat_len - feat.shape[0])
1286
+ if feat.shape[0] < feat_len:
1287
+ feat_len_pad = feat_len - feat.shape[0]
1288
+ feat = torch.nn.functional.pad(feat, (0, feat_len_pad))
1289
+ pad_tgt = (0, 0, 0, max_target_len - seq_len)
1290
+ padded_feat = torch.nn.functional.pad(feat, pad_feat)
1291
+ padded_tgt = torch.nn.functional.pad(tgt, pad_tgt)
1292
+ if max_ch > 1 and padded_feat.shape[1] < max_ch:
1293
+ feat_ch_pad = max_ch - padded_feat.shape[1]
1294
+ padded_feat = torch.nn.functional.pad(padded_feat, (0, feat_ch_pad))
1295
+ audio_signal_list.append(padded_feat)
1296
+ feature_length_list.append(feat_len.clone().detach())
1297
+ target_len_list.append(segment_ct.clone().detach())
1298
+ targets_list.append(padded_tgt)
1299
+ audio_signal = torch.stack(audio_signal_list)
1300
+ feature_length = torch.stack(feature_length_list)
1301
+ target_lens = torch.stack(target_len_list).squeeze(1)
1302
+ targets = torch.stack(targets_list)
1303
+ return audio_signal, feature_length, targets, target_lens
1304
+
1305
+
1306
+ class AudioToSpeechE2ESpkDiarDataset(_AudioToSpeechE2ESpkDiarDataset):
1307
+ """
1308
+ Dataset class for loading a JSON file containing paths to audio files,
1309
+ RTTM (Rich Transcription Time Marked) files, and the number of speakers.
1310
+ This class is designed for training or fine-tuning a speaker embedding
1311
+ extractor and diarization decoder simultaneously.
1312
+
1313
+ The JSON manifest file should have entries in the following format:
1314
+
1315
+ Example:
1316
+ {
1317
+ "audio_filepath": "/path/to/audio_0.wav",
1318
+ "num_speakers": 2,
1319
+ "rttm_filepath": "/path/to/diar_label_0.rttm"
1320
+ }
1321
+ ...
1322
+ {
1323
+ "audio_filepath": "/path/to/audio_n.wav",
1324
+ "num_speakers": 2,
1325
+ "rttm_filepath": "/path/to/diar_label_n.rttm"
1326
+ }
1327
+
1328
+ Args:
1329
+ manifest_filepath (str):
1330
+ Path to the input manifest JSON file containing paths to audio and RTTM files.
1331
+ soft_label_thres (float):
1332
+ Threshold for assigning soft labels to segments based on RTTM file information.
1333
+ session_len_sec (float):
1334
+ Duration of each session (in seconds) for training or fine-tuning.
1335
+ num_spks (int):
1336
+ Number of speakers in the audio files.
1337
+ featurizer:
1338
+ Instance of a featurizer for generating features from the raw waveform.
1339
+ window_stride (float):
1340
+ Window stride (in seconds) for extracting acoustic features, used to calculate
1341
+ the number of feature frames.
1342
+ global_rank (int):
1343
+ Global rank of the current process (used for distributed training).
1344
+ soft_targets (bool):
1345
+ Whether or not to use soft targets during training.
1346
+
1347
+ Methods:
1348
+ eesd_train_collate_fn(batch):
1349
+ Collates a batch of data for end-to-end speaker diarization training.
1350
+ """
1351
+
1352
+ def __init__(
1353
+ self,
1354
+ *,
1355
+ manifest_filepath: str,
1356
+ soft_label_thres: float,
1357
+ session_len_sec: float,
1358
+ num_spks: int,
1359
+ featurizer,
1360
+ window_stride,
1361
+ global_rank: int,
1362
+ soft_targets: bool,
1363
+ device: str,
1364
+ ):
1365
+ super().__init__(
1366
+ manifest_filepath=manifest_filepath,
1367
+ soft_label_thres=soft_label_thres,
1368
+ session_len_sec=session_len_sec,
1369
+ num_spks=num_spks,
1370
+ featurizer=featurizer,
1371
+ window_stride=window_stride,
1372
+ global_rank=global_rank,
1373
+ soft_targets=soft_targets,
1374
+ device=device,
1375
+ )
1376
+
1377
+ def eesd_train_collate_fn(self, batch):
1378
+ """Collate a batch of data for end-to-end speaker diarization training."""
1379
+ return _eesd_train_collate_fn(self, batch)
nemo/collections/asr/data/audio_to_diar_label_lhotse.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict, Optional, Tuple
16
+
17
+ import torch.utils.data
18
+ from lhotse.dataset import AudioSamples
19
+ from lhotse.dataset.collation import collate_matrices
20
+
21
+ from nemo.collections.asr.parts.utils.asr_multispeaker_utils import (
22
+ get_hidden_length_from_sample_length,
23
+ speaker_to_target,
24
+ )
25
+ from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType
26
+
27
+
28
+ class LhotseAudioToSpeechE2ESpkDiarDataset(torch.utils.data.Dataset):
29
+ """
30
+ This dataset is a Lhotse version of diarization dataset in audio_to_diar_label.py.
31
+ Unlike native NeMo datasets, Lhotse dataset defines only the mapping from
32
+ a CutSet (meta-data) to a mini-batch with PyTorch tensors.
33
+ Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any).
34
+ Managing data, sampling, de-duplication across workers/nodes etc. is all handled
35
+ by Lhotse samplers instead.
36
+ """
37
+
38
+ @property
39
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
40
+ """Define the output types of the dataset."""
41
+ return {
42
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
43
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
44
+ 'targets': NeuralType(('B', 'T', 'N'), LabelsType()),
45
+ 'target_length': NeuralType(tuple('B'), LengthsType()),
46
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
47
+ }
48
+
49
+ def __init__(self, cfg):
50
+ super().__init__()
51
+ self.load_audio = AudioSamples(fault_tolerant=True)
52
+ self.cfg = cfg
53
+ self.num_speakers = self.cfg.get('num_speakers', 4)
54
+ self.num_sample_per_mel_frame = int(
55
+ self.cfg.get('window_stride', 0.01) * self.cfg.get('sample_rate', 16000)
56
+ ) # 160 samples for every 1ms by default
57
+ self.num_mel_frame_per_target_frame = int(self.cfg.get('subsampling_factor', 8))
58
+ self.spk_tar_all_zero = self.cfg.get('spk_tar_all_zero', False)
59
+
60
+ def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]:
61
+ audio, audio_lens, cuts = self.load_audio(cuts)
62
+ speaker_activities = []
63
+ for cut in cuts:
64
+ speaker_activity = speaker_to_target(
65
+ a_cut=cut,
66
+ num_speakers=self.num_speakers,
67
+ num_sample_per_mel_frame=self.num_sample_per_mel_frame,
68
+ num_mel_frame_per_asr_frame=self.num_mel_frame_per_target_frame,
69
+ spk_tar_all_zero=self.spk_tar_all_zero,
70
+ boundary_segments=True,
71
+ )
72
+ speaker_activities.append(speaker_activity)
73
+ targets = collate_matrices(speaker_activities).to(audio.dtype)
74
+ target_lens_list = []
75
+ for audio_len in audio_lens:
76
+ target_fr_len = get_hidden_length_from_sample_length(
77
+ audio_len, self.num_sample_per_mel_frame, self.num_mel_frame_per_target_frame
78
+ )
79
+ target_lens_list.append(target_fr_len)
80
+ target_lens = torch.tensor(target_lens_list)
81
+
82
+ return audio, audio_lens, targets, target_lens
nemo/collections/asr/data/audio_to_label.py ADDED
@@ -0,0 +1,1420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import io
15
+ import os
16
+ from typing import Dict, List, Optional, Union
17
+
18
+ import torch
19
+ import webdataset as wds
20
+
21
+ from nemo.collections.asr.data.audio_to_text import cache_datastore_manifests, expand_sharded_filepaths
22
+ from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer
23
+ from nemo.collections.asr.parts.preprocessing.segment import available_formats as valid_sf_formats
24
+ from nemo.collections.common.parts.preprocessing import collections
25
+ from nemo.core.classes import Dataset, IterableDataset
26
+ from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType, RegressionValuesType
27
+ from nemo.utils import logging
28
+ from nemo.utils.distributed import webdataset_split_by_workers
29
+
30
+ # List of valid file formats (prioritized by order of importance)
31
+ VALID_FILE_FORMATS = ';'.join(['wav', 'mp3', 'flac', 'opus'] + [fmt.lower() for fmt in valid_sf_formats.keys()])
32
+
33
+
34
+ def repeat_signal(signal: torch.Tensor, sig_len: int, required_length: int) -> torch.Tensor:
35
+ """repeat signal to make short signal to have required_length
36
+ Args:
37
+ signal (Tensor): input signal
38
+ sig_len (int): length of input signal
39
+ required_length (int): length of generated signal
40
+ Returns:
41
+ signal (Tensor): generated signal of required_length by repeating itself.
42
+ """
43
+ sub: torch.Tensor = torch.tensor([])
44
+ repeat = int(required_length // sig_len)
45
+ rem = int(required_length % sig_len)
46
+ sub: torch.Tensor = torch.tensor([])
47
+ rep_sig: torch.Tensor = torch.cat(repeat * [signal])
48
+ if rem > 0:
49
+ sub = signal[-rem:]
50
+ signal = torch.cat((rep_sig, sub))
51
+ else:
52
+ signal = rep_sig
53
+ return signal
54
+
55
+
56
+ def normalize(signal):
57
+ """normalize signal
58
+ Args:
59
+ signal(FloatTensor): signal to be normalized.
60
+ """
61
+ signal_minusmean = signal - signal.mean()
62
+ return signal_minusmean / signal_minusmean.abs().max()
63
+
64
+
65
+ def count_occurence(manifest_file_id):
66
+ """Count number of wav files in Dict manifest_file_id. Use for _TarredAudioToLabelDataset.
67
+ Args:
68
+ manifest_file_id (Dict): Dict of files and their corresponding id. {'A-sub0' : 1, ..., 'S-sub10':100}
69
+ Returns:
70
+ count (Dict): Dict of wav files {'A' : 2, ..., 'S':10}
71
+ """
72
+ count = dict()
73
+ for i in manifest_file_id:
74
+ audio_filename = i.split("-sub")[0]
75
+ count[audio_filename] = count.get(audio_filename, 0) + 1
76
+ return count
77
+
78
+
79
+ def _speech_collate_fn(batch, pad_id):
80
+ """collate batch of audio sig, audio len, tokens, tokens len
81
+ Args:
82
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
83
+ LongTensor): A tuple of tuples of signal, signal lengths,
84
+ encoded tokens, and encoded tokens length. This collate func
85
+ assumes the signals are 1d torch tensors (i.e. mono audio).
86
+ """
87
+ _, audio_lengths, _, tokens_lengths = zip(*batch)
88
+ max_audio_len = 0
89
+ has_audio = audio_lengths[0] is not None
90
+ if has_audio:
91
+ max_audio_len = max(audio_lengths).item()
92
+ max_tokens_len = max(tokens_lengths).item()
93
+
94
+ audio_signal, tokens = [], []
95
+ for sig, sig_len, tokens_i, tokens_i_len in batch:
96
+ if has_audio:
97
+ sig_len = sig_len.item()
98
+ if sig_len < max_audio_len:
99
+ pad = (0, max_audio_len - sig_len)
100
+ sig = torch.nn.functional.pad(sig, pad)
101
+ audio_signal.append(sig)
102
+ tokens_i_len = tokens_i_len.item()
103
+ if tokens_i_len < max_tokens_len:
104
+ pad = (0, max_tokens_len - tokens_i_len)
105
+ tokens_i = torch.nn.functional.pad(tokens_i, pad, value=pad_id)
106
+ tokens.append(tokens_i)
107
+
108
+ if has_audio:
109
+ audio_signal = torch.stack(audio_signal)
110
+ audio_lengths = torch.stack(audio_lengths)
111
+ else:
112
+ audio_signal, audio_lengths = None, None
113
+ tokens = torch.stack(tokens)
114
+ tokens_lengths = torch.stack(tokens_lengths)
115
+
116
+ return audio_signal, audio_lengths, tokens, tokens_lengths
117
+
118
+
119
+ def _fixed_seq_collate_fn(self, batch):
120
+ """collate batch of audio sig, audio len, tokens, tokens len
121
+ Args:
122
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
123
+ LongTensor): A tuple of tuples of signal, signal lengths,
124
+ encoded tokens, and encoded tokens length. This collate func
125
+ assumes the signals are 1d torch tensors (i.e. mono audio).
126
+ """
127
+ _, audio_lengths, _, tokens_lengths = zip(*batch)
128
+
129
+ has_audio = audio_lengths[0] is not None
130
+ fixed_length = int(max(audio_lengths))
131
+
132
+ audio_signal, tokens, new_audio_lengths = [], [], []
133
+ for sig, sig_len, tokens_i, _ in batch:
134
+ if has_audio:
135
+ sig_len = sig_len.item()
136
+ chunck_len = sig_len - fixed_length
137
+
138
+ if chunck_len < 0:
139
+ repeat = fixed_length // sig_len
140
+ rem = fixed_length % sig_len
141
+ sub = sig[-rem:] if rem > 0 else torch.tensor([])
142
+ rep_sig = torch.cat(repeat * [sig])
143
+ sig = torch.cat((rep_sig, sub))
144
+ new_audio_lengths.append(torch.tensor(fixed_length))
145
+
146
+ audio_signal.append(sig)
147
+
148
+ tokens.append(tokens_i)
149
+
150
+ if has_audio:
151
+ audio_signal = torch.stack(audio_signal)
152
+ audio_lengths = torch.stack(new_audio_lengths)
153
+ else:
154
+ audio_signal, audio_lengths = None, None
155
+ tokens = torch.stack(tokens)
156
+ tokens_lengths = torch.stack(tokens_lengths)
157
+
158
+ return audio_signal, audio_lengths, tokens, tokens_lengths
159
+
160
+
161
+ def _vad_frame_seq_collate_fn(self, batch):
162
+ """collate batch of audio sig, audio len, tokens, tokens len
163
+ Args:
164
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
165
+ LongTensor): A tuple of tuples of signal, signal lengths,
166
+ encoded tokens, and encoded tokens length. This collate func
167
+ assumes the signals are 1d torch tensors (i.e. mono audio).
168
+ batch size equals to 1.
169
+ """
170
+ slice_length = int(self.featurizer.sample_rate * self.window_length_in_sec)
171
+ _, audio_lengths, _, tokens_lengths = zip(*batch)
172
+ slice_length = int(min(slice_length, max(audio_lengths)))
173
+ shift = int(self.featurizer.sample_rate * self.shift_length_in_sec)
174
+ has_audio = audio_lengths[0] is not None
175
+
176
+ audio_signal, num_slices, tokens, audio_lengths = [], [], [], []
177
+
178
+ append_len_start = slice_length // 2
179
+ append_len_end = slice_length - slice_length // 2
180
+ for sig, sig_len, tokens_i, _ in batch:
181
+ if self.normalize_audio:
182
+ sig = normalize(sig)
183
+ start = torch.zeros(append_len_start)
184
+ end = torch.zeros(append_len_end)
185
+ sig = torch.cat((start, sig, end))
186
+ sig_len += slice_length
187
+
188
+ if has_audio:
189
+ slices = torch.div(sig_len - slice_length, shift, rounding_mode='trunc')
190
+ for slice_id in range(slices):
191
+ start_idx = slice_id * shift
192
+ end_idx = start_idx + slice_length
193
+ signal = sig[start_idx:end_idx]
194
+ audio_signal.append(signal)
195
+
196
+ num_slices.append(slices)
197
+ tokens.extend([tokens_i] * slices)
198
+ audio_lengths.extend([slice_length] * slices)
199
+
200
+ if has_audio:
201
+ audio_signal = torch.stack(audio_signal)
202
+ audio_lengths = torch.tensor(audio_lengths)
203
+ else:
204
+ audio_signal, audio_lengths = None, None
205
+
206
+ tokens = torch.stack(tokens)
207
+ tokens_lengths = torch.tensor(num_slices)
208
+ return audio_signal, audio_lengths, tokens, tokens_lengths
209
+
210
+
211
+ class _AudioLabelDataset(Dataset):
212
+ """
213
+ Dataset that loads tensors via a json file containing paths to audio files,
214
+ labels, and durations and offsets(in seconds). Each new line is a
215
+ different sample. Example below:
216
+ and their target labels. JSON files should be of the following format::
217
+ {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \
218
+ target_label_0, "offset": offset_in_sec_0}
219
+ ...
220
+ {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \
221
+ target_label_n, "offset": offset_in_sec_n}
222
+ Args:
223
+ manifest_filepath (Union[str, List[str]]): Dataset parameter. Path to JSON containing data.
224
+ labels (list): Dataset parameter. List of target classes that can be output by the speaker recognition model.
225
+ featurizer
226
+ min_duration (float): Dataset parameter. All training files which have a duration less than min_duration
227
+ are dropped. Note: Duration is read from the manifest JSON.
228
+ Defaults to 0.1.
229
+ max_duration (float): Dataset parameter.
230
+ All training files which have a duration more than max_duration
231
+ are dropped. Note: Duration is read from the manifest JSON.
232
+ Defaults to None.
233
+ trim (bool): Whether to use trim silence from beginning and end of audio signal using librosa.effects.trim().
234
+ Defaults to False.
235
+ channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable
236
+ of integers denoting a subset of channels. Channel selector is using zero-based indexing.
237
+ If set to `None`, the original signal will be used.
238
+ """
239
+
240
+ @property
241
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
242
+ """Returns definitions of module output ports."""
243
+
244
+ output_types = {
245
+ 'audio_signal': NeuralType(
246
+ ('B', 'T'),
247
+ (
248
+ AudioSignal(freq=self._sample_rate)
249
+ if self is not None and hasattr(self, '_sample_rate')
250
+ else AudioSignal()
251
+ ),
252
+ ),
253
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
254
+ }
255
+
256
+ if self.is_regression_task:
257
+ output_types.update(
258
+ {
259
+ 'targets': NeuralType(tuple('B'), RegressionValuesType()),
260
+ 'targets_length': NeuralType(tuple('B'), LengthsType()),
261
+ }
262
+ )
263
+ else:
264
+
265
+ output_types.update(
266
+ {
267
+ 'label': NeuralType(tuple('B'), LabelsType()),
268
+ 'label_length': NeuralType(tuple('B'), LengthsType()),
269
+ }
270
+ )
271
+
272
+ return output_types
273
+
274
+ def __init__(
275
+ self,
276
+ *,
277
+ manifest_filepath: Union[str, List[str]],
278
+ labels: List[str],
279
+ featurizer,
280
+ min_duration: Optional[float] = 0.1,
281
+ max_duration: Optional[float] = None,
282
+ trim: bool = False,
283
+ channel_selector: Union[str, int, List[int]] = None,
284
+ is_regression_task: bool = False,
285
+ cal_labels_occurrence: Optional[bool] = False,
286
+ ):
287
+ super().__init__()
288
+ if isinstance(manifest_filepath, str):
289
+ manifest_filepath = manifest_filepath.split(',')
290
+ cache_datastore_manifests(manifest_filepaths=manifest_filepath, cache_audio=True)
291
+ self.collection = collections.ASRSpeechLabel(
292
+ manifests_files=manifest_filepath,
293
+ min_duration=min_duration,
294
+ max_duration=max_duration,
295
+ is_regression_task=is_regression_task,
296
+ cal_labels_occurrence=cal_labels_occurrence,
297
+ )
298
+
299
+ self.featurizer = featurizer
300
+ self.trim = trim
301
+ self.channel_selector = channel_selector
302
+ self.is_regression_task = is_regression_task
303
+
304
+ if not is_regression_task:
305
+ self.labels = labels if labels else self.collection.uniq_labels
306
+ self.num_classes = len(self.labels) if self.labels is not None else 1
307
+ self.label2id, self.id2label = {}, {}
308
+ self.id2occurrence, self.labels_occurrence = {}, []
309
+
310
+ for label_id, label in enumerate(self.labels):
311
+ self.label2id[label] = label_id
312
+ self.id2label[label_id] = label
313
+ if cal_labels_occurrence:
314
+ self.id2occurrence[label_id] = self.collection.labels_occurrence[label]
315
+
316
+ if cal_labels_occurrence:
317
+ self.labels_occurrence = [self.id2occurrence[k] for k in sorted(self.id2occurrence)]
318
+
319
+ for idx in range(len(self.labels[:5])):
320
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
321
+
322
+ else:
323
+ self.labels = []
324
+ self.num_classes = 1
325
+
326
+ def __len__(self):
327
+ return len(self.collection)
328
+
329
+ def __getitem__(self, index):
330
+ sample = self.collection[index]
331
+
332
+ offset = sample.offset
333
+
334
+ if offset is None:
335
+ offset = 0
336
+
337
+ features = self.featurizer.process(
338
+ sample.audio_file,
339
+ offset=offset,
340
+ duration=sample.duration,
341
+ trim=self.trim,
342
+ channel_selector=self.channel_selector,
343
+ )
344
+ f, fl = features, torch.tensor(features.shape[0]).long()
345
+
346
+ if not self.is_regression_task:
347
+ t = torch.tensor(self.label2id[sample.label]).long()
348
+ else:
349
+ t = torch.tensor(sample.label).float()
350
+
351
+ tl = torch.tensor(1).long() # For compatibility with collate_fn used later
352
+
353
+ return f, fl, t, tl
354
+
355
+
356
+ # Ported from https://github.com/NVIDIA/OpenSeq2Seq/blob/master/open_seq2seq/data/speech2text/speech_commands.py
357
+ class AudioToClassificationLabelDataset(_AudioLabelDataset):
358
+ """
359
+ Dataset that loads tensors via a json file containing paths to audio
360
+ files, command class, and durations (in seconds). Each new line is a
361
+ different sample. Example below:
362
+ {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \
363
+ target_label_0, "offset": offset_in_sec_0}
364
+ ...
365
+ {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \
366
+ target_label_n, "offset": offset_in_sec_n}
367
+ Args:
368
+ manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can
369
+ be comma-separated paths.
370
+ labels (Optional[list]): String containing all the possible labels to map to
371
+ if None then automatically picks from ASRSpeechLabel collection.
372
+ featurizer: Initialized featurizer class that converts paths of
373
+ audio to feature tensors
374
+ max_duration: If audio exceeds this length, do not include in dataset
375
+ min_duration: If audio is less than this length, do not include
376
+ in dataset
377
+ trim: Boolean flag whether to trim the audio
378
+ """
379
+
380
+ def _collate_fn(self, batch):
381
+ return _speech_collate_fn(batch, pad_id=0)
382
+
383
+
384
+ class AudioToSpeechLabelDataset(_AudioLabelDataset):
385
+ """
386
+ Dataset that loads tensors via a json file containing paths to audio
387
+ files, command class, and durations (in seconds). Each new line is a
388
+ different sample. Example below:
389
+ {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \
390
+ target_label_0, "offset": offset_in_sec_0}
391
+ ...
392
+ {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \
393
+ target_label_n, "offset": offset_in_sec_n}
394
+ Args:
395
+ manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can
396
+ be comma-separated paths.
397
+ labels (Optional[list]): String containing all the possible labels to map to
398
+ if None then automatically picks from ASRSpeechLabel collection.
399
+ min_duration (float): Dataset parameter.
400
+ All training files which have a duration less than min_duration
401
+ are dropped. Note: Duration is read from the manifest JSON.
402
+ Defaults to 0.1.
403
+ max_duration (float): Dataset parameter.
404
+ All training files which have a duration more than max_duration
405
+ are dropped. Note: Duration is read from the manifest JSON.
406
+ Defaults to None.
407
+ trim (bool): Whether to use trim silence from beginning and end
408
+ of audio signal using librosa.effects.trim().
409
+ Defaults to False.
410
+ channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable
411
+ of integers denoting a subset of channels. Channel selector is using zero-based indexing.
412
+ If set to `None`, the original signal will be used.
413
+ window_length_in_sec (float): length of window/slice (in seconds)
414
+ Use this for speaker recognition and VAD tasks.
415
+ shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task in a batch
416
+ Use this for VAD task during inference.
417
+ normalize_audio (bool): Whether to normalize audio signal.
418
+ Defaults to False.
419
+ is_regression_task (bool): Whether the dataset is for a regression task instead of classification.
420
+ Defaults to False.
421
+ cal_labels_occurrence (bool): Whether to calculate occurrence of labels
422
+ Defaults to False.
423
+ """
424
+
425
+ def __init__(
426
+ self,
427
+ *,
428
+ manifest_filepath: Union[str, List[str]],
429
+ labels: List[str],
430
+ featurizer,
431
+ min_duration: Optional[float] = 0.1,
432
+ max_duration: Optional[float] = None,
433
+ trim: bool = False,
434
+ channel_selector: Optional[Union[str, int, List[int]]] = None,
435
+ window_length_in_sec: Optional[float] = 8,
436
+ shift_length_in_sec: Optional[float] = 1,
437
+ normalize_audio: bool = False,
438
+ is_regression_task: bool = False,
439
+ cal_labels_occurrence: Optional[bool] = False,
440
+ ):
441
+ self.window_length_in_sec = window_length_in_sec
442
+ self.shift_length_in_sec = shift_length_in_sec
443
+ self.normalize_audio = normalize_audio
444
+
445
+ logging.debug("Window/slice length considered for collate func is {}".format(self.window_length_in_sec))
446
+ logging.debug("Shift length considered for collate func is {}".format(self.shift_length_in_sec))
447
+
448
+ super().__init__(
449
+ manifest_filepath=manifest_filepath,
450
+ labels=labels,
451
+ featurizer=featurizer,
452
+ min_duration=min_duration,
453
+ max_duration=max_duration,
454
+ trim=trim,
455
+ channel_selector=channel_selector,
456
+ is_regression_task=is_regression_task,
457
+ cal_labels_occurrence=cal_labels_occurrence,
458
+ )
459
+
460
+ def fixed_seq_collate_fn(self, batch):
461
+ return _fixed_seq_collate_fn(self, batch)
462
+
463
+ def vad_frame_seq_collate_fn(self, batch):
464
+ return _vad_frame_seq_collate_fn(self, batch)
465
+
466
+
467
+ class _TarredAudioLabelDataset(IterableDataset):
468
+ """
469
+ A similar Dataset to the AudioLabelDataSet, but which loads tarred audio files.
470
+
471
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset),
472
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
473
+ contain the information for one audio file, including at least the label and name of the audio
474
+ file within the tarball.
475
+
476
+ Valid formats for the audio_tar_filepaths argument include:
477
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
478
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
479
+
480
+ Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference.
481
+ This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements.
482
+ Supported opening braces - { <=> (, [, < and the special tag _OP_.
483
+ Supported closing braces - } <=> ), ], > and the special tag _CL_.
484
+ For SLURM based tasks, we suggest the use of the special tags for ease of use.
485
+
486
+ See the documentation for more information about accepted data and input formats.
487
+
488
+ If using multiple processes the number of shards should be divisible by the number of workers to ensure an
489
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
490
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
491
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
492
+
493
+ Notice that a few arguments are different from the AudioLabelDataSet; for example, shuffle (bool) has been
494
+ replaced by shuffle_n (int).
495
+
496
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
497
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
498
+
499
+ Args:
500
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
501
+ string (can be brace-expandable).
502
+ manifest_filepath (str): Path to the manifest.
503
+ labels (list): Dataset parameter.
504
+ List of target classes that can be output by the speaker recognition model.
505
+ featurizer
506
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
507
+ See WebDataset documentation for more details.
508
+ Defaults to 0.
509
+ min_duration (float): Dataset parameter.
510
+ All training files which have a duration less than min_duration
511
+ are dropped. Note: Duration is read from the manifest JSON.
512
+ Defaults to 0.1.
513
+ max_duration (float): Dataset parameter.
514
+ All training files which have a duration more than max_duration
515
+ are dropped. Note: Duration is read from the manifest JSON.
516
+ Defaults to None.
517
+ trim(bool): Whether to use trim silence from beginning and end
518
+ of audio signal using librosa.effects.trim().
519
+ Defaults to False.
520
+ window_length_in_sec (float): length of slice/window (in seconds) # Pass this only for speaker recognition and VAD task
521
+ shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task. in a batch # Pass this only for VAD task during inference.
522
+ normalize_audio (bool): Whether to normalize audio signal. Defaults to False.
523
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
524
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
525
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
526
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
527
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
528
+ The benefit of replication is that it allows each node to sample data points from the entire
529
+ dataset independently of other nodes, and reduces dependence on the value of `shuffle_n`.
530
+
531
+ .. warning::
532
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
533
+ and therefore more than one node may sample the same tarfile, and even sample the same
534
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
535
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
536
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
537
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
538
+ or test datasets.
539
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
540
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
541
+ is_regression_task (bool): Whether it is a regression task. Defualts to False.
542
+ """
543
+
544
+ def __init__(
545
+ self,
546
+ *,
547
+ audio_tar_filepaths: Union[str, List[str]],
548
+ manifest_filepath: Union[str, List[str]],
549
+ labels: List[str],
550
+ featurizer,
551
+ shuffle_n: int = 0,
552
+ min_duration: Optional[float] = 0.1,
553
+ max_duration: Optional[float] = None,
554
+ trim: bool = False,
555
+ shard_strategy: str = "scatter",
556
+ global_rank: int = 0,
557
+ world_size: int = 0,
558
+ is_regression_task: bool = False,
559
+ ):
560
+ cache_datastore_manifests(manifest_filepaths=manifest_filepath)
561
+ self.collection = collections.ASRSpeechLabel(
562
+ manifests_files=manifest_filepath,
563
+ min_duration=min_duration,
564
+ max_duration=max_duration,
565
+ index_by_file_id=True, # Must set this so the manifest lines can be indexed by file ID
566
+ )
567
+
568
+ self.file_occurence = count_occurence(self.collection.mapping)
569
+
570
+ self.featurizer = featurizer
571
+ self.trim = trim
572
+
573
+ self.labels = labels if labels else self.collection.uniq_labels
574
+ self.num_classes = len(self.labels)
575
+
576
+ self.label2id, self.id2label = {}, {}
577
+ for label_id, label in enumerate(self.labels):
578
+ self.label2id[label] = label_id
579
+ self.id2label[label_id] = label
580
+
581
+ for idx in range(len(self.labels[:5])):
582
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
583
+
584
+ audio_tar_filepaths = expand_sharded_filepaths(
585
+ sharded_filepaths=audio_tar_filepaths,
586
+ shard_strategy=shard_strategy,
587
+ world_size=world_size,
588
+ global_rank=global_rank,
589
+ )
590
+ # Put together WebDataset
591
+ self._dataset = wds.DataPipeline(
592
+ wds.SimpleShardList(urls=audio_tar_filepaths),
593
+ webdataset_split_by_workers,
594
+ wds.shuffle(shuffle_n),
595
+ wds.tarfile_to_samples(),
596
+ wds.rename(audio=VALID_FILE_FORMATS, key='__key__'),
597
+ wds.to_tuple('audio', 'key'),
598
+ self._filter,
599
+ wds.map(self._build_sample),
600
+ )
601
+
602
+ def _filter(self, iterator):
603
+ """This function is used to remove samples that have been filtered out by ASRSpeechLabel already.
604
+ Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample
605
+ that was filtered out (e.g. for duration).
606
+ Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard,
607
+ which may make your code hang as one process will finish before the other.
608
+ """
609
+
610
+ class TarredAudioFilter:
611
+ def __init__(self, collection, file_occurence):
612
+ self.iterator = iterator
613
+ self.collection = collection
614
+ self.file_occurence = file_occurence
615
+ self._iterable = self._internal_generator()
616
+
617
+ def __iter__(self):
618
+ self._iterable = self._internal_generator()
619
+ return self
620
+
621
+ def __next__(self):
622
+ try:
623
+ values = next(self._iterable)
624
+ except StopIteration:
625
+ # reset generator
626
+ self._iterable = self._internal_generator()
627
+ values = next(self._iterable)
628
+
629
+ return values
630
+
631
+ def _internal_generator(self):
632
+ """
633
+ WebDataset requires an Iterator, but we require an iterable that yields 1-or-more
634
+ values per value inside self.iterator.
635
+
636
+ Therefore wrap the iterator with a generator function that will yield 1-or-more
637
+ values per sample in the iterator.
638
+ """
639
+ for _, tup in enumerate(self.iterator):
640
+ audio_bytes, audio_filename = tup
641
+
642
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
643
+ if audio_filename in self.file_occurence:
644
+ for j in range(0, self.file_occurence[file_id]):
645
+ if j == 0:
646
+ audio_filename = file_id
647
+ else:
648
+ audio_filename = file_id + "-sub" + str(j)
649
+ yield audio_bytes, audio_filename
650
+
651
+ return TarredAudioFilter(self.collection, self.file_occurence)
652
+
653
+ def _build_sample(self, tup):
654
+ """Builds the training sample by combining the data from the WebDataset with the manifest info."""
655
+ audio_bytes, audio_filename = tup
656
+ # Grab manifest entry from self.collection
657
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
658
+
659
+ manifest_idx = self.collection.mapping[file_id]
660
+ manifest_entry = self.collection[manifest_idx]
661
+
662
+ offset = manifest_entry.offset
663
+ if offset is None:
664
+ offset = 0
665
+
666
+ # Convert audio bytes to IO stream for processing (for SoundFile to read)
667
+ audio_filestream = io.BytesIO(audio_bytes)
668
+ features = self.featurizer.process(
669
+ audio_filestream,
670
+ offset=offset,
671
+ duration=manifest_entry.duration,
672
+ trim=self.trim,
673
+ )
674
+
675
+ audio_filestream.close()
676
+
677
+ # Audio features
678
+ f, fl = features, torch.tensor(features.shape[0]).long()
679
+
680
+ t = self.label2id[manifest_entry.label]
681
+ tl = 1 # For compatibility with collate_fn used later
682
+
683
+ return f, fl, torch.tensor(t).long(), torch.tensor(tl).long()
684
+
685
+ def __iter__(self):
686
+ return self._dataset.__iter__()
687
+
688
+ def __len__(self):
689
+ return len(self.collection)
690
+
691
+
692
+ class TarredAudioToClassificationLabelDataset(_TarredAudioLabelDataset):
693
+ """
694
+ A similar Dataset to the AudioToClassificationLabelDataset, but which loads tarred audio files.
695
+
696
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToClassificationLabelDataset),
697
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
698
+ contain the information for one audio file, including at least the transcript and name of the audio
699
+ file within the tarball.
700
+
701
+ Valid formats for the audio_tar_filepaths argument include:
702
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
703
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
704
+
705
+ See the WebDataset documentation for more information about accepted data and input formats.
706
+
707
+ If using multiple processes the number of shards should be divisible by the number of workers to ensure an
708
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
709
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
710
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
711
+
712
+ Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been
713
+ replaced by shuffle_n (int).
714
+
715
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
716
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
717
+
718
+ Args:
719
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
720
+ string (can be brace-expandable).
721
+ manifest_filepath (str): Path to the manifest.
722
+ labels (list): Dataset parameter.
723
+ List of target classes that can be output by the speaker recognition model.
724
+ featurizer
725
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
726
+ See WebDataset documentation for more details.
727
+ Defaults to 0.
728
+ min_duration (float): Dataset parameter.
729
+ All training files which have a duration less than min_duration
730
+ are dropped. Note: Duration is read from the manifest JSON.
731
+ Defaults to 0.1.
732
+ max_duration (float): Dataset parameter.
733
+ All training files which have a duration more than max_duration
734
+ are dropped. Note: Duration is read from the manifest JSON.
735
+ Defaults to None.
736
+ trim(bool): Whether to use trim silence from beginning and end
737
+ of audio signal using librosa.effects.trim().
738
+ Defaults to False.
739
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
740
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
741
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
742
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
743
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
744
+ The benefit of replication is that it allows each node to sample data points from the entire
745
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
746
+
747
+ .. warning::
748
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
749
+ and therefore more than one node may sample the same tarfile, and even sample the same
750
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
751
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
752
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
753
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
754
+ or test datasets.
755
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
756
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
757
+ is_regression_task (bool): Whether it is a regression task. Defualts to False.
758
+ """
759
+
760
+ def _collate_fn(self, batch):
761
+ return _speech_collate_fn(batch, pad_id=0)
762
+
763
+
764
+ class TarredAudioToSpeechLabelDataset(_TarredAudioLabelDataset):
765
+ """
766
+ A similar Dataset to the AudioToSpeechLabelDataset, but which loads tarred audio files.
767
+
768
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset),
769
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
770
+ contain the information for one audio file, including at least the transcript and name of the audio
771
+ file within the tarball.
772
+
773
+ Valid formats for the audio_tar_filepaths argument include:
774
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
775
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
776
+
777
+ See the WebDataset documentation for more information about accepted data and input formats.
778
+
779
+ If using multiple processes the number of shards should be divisible by the number of workers to ensure an
780
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
781
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
782
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
783
+
784
+ Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been
785
+ replaced by shuffle_n (int).
786
+
787
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
788
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
789
+
790
+ Args:
791
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
792
+ string (can be brace-expandable).
793
+ manifest_filepath (str): Path to the manifest.
794
+ labels (list): Dataset parameter.
795
+ List of target classes that can be output by the speaker recognition model.
796
+ featurizer
797
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
798
+ See WebDataset documentation for more details.
799
+ Defaults to 0.
800
+ min_duration (float): Dataset parameter.
801
+ All training files which have a duration less than min_duration
802
+ are dropped. Note: Duration is read from the manifest JSON.
803
+ Defaults to 0.1.
804
+ max_duration (float): Dataset parameter.
805
+ All training files which have a duration more than max_duration
806
+ are dropped. Note: Duration is read from the manifest JSON.
807
+ Defaults to None.
808
+ trim(bool): Whether to use trim silence from beginning and end
809
+ of audio signal using librosa.effects.trim().
810
+ Defaults to False.
811
+ window_length_in_sec (float): time length of window/slice (in seconds) # Pass this only for speaker recognition and VAD task
812
+ shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task. in a batch # Pass this only for VAD task during inference.
813
+ normalize_audio (bool): Whether to normalize audio signal. Defaults to False.
814
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
815
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
816
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
817
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
818
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
819
+ The benefit of replication is that it allows each node to sample data points from the entire
820
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
821
+
822
+ .. warning::
823
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
824
+ and therefore more than one node may sample the same tarfile, and even sample the same
825
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
826
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
827
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
828
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
829
+ or test datasets.
830
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
831
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
832
+ """
833
+
834
+ def __init__(
835
+ self,
836
+ *,
837
+ audio_tar_filepaths: Union[str, List[str]],
838
+ manifest_filepath: Union[str, List[str]],
839
+ labels: List[str],
840
+ featurizer,
841
+ shuffle_n: int = 0,
842
+ min_duration: Optional[float] = 0.1,
843
+ max_duration: Optional[float] = None,
844
+ trim: bool = False,
845
+ window_length_in_sec: Optional[float] = 8,
846
+ shift_length_in_sec: Optional[float] = 1,
847
+ normalize_audio: bool = False,
848
+ shard_strategy: str = "scatter",
849
+ global_rank: int = 0,
850
+ world_size: int = 0,
851
+ ):
852
+ logging.info("Window/slice length considered for collate func is {}".format(window_length_in_sec))
853
+ logging.info("Shift length considered for collate func is {}".format(shift_length_in_sec))
854
+ self.window_length_in_sec = window_length_in_sec
855
+ self.shift_length_in_sec = shift_length_in_sec
856
+ self.normalize_audio = normalize_audio
857
+
858
+ super().__init__(
859
+ audio_tar_filepaths=audio_tar_filepaths,
860
+ manifest_filepath=manifest_filepath,
861
+ labels=labels,
862
+ featurizer=featurizer,
863
+ shuffle_n=shuffle_n,
864
+ min_duration=min_duration,
865
+ max_duration=max_duration,
866
+ trim=trim,
867
+ shard_strategy=shard_strategy,
868
+ global_rank=global_rank,
869
+ world_size=world_size,
870
+ )
871
+
872
+ def fixed_seq_collate_fn(self, batch):
873
+ return _fixed_seq_collate_fn(self, batch)
874
+
875
+ def sliced_seq_collate_fn(self, batch):
876
+ raise NotImplementedError
877
+
878
+ def vad_frame_seq_collate_fn(self, batch):
879
+ return _vad_frame_seq_collate_fn(self, batch)
880
+
881
+
882
+ class AudioToMultiLabelDataset(Dataset):
883
+ """
884
+ Dataset that loads a json file containing paths to audio files, durations (in seconds), and a sequence of labels.
885
+ Each new line is a different sample. Example below:
886
+ {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \
887
+ "0 1 1 0 1", "offset": offset_in_sec_0}
888
+ ...
889
+ {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \
890
+ "0 1 0 0 1", "offset": offset_in_sec_n}
891
+ Args:
892
+ manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can
893
+ be comma-separated paths.
894
+ labels (Optional[list]): String containing all the possible labels to map to
895
+ if None then automatically picks from ASRSpeechLabel collection.
896
+ min_duration (float): Dataset parameter.
897
+ All training files which have a duration less than min_duration
898
+ are dropped. Note: Duration is read from the manifest JSON.
899
+ Defaults to 0.1.
900
+ max_duration (float): Dataset parameter.
901
+ All training files which have a duration more than max_duration
902
+ are dropped. Note: Duration is read from the manifest JSON.
903
+ Defaults to None.
904
+ trim_silence (bool): Whether to use trim silence from beginning and end
905
+ of audio signal using librosa.effects.trim().
906
+ Defaults to False.
907
+ channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable
908
+ of integers denoting a subset of channels. Channel selector is using zero-based indexing.
909
+ If set to `None`, the original signal will be used.
910
+ window_length_in_sec (float): length of window/slice (in seconds)
911
+ Use this for speaker recognition and VAD tasks.
912
+ shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task in a batch
913
+ Use this for VAD task during inference.
914
+ normalize_audio (bool): Whether to normalize audio signal.
915
+ Defaults to False.
916
+ is_regression_task (bool): Whether the dataset is for a regression task instead of classification.
917
+ Defaults to False.
918
+ cal_labels_occurrence (bool): Whether to calculate occurrence of labels
919
+ Defaults to False.
920
+ delimiter (Optional[str]): Delimiter to use when splitting the label string, default to None.
921
+ normalize_audio_db (Optional[float]): normalize audio signal to a target db, default to None.
922
+ """
923
+
924
+ @property
925
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
926
+ """Returns definitions of module output ports."""
927
+
928
+ output_types = {
929
+ 'audio_signal': NeuralType(
930
+ ('B', 'T'),
931
+ (
932
+ AudioSignal(freq=self._sample_rate)
933
+ if self is not None and hasattr(self, '_sample_rate')
934
+ else AudioSignal()
935
+ ),
936
+ ),
937
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
938
+ }
939
+
940
+ if self.is_regression_task:
941
+ output_types.update(
942
+ {
943
+ 'targets': NeuralType(tuple('B, T'), RegressionValuesType()),
944
+ 'targets_length': NeuralType(tuple('B'), LengthsType()),
945
+ }
946
+ )
947
+ else:
948
+ output_types.update(
949
+ {
950
+ 'label': NeuralType(('B', 'T'), LabelsType()),
951
+ 'label_length': NeuralType(tuple('B'), LengthsType()),
952
+ }
953
+ )
954
+
955
+ return output_types
956
+
957
+ def __init__(
958
+ self,
959
+ *,
960
+ manifest_filepath: Union[str, List[str]],
961
+ sample_rate: int,
962
+ labels: Optional[List[str]] = None,
963
+ int_values: bool = False,
964
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
965
+ min_duration: Optional[float] = 0.1,
966
+ max_duration: Optional[float] = None,
967
+ trim_silence: bool = False,
968
+ channel_selector: Optional[Union[str, int, List[int]]] = None,
969
+ is_regression_task: bool = False,
970
+ cal_labels_occurrence: Optional[bool] = False,
971
+ delimiter: Optional[str] = None,
972
+ normalize_audio_db: Optional[float] = None,
973
+ ):
974
+ super().__init__()
975
+ if isinstance(manifest_filepath, str):
976
+ manifest_filepath = manifest_filepath.split(',')
977
+
978
+ self.delimiter = delimiter
979
+ self.normalize_audio_db = normalize_audio_db
980
+
981
+ self.collection = collections.ASRSpeechLabel(
982
+ manifests_files=manifest_filepath,
983
+ min_duration=min_duration,
984
+ max_duration=max_duration,
985
+ is_regression_task=is_regression_task,
986
+ cal_labels_occurrence=cal_labels_occurrence,
987
+ delimiter=delimiter,
988
+ )
989
+
990
+ self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)
991
+ self.trim = trim_silence
992
+ self.channel_selector = channel_selector
993
+ self.is_regression_task = is_regression_task
994
+ self.id2occurrence = {}
995
+ self.labels_occurrence = None
996
+
997
+ if not is_regression_task:
998
+ self.labels = labels if labels else self._get_label_set()
999
+ self.num_classes = len(self.labels) if self.labels is not None else 1
1000
+ self.label2id, self.id2label = {}, {}
1001
+ for label_id, label in enumerate(self.labels):
1002
+ self.label2id[label] = label_id
1003
+ self.id2label[label_id] = label
1004
+ if cal_labels_occurrence:
1005
+ self.id2occurrence[label_id] = self.collection.labels_occurrence[label]
1006
+ self.labels_occurrence.append(self.id2occurrence[label_id])
1007
+
1008
+ for idx in range(len(self.labels[:5])):
1009
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
1010
+ else:
1011
+ self.labels = []
1012
+ self.num_classes = 1
1013
+
1014
+ def _get_label_set(self):
1015
+ labels = []
1016
+ for sample in self.collection:
1017
+ label_str = sample.label
1018
+ if label_str:
1019
+ label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split()
1020
+ labels.extend(label_str_list)
1021
+ return sorted(set(labels))
1022
+
1023
+ def _label_str_to_tensor(self, label_str: str):
1024
+ labels = label_str.split(self.delimiter) if self.delimiter else label_str.split()
1025
+
1026
+ if self.is_regression_task:
1027
+ labels = [float(s) for s in labels]
1028
+ labels = torch.tensor(labels).float()
1029
+ else:
1030
+ labels = [self.label2id[s] for s in labels]
1031
+ labels = torch.tensor(labels).long()
1032
+ return labels
1033
+
1034
+ def __len__(self):
1035
+ return len(self.collection)
1036
+
1037
+ def __getitem__(self, index):
1038
+ sample = self.collection[index]
1039
+
1040
+ offset = sample.offset
1041
+
1042
+ if offset is None:
1043
+ offset = 0
1044
+
1045
+ features = self.featurizer.process(
1046
+ sample.audio_file,
1047
+ offset=offset,
1048
+ duration=sample.duration,
1049
+ trim=self.trim,
1050
+ channel_selector=self.channel_selector,
1051
+ normalize_db=self.normalize_audio_db,
1052
+ )
1053
+
1054
+ f, fl = features, torch.tensor(features.size(0)).long()
1055
+
1056
+ t = self._label_str_to_tensor(sample.label)
1057
+
1058
+ tl = torch.tensor(t.size(0)).long()
1059
+
1060
+ return f, fl, t, tl
1061
+
1062
+ def _collate_fn(self, batch):
1063
+ return _speech_collate_fn(batch, pad_id=0)
1064
+
1065
+
1066
+ class TarredAudioToMultiLabelDataset(IterableDataset):
1067
+ """
1068
+ A similar Dataset to the AudioToMultiLabelDataset, but which loads tarred audio files.
1069
+
1070
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset),
1071
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
1072
+ contain the information for one audio file, including at least the transcript and name of the audio
1073
+ file within the tarball.
1074
+
1075
+ Valid formats for the audio_tar_filepaths argument include:
1076
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
1077
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
1078
+
1079
+ See the WebDataset documentation for more information about accepted data and input formats.
1080
+
1081
+ If using multiple processes the number of shards should be divisible by the number of workers to ensure an
1082
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
1083
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
1084
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
1085
+
1086
+ Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been
1087
+ replaced by shuffle_n (int).
1088
+
1089
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
1090
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
1091
+
1092
+ Args:
1093
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
1094
+ string (can be brace-expandable).
1095
+ manifest_filepath (str): Path to the manifest.
1096
+ labels (list): Dataset parameter.
1097
+ List of target classes that can be output by the speaker recognition model.
1098
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
1099
+ See WebDataset documentation for more details.
1100
+ Defaults to 0.
1101
+ min_duration (float): Dataset parameter.
1102
+ All training files which have a duration less than min_duration
1103
+ are dropped. Note: Duration is read from the manifest JSON.
1104
+ Defaults to 0.1.
1105
+ max_duration (float): Dataset parameter.
1106
+ All training files which have a duration more than max_duration
1107
+ are dropped. Note: Duration is read from the manifest JSON.
1108
+ Defaults to None.
1109
+ trim(bool): Whether to use trim silence from beginning and end
1110
+ of audio signal using librosa.effects.trim().
1111
+ Defaults to False.
1112
+ window_length_in_sec (float): time length of window/slice (in seconds) # Pass this only for speaker recognition and VAD task
1113
+ shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task. in a batch # Pass this only for VAD task during inference.
1114
+ normalize_audio (bool): Whether to normalize audio signal. Defaults to False.
1115
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
1116
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
1117
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
1118
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
1119
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
1120
+ The benefit of replication is that it allows each node to sample data points from the entire
1121
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
1122
+
1123
+ .. warning::
1124
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
1125
+ and therefore more than one node may sample the same tarfile, and even sample the same
1126
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
1127
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
1128
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
1129
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
1130
+ or test datasets.
1131
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
1132
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
1133
+ delimiter (Optional[str]): Delimiter to use when splitting the label string, default to None.
1134
+ normalize_audio_db (Optional[float]): normalize audio signal to a target db, default to None.
1135
+ """
1136
+
1137
+ def __init__(
1138
+ self,
1139
+ *,
1140
+ audio_tar_filepaths: Union[str, List[str]],
1141
+ manifest_filepath: Union[str, List[str]],
1142
+ sample_rate: int,
1143
+ labels: Optional[List[str]] = None,
1144
+ shuffle_n: int = 0,
1145
+ int_values: bool = False,
1146
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
1147
+ min_duration: Optional[float] = 0.1,
1148
+ max_duration: Optional[float] = None,
1149
+ trim_silence: bool = False,
1150
+ is_regression_task: bool = False,
1151
+ shard_strategy: str = "scatter",
1152
+ global_rank: int = 0,
1153
+ world_size: int = 0,
1154
+ delimiter: Optional[str] = None,
1155
+ normalize_audio_db: Optional[float] = None,
1156
+ ):
1157
+ super().__init__()
1158
+ if isinstance(manifest_filepath, str):
1159
+ manifest_filepath = manifest_filepath.split(',')
1160
+
1161
+ self.trim = trim_silence
1162
+ self.is_regression_task = is_regression_task
1163
+ self.delimiter = delimiter
1164
+ self.normalize_audio_db = normalize_audio_db
1165
+
1166
+ self.collection = collections.ASRSpeechLabel(
1167
+ manifests_files=manifest_filepath,
1168
+ min_duration=min_duration,
1169
+ max_duration=max_duration,
1170
+ is_regression_task=is_regression_task,
1171
+ index_by_file_id=True,
1172
+ )
1173
+ self.file_occurence = count_occurence(self.collection.mapping)
1174
+
1175
+ self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)
1176
+
1177
+ if not is_regression_task:
1178
+ self.labels = labels if labels else self._get_label_set()
1179
+ self.num_classes = len(self.labels) if self.labels is not None else 1
1180
+ self.label2id, self.id2label = {}, {}
1181
+ for label_id, label in enumerate(self.labels):
1182
+ self.label2id[label] = label_id
1183
+ self.id2label[label_id] = label
1184
+ for idx in range(len(self.labels[:5])):
1185
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
1186
+ else:
1187
+ self.labels = []
1188
+ self.num_classes = 1
1189
+
1190
+ audio_tar_filepaths = expand_sharded_filepaths(
1191
+ sharded_filepaths=audio_tar_filepaths,
1192
+ shard_strategy=shard_strategy,
1193
+ world_size=world_size,
1194
+ global_rank=global_rank,
1195
+ )
1196
+ # Put together WebDataset
1197
+ self._dataset = wds.DataPipeline(
1198
+ wds.SimpleShardList(urls=audio_tar_filepaths),
1199
+ webdataset_split_by_workers,
1200
+ wds.shuffle(shuffle_n),
1201
+ wds.tarfile_to_samples(),
1202
+ wds.rename(audio=VALID_FILE_FORMATS, key='__key__'),
1203
+ wds.to_tuple('audio', 'key'),
1204
+ self._filter,
1205
+ wds.map(self._build_sample),
1206
+ )
1207
+
1208
+ def _get_label_set(self):
1209
+ labels = []
1210
+ for sample in self.collection:
1211
+ label_str = sample.label
1212
+ if label_str:
1213
+ label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split()
1214
+ labels.extend(label_str_list)
1215
+ return sorted(set(labels))
1216
+
1217
+ def _label_str_to_tensor(self, label_str: str):
1218
+ labels = label_str.split(self.delimiter) if self.delimiter else label_str.split()
1219
+
1220
+ if self.is_regression_task:
1221
+ labels = [float(s) for s in labels]
1222
+ labels = torch.tensor(labels).float()
1223
+ else:
1224
+ labels = [self.label2id[s] for s in labels]
1225
+ labels = torch.tensor(labels).long()
1226
+ return labels
1227
+
1228
+ def _filter(self, iterator):
1229
+ """This function is used to remove samples that have been filtered out by ASRSpeechLabel already.
1230
+ Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample
1231
+ that was filtered out (e.g. for duration).
1232
+ Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard,
1233
+ which may make your code hang as one process will finish before the other.
1234
+ """
1235
+
1236
+ class TarredAudioFilter:
1237
+ def __init__(self, collection, file_occurence):
1238
+ self.iterator = iterator
1239
+ self.collection = collection
1240
+ self.file_occurence = file_occurence
1241
+ self._iterable = self._internal_generator()
1242
+
1243
+ def __iter__(self):
1244
+ self._iterable = self._internal_generator()
1245
+ return self
1246
+
1247
+ def __next__(self):
1248
+ try:
1249
+ values = next(self._iterable)
1250
+ except StopIteration:
1251
+ # reset generator
1252
+ self._iterable = self._internal_generator()
1253
+ values = next(self._iterable)
1254
+
1255
+ return values
1256
+
1257
+ def _internal_generator(self):
1258
+ """
1259
+ WebDataset requires an Iterator, but we require an iterable that yields 1-or-more
1260
+ values per value inside self.iterator.
1261
+
1262
+ Therefore wrap the iterator with a generator function that will yield 1-or-more
1263
+ values per sample in the iterator.
1264
+ """
1265
+ for _, tup in enumerate(self.iterator):
1266
+ audio_bytes, audio_filename = tup
1267
+
1268
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
1269
+ if audio_filename in self.file_occurence:
1270
+ for j in range(0, self.file_occurence[file_id]):
1271
+ if j == 0:
1272
+ audio_filename = file_id
1273
+ else:
1274
+ audio_filename = file_id + "-sub" + str(j)
1275
+ yield audio_bytes, audio_filename
1276
+
1277
+ return TarredAudioFilter(self.collection, self.file_occurence)
1278
+
1279
+ def _build_sample(self, tup):
1280
+ """Builds the training sample by combining the data from the WebDataset with the manifest info."""
1281
+ audio_bytes, audio_filename = tup
1282
+ # Grab manifest entry from self.collection
1283
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
1284
+
1285
+ manifest_idx = self.collection.mapping[file_id]
1286
+ manifest_entry = self.collection[manifest_idx]
1287
+
1288
+ offset = manifest_entry.offset
1289
+ if offset is None:
1290
+ offset = 0
1291
+
1292
+ # Convert audio bytes to IO stream for processing (for SoundFile to read)
1293
+ audio_filestream = io.BytesIO(audio_bytes)
1294
+ features = self.featurizer.process(
1295
+ audio_filestream,
1296
+ offset=offset,
1297
+ duration=manifest_entry.duration,
1298
+ trim=self.trim,
1299
+ normalize_db=self.normalize_audio_db,
1300
+ )
1301
+
1302
+ audio_filestream.close()
1303
+
1304
+ # Audio features
1305
+ f, fl = features, torch.tensor(features.shape[0]).long()
1306
+
1307
+ t = self._label_str_to_tensor(manifest_entry.label)
1308
+
1309
+ tl = torch.tensor(t.size(0)).long()
1310
+
1311
+ return f, fl, t, tl
1312
+
1313
+ def __iter__(self):
1314
+ return self._dataset.__iter__()
1315
+
1316
+ def __len__(self):
1317
+ return len(self.collection)
1318
+
1319
+ def _collate_fn(self, batch):
1320
+ return _speech_collate_fn(batch, pad_id=0)
1321
+
1322
+
1323
+ class AudioPairToLabelDataset(AudioToSpeechLabelDataset):
1324
+ """
1325
+ Dataset class for audio pairs classification tasks, such as calculating EER for speaker verification.
1326
+ The input manifest file should contain pairs of audio files and a label. It's format is almost the same as
1327
+ `AudioToSpeechLabelDataset` except that the `audio_filepath` field should be a list of two audio file paths
1328
+ instead of one, and that `offset` and `duration` are not used as the dataset class will load the whole audio.
1329
+
1330
+ Example of a line in the manifest file:
1331
+ {
1332
+ "audio_filepath": ["/path/to/audio_wav_0.wav", "/path/to/audio_wav_1.wav"],
1333
+ "duration": null, # not used, will load the whole audio
1334
+ "offset": 0.0, # not used, will load the whole audio
1335
+ "label": "0" # label for the pair, can be a string or an integer
1336
+ }
1337
+
1338
+ """
1339
+
1340
+ @property
1341
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
1342
+ """Returns definitions of module output ports."""
1343
+
1344
+ output_types = {
1345
+ 'audio_signal': NeuralType(
1346
+ ('B', 'T'),
1347
+ (
1348
+ AudioSignal(freq=self._sample_rate)
1349
+ if self is not None and hasattr(self, '_sample_rate')
1350
+ else AudioSignal()
1351
+ ),
1352
+ ),
1353
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
1354
+ 'audio_signal_2': NeuralType(
1355
+ ('B', 'T'),
1356
+ (
1357
+ AudioSignal(freq=self._sample_rate)
1358
+ if self is not None and hasattr(self, '_sample_rate')
1359
+ else AudioSignal()
1360
+ ),
1361
+ ),
1362
+ 'a_sig_length_2': NeuralType(tuple('B'), LengthsType()),
1363
+ 'label': NeuralType(tuple('B'), LabelsType()),
1364
+ 'label_length': NeuralType(tuple('B'), LengthsType()),
1365
+ }
1366
+
1367
+ return output_types
1368
+
1369
+ def __init__(
1370
+ self,
1371
+ *,
1372
+ manifest_filepath: str | List[str],
1373
+ labels: List[str],
1374
+ featurizer,
1375
+ min_duration: float | None = 0.1,
1376
+ max_duration: float | None = None,
1377
+ trim: bool = False,
1378
+ window_length_in_sec: float | None = 8,
1379
+ shift_length_in_sec: float | None = 1,
1380
+ normalize_audio: bool = False,
1381
+ **kwargs,
1382
+ ):
1383
+ super().__init__(
1384
+ manifest_filepath=manifest_filepath,
1385
+ labels=labels,
1386
+ featurizer=featurizer,
1387
+ min_duration=min_duration,
1388
+ max_duration=max_duration,
1389
+ trim=trim,
1390
+ window_length_in_sec=window_length_in_sec,
1391
+ shift_length_in_sec=shift_length_in_sec,
1392
+ normalize_audio=normalize_audio,
1393
+ is_regression_task=False,
1394
+ cal_labels_occurrence=False,
1395
+ )
1396
+
1397
+ def __getitem__(self, index):
1398
+ sample = self.collection[index]
1399
+
1400
+ audio_pair = sample.audio_file
1401
+
1402
+ features = self.featurizer.process(audio_pair[0], offset=0, duration=None, trim=self.trim)
1403
+ f, fl = features, torch.tensor(features.shape[0]).long()
1404
+
1405
+ features2 = self.featurizer.process(audio_pair[1], offset=0, duration=None, trim=self.trim)
1406
+ f2, fl2 = features2, torch.tensor(features2.shape[0]).long()
1407
+
1408
+ t = torch.tensor(self.label2id[sample.label]).long()
1409
+ tl = torch.tensor(1).long() # For compatibility with collate_fn used later
1410
+
1411
+ return f, fl, f2, fl2, t, tl
1412
+
1413
+ def fixed_seq_collate_fn(self, batch):
1414
+ audio1, audio_len1, audio2, audio_len2, label, label_len = zip(*batch)
1415
+
1416
+ batch1 = list(zip(audio1, audio_len1, label, label_len))
1417
+ a_sig1, a_sig_len1, pair_label, pair_label_len = _fixed_seq_collate_fn(self, batch1)
1418
+ batch2 = list(zip(audio2, audio_len2, label, label_len))
1419
+ a_sig2, a_sig_len2, _, _ = _fixed_seq_collate_fn(self, batch2)
1420
+ return a_sig1, a_sig_len1, a_sig2, a_sig_len2, pair_label, pair_label_len
nemo/collections/asr/data/audio_to_label_dataset.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import copy
15
+
16
+ from omegaconf import DictConfig
17
+
18
+ from nemo.collections.asr.data import audio_to_label
19
+ from nemo.collections.asr.data.audio_to_text_dataset import convert_to_config_list, get_chain_dataset
20
+ from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations
21
+ from nemo.collections.common.data.dataset import ConcatDataset
22
+
23
+
24
+ def get_classification_label_dataset(featurizer, config: dict) -> audio_to_label.AudioToClassificationLabelDataset:
25
+ """
26
+ Instantiates a Classification AudioLabelDataset.
27
+
28
+ Args:
29
+ config: Config of the AudioToClassificationLabelDataset.
30
+
31
+ Returns:
32
+ An instance of AudioToClassificationLabelDataset.
33
+ """
34
+ dataset = audio_to_label.AudioToClassificationLabelDataset(
35
+ manifest_filepath=config['manifest_filepath'],
36
+ labels=config['labels'],
37
+ featurizer=featurizer,
38
+ max_duration=config.get('max_duration', None),
39
+ min_duration=config.get('min_duration', None),
40
+ trim=config.get('trim_silence', False),
41
+ is_regression_task=config.get('is_regression_task', False),
42
+ cal_labels_occurrence=config.get('cal_labels_occurrence', False),
43
+ )
44
+ return dataset
45
+
46
+
47
+ def get_speech_label_dataset(featurizer, config: dict) -> audio_to_label.AudioToSpeechLabelDataset:
48
+ """
49
+ Instantiates a Speech Label (e.g. VAD, speaker recognition) AudioLabelDataset.
50
+
51
+ Args:
52
+ config: Config of the AudioToSpeechLabelDataSet.
53
+
54
+ Returns:
55
+ An instance of AudioToSpeechLabelDataset.
56
+ """
57
+ dataset = audio_to_label.AudioToSpeechLabelDataset(
58
+ manifest_filepath=config['manifest_filepath'],
59
+ labels=config['labels'],
60
+ featurizer=featurizer,
61
+ max_duration=config.get('max_duration', None),
62
+ min_duration=config.get('min_duration', None),
63
+ trim=config.get('trim_silence', False),
64
+ window_length_in_sec=config.get('window_length_in_sec', 0.31),
65
+ shift_length_in_sec=config.get('shift_length_in_sec', 0.01),
66
+ normalize_audio=config.get('normalize_audio', False),
67
+ cal_labels_occurrence=config.get('cal_labels_occurrence', False),
68
+ )
69
+ return dataset
70
+
71
+
72
+ def get_tarred_classification_label_dataset(
73
+ featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int
74
+ ) -> audio_to_label.TarredAudioToClassificationLabelDataset:
75
+ """
76
+ Instantiates a Classification TarredAudioLabelDataset.
77
+
78
+ Args:
79
+ config: Config of the TarredAudioToClassificationLabelDataset.
80
+ shuffle_n: How many samples to look ahead and load to be shuffled.
81
+ See WebDataset documentation for more details.
82
+ global_rank: Global rank of this device.
83
+ world_size: Global world size in the training method.
84
+
85
+ Returns:
86
+ An instance of TarredAudioToClassificationLabelDataset.
87
+ """
88
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
89
+ manifest_filepaths = config['manifest_filepath']
90
+ datasets = []
91
+ tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths)
92
+ manifest_filepaths = convert_to_config_list(manifest_filepaths)
93
+
94
+ bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets
95
+ if bucketing_weights:
96
+ for idx, weight in enumerate(bucketing_weights):
97
+ if not isinstance(weight, int) or weight <= 0:
98
+ raise ValueError(f"bucket weights must be positive integers")
99
+
100
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
101
+ raise ValueError(
102
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets."
103
+ )
104
+
105
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
106
+ zip(tarred_audio_filepaths, manifest_filepaths)
107
+ ):
108
+ if len(tarred_audio_filepath) == 1:
109
+ tarred_audio_filepath = tarred_audio_filepath[0]
110
+ dataset = audio_to_label.TarredAudioToClassificationLabelDataset(
111
+ audio_tar_filepaths=tarred_audio_filepath,
112
+ manifest_filepath=manifest_filepath,
113
+ labels=config['labels'],
114
+ featurizer=featurizer,
115
+ shuffle_n=shuffle_n,
116
+ max_duration=config.get('max_duration', None),
117
+ min_duration=config.get('min_duration', None),
118
+ trim=config.get('trim_silence', False),
119
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
120
+ global_rank=global_rank,
121
+ world_size=world_size,
122
+ is_regression_task=config.get('is_regression_task', False),
123
+ )
124
+
125
+ if bucketing_weights:
126
+ [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])]
127
+ else:
128
+ datasets.append(dataset)
129
+
130
+ return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank)
131
+
132
+
133
+ def get_concat_tarred_speech_label_dataset(
134
+ featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int,
135
+ ):
136
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
137
+ manifest_filepaths = config['manifest_filepath']
138
+ datasets = []
139
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
140
+ zip(tarred_audio_filepaths, manifest_filepaths)
141
+ ):
142
+ conf = copy.deepcopy(config)
143
+ conf['manifest_filepath'] = manifest_filepath
144
+ conf['tarred_audio_filepaths'] = tarred_audio_filepath
145
+ dataset = get_tarred_speech_label_dataset(
146
+ config=conf, featurizer=featurizer, shuffle_n=shuffle_n, global_rank=global_rank, world_size=world_size,
147
+ )
148
+ datasets.append(dataset)
149
+
150
+ dataset = ConcatDataset(
151
+ datasets,
152
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
153
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
154
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
155
+ global_rank=global_rank,
156
+ world_size=world_size,
157
+ shuffle=config['shuffle'],
158
+ )
159
+ return dataset
160
+
161
+
162
+ def get_tarred_speech_label_dataset(
163
+ featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int,
164
+ ) -> audio_to_label.TarredAudioToSpeechLabelDataset:
165
+ """
166
+ InInstantiates a Speech Label (e.g. VAD, speaker recognition) TarredAudioLabelDataset.
167
+
168
+ Args:
169
+ config: Config of the TarredAudioToSpeechLabelDataset.
170
+ shuffle_n: How many samples to look ahead and load to be shuffled.
171
+ See WebDataset documentation for more details.
172
+ global_rank: Global rank of this device.
173
+ world_size: Global world size in the training method.
174
+
175
+ Returns:
176
+ An instance of TarredAudioToSpeechLabelDataset.
177
+ """
178
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
179
+ manifest_filepaths = config['manifest_filepath']
180
+ datasets = []
181
+ tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths)
182
+ manifest_filepaths = convert_to_config_list(manifest_filepaths)
183
+
184
+ bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets
185
+ if bucketing_weights:
186
+ for idx, weight in enumerate(bucketing_weights):
187
+ if not isinstance(weight, int) or weight <= 0:
188
+ raise ValueError(f"bucket weights must be positive integers")
189
+
190
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
191
+ raise ValueError(
192
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets."
193
+ )
194
+
195
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
196
+ zip(tarred_audio_filepaths, manifest_filepaths)
197
+ ):
198
+ if len(tarred_audio_filepath) == 1:
199
+ tarred_audio_filepath = tarred_audio_filepath[0]
200
+ dataset = audio_to_label.TarredAudioToSpeechLabelDataset(
201
+ audio_tar_filepaths=tarred_audio_filepath,
202
+ manifest_filepath=manifest_filepath,
203
+ labels=config['labels'],
204
+ featurizer=featurizer,
205
+ shuffle_n=shuffle_n,
206
+ max_duration=config.get('max_duration', None),
207
+ min_duration=config.get('min_duration', None),
208
+ trim=config.get('trim_silence', False),
209
+ window_length_in_sec=config.get('window_length_in_sec', 8),
210
+ shift_length_in_sec=config.get('shift_length_in_sec', 0.075),
211
+ normalize_audio=config.get('normalize_audio', False),
212
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
213
+ global_rank=global_rank,
214
+ world_size=world_size,
215
+ )
216
+
217
+ if bucketing_weights:
218
+ [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])]
219
+ else:
220
+ datasets.append(dataset)
221
+
222
+ return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank)
223
+
224
+
225
+ def get_audio_multi_label_dataset(cfg: DictConfig) -> audio_to_label.AudioToMultiLabelDataset:
226
+ if "augmentor" in cfg:
227
+ augmentor = process_augmentations(cfg.augmentor)
228
+ else:
229
+ augmentor = None
230
+
231
+ dataset = audio_to_label.AudioToMultiLabelDataset(
232
+ manifest_filepath=cfg.get("manifest_filepath"),
233
+ sample_rate=cfg.get("sample_rate"),
234
+ labels=cfg.get("labels", None),
235
+ int_values=cfg.get("int_values", False),
236
+ augmentor=augmentor,
237
+ min_duration=cfg.get("min_duration", None),
238
+ max_duration=cfg.get("max_duration", None),
239
+ trim_silence=cfg.get("trim_silence", False),
240
+ is_regression_task=cfg.get("is_regression_task", False),
241
+ cal_labels_occurrence=cfg.get("cal_labels_occurrence", False),
242
+ delimiter=cfg.get("delimiter", None),
243
+ normalize_audio_db=cfg.get("normalize_audio_db", None),
244
+ )
245
+ return dataset
246
+
247
+
248
+ def get_tarred_audio_multi_label_dataset(
249
+ cfg: DictConfig, shuffle_n: int, global_rank: int, world_size: int
250
+ ) -> audio_to_label.TarredAudioToMultiLabelDataset:
251
+
252
+ if "augmentor" in cfg:
253
+ augmentor = process_augmentations(cfg.augmentor)
254
+ else:
255
+ augmentor = None
256
+
257
+ tarred_audio_filepaths = cfg['tarred_audio_filepaths']
258
+ manifest_filepaths = cfg['manifest_filepath']
259
+ datasets = []
260
+ tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths)
261
+ manifest_filepaths = convert_to_config_list(manifest_filepaths)
262
+
263
+ bucketing_weights = cfg.get('bucketing_weights', None) # For upsampling buckets
264
+ if bucketing_weights:
265
+ for idx, weight in enumerate(bucketing_weights):
266
+ if not isinstance(weight, int) or weight <= 0:
267
+ raise ValueError(f"bucket weights must be positive integers")
268
+
269
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
270
+ raise ValueError(
271
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets."
272
+ )
273
+
274
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
275
+ zip(tarred_audio_filepaths, manifest_filepaths)
276
+ ):
277
+ if len(tarred_audio_filepath) == 1:
278
+ tarred_audio_filepath = tarred_audio_filepath[0]
279
+
280
+ dataset = audio_to_label.TarredAudioToMultiLabelDataset(
281
+ audio_tar_filepaths=tarred_audio_filepath,
282
+ manifest_filepath=manifest_filepath,
283
+ sample_rate=cfg["sample_rate"],
284
+ labels=cfg['labels'],
285
+ shuffle_n=shuffle_n,
286
+ int_values=cfg.get("int_values", False),
287
+ augmentor=augmentor,
288
+ min_duration=cfg.get('min_duration', None),
289
+ max_duration=cfg.get('max_duration', None),
290
+ trim_silence=cfg.get('trim_silence', False),
291
+ is_regression_task=cfg.get('is_regression_task', False),
292
+ delimiter=cfg.get("delimiter", None),
293
+ shard_strategy=cfg.get('tarred_shard_strategy', 'scatter'),
294
+ global_rank=global_rank,
295
+ world_size=world_size,
296
+ normalize_audio_db=cfg.get("normalize_audio_db", None),
297
+ )
298
+
299
+ if bucketing_weights:
300
+ [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])]
301
+ else:
302
+ datasets.append(dataset)
303
+
304
+ return get_chain_dataset(datasets=datasets, ds_config=cfg, rank=global_rank)
nemo/collections/asr/data/audio_to_text.py ADDED
@@ -0,0 +1,1404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import io
15
+ import json
16
+ import math
17
+ import multiprocessing
18
+ import os
19
+ from collections.abc import Iterable as IterableABC
20
+ from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
21
+
22
+ import braceexpand
23
+ import numpy as np
24
+ import torch
25
+ import webdataset as wds
26
+ from torch.utils.data import ChainDataset
27
+ from tqdm import tqdm
28
+
29
+ from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer
30
+ from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType
31
+ from nemo.collections.asr.parts.preprocessing.segment import available_formats as valid_sf_formats
32
+ from nemo.collections.common import tokenizers
33
+ from nemo.collections.common.parts.preprocessing import collections, parsers
34
+ from nemo.core.classes import Dataset, IterableDataset
35
+ from nemo.core.neural_types import *
36
+ from nemo.utils import logging
37
+ from nemo.utils.data_utils import (
38
+ DataStoreObject,
39
+ datastore_object_get,
40
+ datastore_path_to_webdataset_url,
41
+ is_datastore_cache_shared,
42
+ is_datastore_path,
43
+ is_tarred_path,
44
+ )
45
+ from nemo.utils.decorators import deprecated
46
+ from nemo.utils.distributed import webdataset_split_by_workers
47
+ from nemo.utils.get_rank import is_global_rank_zero
48
+
49
+ __all__ = [
50
+ 'AudioToCharDataset',
51
+ 'AudioToBPEDataset',
52
+ 'TarredAudioToCharDataset',
53
+ 'TarredAudioToBPEDataset',
54
+ ]
55
+
56
+ VALID_FILE_FORMATS = ';'.join(['wav', 'mp3', 'flac', 'opus'] + [fmt.lower() for fmt in valid_sf_formats.keys()])
57
+
58
+
59
+ def _speech_collate_fn(batch, pad_id):
60
+ """collate batch of audio sig, audio len, tokens, tokens len
61
+ Args:
62
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
63
+ LongTensor): A tuple of tuples of signal, signal lengths,
64
+ encoded tokens, and encoded tokens length. This collate func
65
+ assumes the signals are 1d torch tensors (i.e. mono audio).
66
+ """
67
+ packed_batch = list(zip(*batch))
68
+ if len(packed_batch) == 5:
69
+ _, audio_lengths, _, tokens_lengths, sample_ids = packed_batch
70
+ elif len(packed_batch) == 4:
71
+ sample_ids = None
72
+ _, audio_lengths, _, tokens_lengths = packed_batch
73
+ else:
74
+ raise ValueError("Expects 4 or 5 tensors in the batch!")
75
+ max_audio_len = 0
76
+ has_audio = audio_lengths[0] is not None
77
+ if has_audio:
78
+ max_audio_len = max(audio_lengths).item()
79
+ has_tokens = tokens_lengths[0] is not None
80
+ if has_tokens:
81
+ max_tokens_len = max(tokens_lengths).item()
82
+
83
+ audio_signal, tokens = [], []
84
+ for b in batch:
85
+ if len(b) == 5:
86
+ sig, sig_len, tokens_i, tokens_i_len, _ = b
87
+ else:
88
+ sig, sig_len, tokens_i, tokens_i_len = b
89
+ if has_audio:
90
+ sig_len = sig_len.item()
91
+ if sig_len < max_audio_len:
92
+ pad = (0, max_audio_len - sig_len)
93
+ sig = torch.nn.functional.pad(sig, pad)
94
+ audio_signal.append(sig)
95
+ if has_tokens:
96
+ tokens_i_len = tokens_i_len.item()
97
+ if tokens_i_len < max_tokens_len:
98
+ pad = (0, max_tokens_len - tokens_i_len)
99
+ tokens_i = torch.nn.functional.pad(tokens_i, pad, value=pad_id)
100
+ tokens.append(tokens_i)
101
+
102
+ if has_audio:
103
+ audio_signal = torch.stack(audio_signal)
104
+ audio_lengths = torch.stack(audio_lengths)
105
+ else:
106
+ audio_signal, audio_lengths = None, None
107
+ if has_tokens:
108
+ tokens = torch.stack(tokens)
109
+ tokens_lengths = torch.stack(tokens_lengths)
110
+ else:
111
+ tokens = None
112
+ tokens_lengths = None
113
+ if sample_ids is None:
114
+ return audio_signal, audio_lengths, tokens, tokens_lengths
115
+ else:
116
+ sample_ids = torch.tensor(sample_ids, dtype=torch.int32)
117
+ return audio_signal, audio_lengths, tokens, tokens_lengths, sample_ids
118
+
119
+
120
+ class ASRManifestProcessor:
121
+ """
122
+ Class that processes a manifest json file containing paths to audio files, transcripts, and durations (in seconds).
123
+ Each new line is a different sample. Example below:
124
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147}
125
+ ...
126
+ {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
127
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
128
+ Args:
129
+ manifest_filepath: Path to manifest json as described above. Can be comma-separated paths.
130
+ parser: Str for a language specific preprocessor or a callable.
131
+ max_duration: If audio exceeds this length, do not include in dataset.
132
+ min_duration: If audio is less than this length, do not include in dataset.
133
+ max_utts: Limit number of utterances.
134
+ bos_id: Id of beginning of sequence symbol to append if not None.
135
+ eos_id: Id of end of sequence symbol to append if not None.
136
+ pad_id: Id of pad symbol. Defaults to 0.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ manifest_filepath: str,
142
+ parser: Union[str, Callable],
143
+ max_duration: Optional[float] = None,
144
+ min_duration: Optional[float] = None,
145
+ max_utts: int = 0,
146
+ bos_id: Optional[int] = None,
147
+ eos_id: Optional[int] = None,
148
+ pad_id: int = 0,
149
+ index_by_file_id: bool = False,
150
+ manifest_parse_func: Optional[Callable] = None,
151
+ ):
152
+ self.parser = parser
153
+
154
+ self.collection = collections.ASRAudioText(
155
+ manifests_files=manifest_filepath,
156
+ parser=parser,
157
+ min_duration=min_duration,
158
+ max_duration=max_duration,
159
+ max_number=max_utts,
160
+ index_by_file_id=index_by_file_id,
161
+ parse_func=manifest_parse_func,
162
+ )
163
+
164
+ self.eos_id = eos_id
165
+ self.bos_id = bos_id
166
+ self.pad_id = pad_id
167
+
168
+ def process_text_by_id(self, index: int) -> Tuple[List[int], int]:
169
+ sample = self.collection[index]
170
+ return self.process_text_by_sample(sample)
171
+
172
+ def process_text_by_file_id(self, file_id: str) -> Tuple[List[int], int]:
173
+ manifest_idx = self.collection.mapping[file_id][0]
174
+ sample = self.collection[manifest_idx]
175
+ return self.process_text_by_sample(sample)
176
+
177
+ def process_text_by_sample(self, sample: collections.ASRAudioText.OUTPUT_TYPE) -> Tuple[List[int], int]:
178
+ t, tl = sample.text_tokens, len(sample.text_tokens)
179
+
180
+ if self.bos_id is not None:
181
+ t = [self.bos_id] + t
182
+ tl += 1
183
+ if self.eos_id is not None:
184
+ t = t + [self.eos_id]
185
+ tl += 1
186
+
187
+ return t, tl
188
+
189
+
190
+ def expand_sharded_filepaths(sharded_filepaths, shard_strategy: str, world_size: int, global_rank: int):
191
+ valid_shard_strategies = ['scatter', 'replicate']
192
+ if shard_strategy not in valid_shard_strategies:
193
+ raise ValueError(f"`shard_strategy` must be one of {valid_shard_strategies}")
194
+
195
+ if isinstance(sharded_filepaths, str):
196
+ # Replace '(' and '[' with '{'
197
+ brace_keys_open = ['(', '[', '<', '_OP_']
198
+ for bkey in brace_keys_open:
199
+ if bkey in sharded_filepaths:
200
+ sharded_filepaths = sharded_filepaths.replace(bkey, "{")
201
+
202
+ # Replace ')' and ']' with '}'
203
+ brace_keys_close = [')', ']', '>', '_CL_']
204
+ for bkey in brace_keys_close:
205
+ if bkey in sharded_filepaths:
206
+ sharded_filepaths = sharded_filepaths.replace(bkey, "}")
207
+
208
+ if isinstance(sharded_filepaths, str):
209
+ # Brace expand, set escape=False for Windows compatibility
210
+ sharded_filepaths = list(braceexpand.braceexpand(sharded_filepaths, escape=False))
211
+
212
+ # Expand store paths into WebDataset URLs
213
+ sharded_filepaths = [
214
+ datastore_path_to_webdataset_url(p) if is_datastore_path(p) and is_tarred_path(p) else p
215
+ for p in sharded_filepaths
216
+ ]
217
+
218
+ # Check for distributed and partition shards accordingly
219
+ if world_size > 1:
220
+ if shard_strategy == 'scatter':
221
+ logging.info("All tarred dataset shards will be scattered evenly across all nodes.")
222
+
223
+ if len(sharded_filepaths) % world_size != 0:
224
+ logging.warning(
225
+ f"Number of shards in tarred dataset ({len(sharded_filepaths)}) is not divisible "
226
+ f"by number of distributed workers ({world_size})."
227
+ )
228
+
229
+ begin_idx = (len(sharded_filepaths) // world_size) * global_rank
230
+ end_idx = begin_idx + len(sharded_filepaths) // world_size
231
+ sharded_filepaths = sharded_filepaths[begin_idx:end_idx]
232
+ logging.info(
233
+ "Partitioning tarred dataset: process (%d) taking shards [%d, %d)", global_rank, begin_idx, end_idx
234
+ )
235
+
236
+ elif shard_strategy == 'replicate':
237
+ logging.info("All tarred dataset shards will be replicated across all nodes.")
238
+ else:
239
+ raise ValueError(f"Invalid shard strategy ! Allowed values are : {valid_shard_strategies}")
240
+
241
+ return sharded_filepaths
242
+
243
+
244
+ def cache_datastore_manifests(
245
+ manifest_filepaths: Union[str, List[str]],
246
+ cache_audio: bool = False,
247
+ shared_cache: Optional[bool] = None,
248
+ num_workers: Optional[int] = None,
249
+ max_num_workers: int = 20,
250
+ ):
251
+ """Cache manifests and audio from an object store.
252
+ It is assumed that remote manifests are using relative paths.
253
+
254
+ Args:
255
+ manifest_filepaths: list of paths to manifest files (list of strings or a string with `,` as separator)
256
+ cache_audio: If True, audio from manifest will also be cached
257
+ shared_cache: Optional, True if cache is shared across all nodes
258
+ num_workers: Optional, number of workers to be used for download
259
+ max_num_workers: max number of workers to be used for download, used when setting num_workers automatically
260
+ """
261
+ if isinstance(manifest_filepaths, str):
262
+ manifest_filepaths = manifest_filepaths.split(',')
263
+
264
+ num_datastore_manifests = sum([is_datastore_path(f) for f in manifest_filepaths])
265
+
266
+ if num_datastore_manifests > 0:
267
+ # Local utility function
268
+ def cache_data(manifest_filepaths, cache_audio, num_workers, max_num_workers):
269
+ """Cache manifests and audio data from object store."""
270
+ # Determine the number of workers to use
271
+ if num_workers is None:
272
+ num_workers = os.cpu_count() - 1
273
+ num_workers = min(num_workers, max_num_workers)
274
+
275
+ # Process each manifest file
276
+ for manifest_file in manifest_filepaths:
277
+ # If manifest is on a data store, then cache it.
278
+ # Otherwise, nothing to do.
279
+ if is_datastore_path(manifest_file):
280
+ logging.info('Cache manifest file: %s', manifest_file)
281
+ cached_manifest_file = DataStoreObject(manifest_file).get()
282
+ logging.info('Cached at: %s', str(cached_manifest_file))
283
+
284
+ if cache_audio:
285
+ # Each audio file from manifest will be cached.
286
+ logging.info('Cache audio from manifest file: %s', manifest_file)
287
+ # Assumes that manifest is using relative paths
288
+ manifest_dir = os.path.dirname(manifest_file)
289
+ # Prepare all store objects
290
+ audio_objects = []
291
+ with open(cached_manifest_file, 'r') as f:
292
+ for line in f:
293
+ item = json.loads(line)
294
+ store_path = os.path.join(manifest_dir, item['audio_filepath'])
295
+ audio_objects.append(DataStoreObject(store_path=store_path))
296
+
297
+ if num_workers is not None and num_workers > 1:
298
+ logging.debug('Using multiprocessing with num_workers: %d.', num_workers)
299
+ with multiprocessing.Pool(processes=num_workers) as p:
300
+ result = list(
301
+ tqdm(p.imap(datastore_object_get, audio_objects), total=len(audio_objects))
302
+ )
303
+ else:
304
+ logging.debug('Using a single process.')
305
+ result = []
306
+ for audio_object in tqdm(audio_objects):
307
+ result.append(audio_object.get() is not None)
308
+
309
+ if not all(result):
310
+ raise RuntimeError('Some files not downloaded successfully')
311
+ logging.info('Caching complete')
312
+
313
+ else:
314
+ # Nothing to do here
315
+ logging.debug('Manifest is not on a data store: %s', manifest_file)
316
+
317
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
318
+ logging.debug('Distributed environment is available and initialized.')
319
+
320
+ # Handle distributed environment
321
+ if shared_cache is None:
322
+ shared_cache = is_datastore_cache_shared()
323
+
324
+ if shared_cache:
325
+ logging.debug('Cache is shared among nodes, cache data on global rank zero.')
326
+ is_rank_zero = is_global_rank_zero()
327
+ else:
328
+ logging.debug('Cache is not shared among nodes, cache data on local rank zero.')
329
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
330
+ is_rank_zero = local_rank == 0
331
+
332
+ if is_rank_zero:
333
+ logging.info('Cache data from %s rank 0', 'global' if shared_cache else 'local')
334
+ cache_data(
335
+ manifest_filepaths=manifest_filepaths,
336
+ cache_audio=cache_audio,
337
+ num_workers=num_workers,
338
+ max_num_workers=max_num_workers,
339
+ )
340
+ logging.debug('Reached barrier')
341
+ torch.distributed.barrier()
342
+
343
+ elif is_global_rank_zero():
344
+ # Handle non-distributed environment, e.g., if running on a single GPU
345
+ logging.warning(
346
+ 'Torch distributed is not initialized and caching may be prone to data race conditions. '
347
+ 'Now caching data from global rank 0. If there are other ranks and they pass this '
348
+ 'before rank 0, errors might result.'
349
+ )
350
+ cache_data(
351
+ manifest_filepaths=manifest_filepaths,
352
+ cache_audio=cache_audio,
353
+ num_workers=num_workers,
354
+ max_num_workers=max_num_workers,
355
+ )
356
+ else:
357
+ raise RuntimeError(
358
+ 'Torch distributed is not initialized and caching on nodes other than global rank zero is disabled '
359
+ 'to avoid race condition between different ranks. To ensure distributed environment is '
360
+ 'initialized, please update data config to use `defer_setup = True`.'
361
+ )
362
+
363
+
364
+ """Optionally expand / shard the list of manifests
365
+ This is made to use the same notation as the sharded audio files
366
+
367
+ Args:
368
+ manifest_filepaths: list of manifest files (the sharded notation)
369
+ shard_strategy: scatter or replicate (scatter by default)
370
+ shard_manifests: bool, if False, no sharding / manifest filepath expansion will be attempted
371
+ global_rank: int, the rank of this worker
372
+ world_size: int, total number of workers
373
+ """
374
+
375
+
376
+ def shard_manifests_if_needed(
377
+ manifest_filepaths: Union[str, List[str]],
378
+ shard_strategy: str,
379
+ shard_manifests: bool,
380
+ global_rank: int,
381
+ world_size: int,
382
+ ):
383
+ if shard_manifests:
384
+ if not torch.distributed.is_available():
385
+ logging.warning("Not running in torch.distributed mode. Manifest sharding not available")
386
+ return manifest_filepaths
387
+
388
+ if not torch.distributed.is_initialized():
389
+ logging.warning(
390
+ 'Manifest sharding was requested but torch.distributed is not initialized '
391
+ 'Did you intend to set the defer_setup flag?'
392
+ )
393
+ return manifest_filepaths
394
+
395
+ manifest_filepaths = expand_sharded_filepaths(
396
+ sharded_filepaths=manifest_filepaths,
397
+ shard_strategy=shard_strategy,
398
+ world_size=world_size,
399
+ global_rank=global_rank,
400
+ )
401
+
402
+ return manifest_filepaths
403
+
404
+
405
+ class _AudioTextDataset(Dataset):
406
+ """
407
+ Dataset that loads tensors via a json file containing paths to audio files, transcripts, and durations (in seconds).
408
+ Each new line is a different sample. Example below:
409
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147}
410
+ ...
411
+ {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
412
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
413
+ Args:
414
+ manifest_filepath: Path to manifest json as described above. Can be comma-separated paths.
415
+ parser: Str for a language specific preprocessor or a callable.
416
+ sample_rate (int): Sample rate to resample loaded audio to
417
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
418
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor object used to augment loaded
419
+ audio
420
+ max_duration: If audio exceeds this length, do not include in dataset
421
+ min_duration: If audio is less than this length, do not include in dataset
422
+ max_utts: Limit number of utterances
423
+ trim: whether or not to trim silence. Defaults to False
424
+ bos_id: Id of beginning of sequence symbol to append if not None
425
+ eos_id: Id of end of sequence symbol to append if not None
426
+ pad_id: Id of pad symbol. Defaults to 0
427
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
428
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
429
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
430
+ """
431
+
432
+ @property
433
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
434
+ """Returns definitions of module output ports."""
435
+ return {
436
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
437
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
438
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
439
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
440
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
441
+ }
442
+
443
+ def __init__(
444
+ self,
445
+ manifest_filepath: str,
446
+ parser: Union[str, Callable],
447
+ sample_rate: int,
448
+ int_values: bool = False,
449
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
450
+ max_duration: Optional[int] = None,
451
+ min_duration: Optional[int] = None,
452
+ max_utts: int = 0,
453
+ trim: bool = False,
454
+ bos_id: Optional[int] = None,
455
+ eos_id: Optional[int] = None,
456
+ pad_id: int = 0,
457
+ return_sample_id: bool = False,
458
+ channel_selector: Optional[ChannelSelectorType] = None,
459
+ manifest_parse_func: Optional[Callable] = None,
460
+ ):
461
+ if type(manifest_filepath) == str:
462
+ manifest_filepath = manifest_filepath.split(",")
463
+
464
+ # If necessary, cache manifests and audio from object store
465
+ cache_datastore_manifests(manifest_filepaths=manifest_filepath, cache_audio=True)
466
+
467
+ self.manifest_processor = ASRManifestProcessor(
468
+ manifest_filepath=manifest_filepath,
469
+ parser=parser,
470
+ max_duration=max_duration,
471
+ min_duration=min_duration,
472
+ max_utts=max_utts,
473
+ bos_id=bos_id,
474
+ eos_id=eos_id,
475
+ pad_id=pad_id,
476
+ manifest_parse_func=manifest_parse_func,
477
+ )
478
+ self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)
479
+ self.trim = trim
480
+ self.return_sample_id = return_sample_id
481
+ self.channel_selector = channel_selector
482
+
483
+ def get_manifest_sample(self, sample_id):
484
+ return self.manifest_processor.collection[sample_id]
485
+
486
+ def __getitem__(self, index):
487
+ if isinstance(index, IterableABC):
488
+ return [self._process_sample(_index) for _index in index]
489
+ else:
490
+ return self._process_sample(index)
491
+
492
+ def _process_sample(self, index):
493
+ sample = self.manifest_processor.collection[index]
494
+ offset = sample.offset
495
+
496
+ if offset is None:
497
+ offset = 0
498
+
499
+ features = self.featurizer.process(
500
+ sample.audio_file,
501
+ offset=offset,
502
+ duration=sample.duration,
503
+ trim=self.trim,
504
+ orig_sr=sample.orig_sr,
505
+ channel_selector=self.channel_selector,
506
+ )
507
+ f, fl = features, torch.tensor(features.shape[0]).long()
508
+
509
+ t, tl = self.manifest_processor.process_text_by_sample(sample=sample)
510
+
511
+ if self.return_sample_id:
512
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index
513
+ else:
514
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long()
515
+
516
+ return output
517
+
518
+ def __len__(self):
519
+ return len(self.manifest_processor.collection)
520
+
521
+ def _collate_fn(self, batch):
522
+ return _speech_collate_fn(batch, pad_id=self.manifest_processor.pad_id)
523
+
524
+
525
+ class AudioToCharDataset(_AudioTextDataset):
526
+ """
527
+ Dataset that loads tensors via a json file containing paths to audio
528
+ files, transcripts, and durations (in seconds). Each new line is a
529
+ different sample. Example below:
530
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath":
531
+ "/path/to/audio.txt", "duration": 23.147}
532
+ ...
533
+ {"audio_filepath": "/path/to/audio.wav", "text": "the
534
+ transcription", "offset": 301.75, "duration": 0.82, "utt":
535
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
536
+
537
+ Args:
538
+ manifest_filepath: Path to manifest json as described above. Can
539
+ be comma-separated paths.
540
+ labels: String containing all the possible characters to map to
541
+ sample_rate (int): Sample rate to resample loaded audio to
542
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
543
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
544
+ object used to augment loaded audio
545
+ max_duration: If audio exceeds this length, do not include in dataset
546
+ min_duration: If audio is less than this length, do not include
547
+ in dataset
548
+ max_utts: Limit number of utterances
549
+ blank_index: blank character index, default = -1
550
+ unk_index: unk_character index, default = -1
551
+ normalize: whether to normalize transcript text (default): True
552
+ bos_id: Id of beginning of sequence symbol to append if not None
553
+ eos_id: Id of end of sequence symbol to append if not None
554
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
555
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
556
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
557
+ """
558
+
559
+ @property
560
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
561
+ """Returns definitions of module output ports."""
562
+ return {
563
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
564
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
565
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
566
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
567
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
568
+ }
569
+
570
+ def __init__(
571
+ self,
572
+ manifest_filepath: str,
573
+ labels: Union[str, List[str]],
574
+ sample_rate: int,
575
+ int_values: bool = False,
576
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
577
+ max_duration: Optional[float] = None,
578
+ min_duration: Optional[float] = None,
579
+ max_utts: int = 0,
580
+ blank_index: int = -1,
581
+ unk_index: int = -1,
582
+ normalize: bool = True,
583
+ trim: bool = False,
584
+ bos_id: Optional[int] = None,
585
+ eos_id: Optional[int] = None,
586
+ pad_id: int = 0,
587
+ parser: Union[str, Callable] = 'en',
588
+ return_sample_id: bool = False,
589
+ channel_selector: Optional[ChannelSelectorType] = None,
590
+ manifest_parse_func: Optional[Callable] = None,
591
+ ):
592
+ self.labels = labels
593
+
594
+ parser = parsers.make_parser(
595
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
596
+ )
597
+
598
+ super().__init__(
599
+ manifest_filepath=manifest_filepath,
600
+ parser=parser,
601
+ sample_rate=sample_rate,
602
+ int_values=int_values,
603
+ augmentor=augmentor,
604
+ max_duration=max_duration,
605
+ min_duration=min_duration,
606
+ max_utts=max_utts,
607
+ trim=trim,
608
+ bos_id=bos_id,
609
+ eos_id=eos_id,
610
+ pad_id=pad_id,
611
+ return_sample_id=return_sample_id,
612
+ channel_selector=channel_selector,
613
+ manifest_parse_func=manifest_parse_func,
614
+ )
615
+
616
+
617
+ class AudioToBPEDataset(_AudioTextDataset):
618
+ """
619
+ Dataset that loads tensors via a json file containing paths to audio
620
+ files, transcripts, and durations (in seconds). Each new line is a
621
+ different sample. Example below:
622
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath":
623
+ "/path/to/audio.txt", "duration": 23.147}
624
+ ...
625
+ {"audio_filepath": "/path/to/audio.wav", "text": "the
626
+ transcription", "offset": 301.75, "duration": 0.82, "utt":
627
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
628
+
629
+ In practice, the dataset and manifest used for character encoding and byte pair encoding
630
+ are exactly the same. The only difference lies in how the dataset tokenizes the text in
631
+ the manifest.
632
+
633
+ Args:
634
+ manifest_filepath: Path to manifest json as described above. Can
635
+ be comma-separated paths.
636
+ tokenizer: A subclass of the Tokenizer wrapper found in the common collection,
637
+ nemo.collections.common.tokenizers.TokenizerSpec. ASR Models support a subset of
638
+ all available tokenizers.
639
+ sample_rate (int): Sample rate to resample loaded audio to
640
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
641
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
642
+ object used to augment loaded audio
643
+ max_duration: If audio exceeds this length, do not include in dataset
644
+ min_duration: If audio is less than this length, do not include
645
+ in dataset
646
+ max_utts: Limit number of utterances
647
+ trim: Whether to trim silence segments
648
+ use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS]
649
+ tokens to beginning and ending of speech respectively.
650
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
651
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
652
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
653
+ """
654
+
655
+ @property
656
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
657
+ """Returns definitions of module output ports."""
658
+ return {
659
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
660
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
661
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
662
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
663
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
664
+ }
665
+
666
+ def __init__(
667
+ self,
668
+ manifest_filepath: str,
669
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
670
+ sample_rate: int,
671
+ int_values: bool = False,
672
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
673
+ max_duration: Optional[int] = None,
674
+ min_duration: Optional[int] = None,
675
+ max_utts: int = 0,
676
+ trim: bool = False,
677
+ use_start_end_token: bool = True,
678
+ return_sample_id: bool = False,
679
+ channel_selector: Optional[ChannelSelectorType] = None,
680
+ manifest_parse_func: Optional[Callable] = None,
681
+ ):
682
+ if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0:
683
+ bos_id = tokenizer.bos_id
684
+ else:
685
+ bos_id = None
686
+
687
+ if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0:
688
+ eos_id = tokenizer.eos_id
689
+ else:
690
+ eos_id = None
691
+
692
+ if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0:
693
+ pad_id = tokenizer.pad_id
694
+ else:
695
+ pad_id = 0
696
+
697
+ class TokenizerWrapper:
698
+ def __init__(self, tokenizer):
699
+ if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer):
700
+ self.is_aggregate = True
701
+ else:
702
+ self.is_aggregate = False
703
+ self._tokenizer = tokenizer
704
+
705
+ def __call__(self, *args):
706
+ if isinstance(args[0], List) and self.is_aggregate:
707
+ t = []
708
+ for span in args[0]:
709
+ t.extend(self._tokenizer.text_to_ids(span['str'], span['lang']))
710
+ return t
711
+
712
+ t = self._tokenizer.text_to_ids(*args)
713
+ return t
714
+
715
+ super().__init__(
716
+ manifest_filepath=manifest_filepath,
717
+ parser=TokenizerWrapper(tokenizer),
718
+ sample_rate=sample_rate,
719
+ int_values=int_values,
720
+ augmentor=augmentor,
721
+ max_duration=max_duration,
722
+ min_duration=min_duration,
723
+ max_utts=max_utts,
724
+ bos_id=bos_id,
725
+ eos_id=eos_id,
726
+ pad_id=pad_id,
727
+ trim=trim,
728
+ return_sample_id=return_sample_id,
729
+ channel_selector=channel_selector,
730
+ manifest_parse_func=manifest_parse_func,
731
+ )
732
+
733
+
734
+ @deprecated(
735
+ explanation='Webdataset support will be removed in v2.1.0 versions, please use LhotseSpeechToTextBpeDataset class instead'
736
+ )
737
+ class _TarredAudioToTextDataset(IterableDataset):
738
+ """
739
+ A similar Dataset to the AudioToCharDataset/AudioToBPEDataset, but which loads tarred audio files.
740
+
741
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset/AudioToBPEDataset),
742
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
743
+ contain the information for one audio file, including at least the transcript and name of the audio
744
+ file within the tarball.
745
+
746
+ Valid formats for the audio_tar_filepaths argument include:
747
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
748
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
749
+
750
+ Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference.
751
+ This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements.
752
+ Supported opening braces - { <=> (, [, < and the special tag _OP_.
753
+ Supported closing braces - } <=> ), ], > and the special tag _CL_.
754
+ For SLURM based tasks, we suggest the use of the special tags for ease of use.
755
+
756
+ See the WebDataset documentation for more information about accepted data and input formats.
757
+
758
+ If using multiple workers the number of shards should be divisible by world_size to ensure an
759
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
760
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
761
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
762
+
763
+ Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been
764
+ replaced by shuffle_n (int).
765
+
766
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
767
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
768
+
769
+ Args:
770
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
771
+ string (can be brace-expandable).
772
+ manifest_filepath (str): Path to the manifest.
773
+ parser (callable): A callable which is used to pre-process the text output.
774
+ sample_rate (int): Sample rate to resample loaded audio to
775
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
776
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
777
+ object used to augment loaded audio
778
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
779
+ See WebDataset documentation for more details.
780
+ Defaults to 0.
781
+ min_duration (float): Dataset parameter.
782
+ All training files which have a duration less than min_duration
783
+ are dropped. Note: Duration is read from the manifest JSON.
784
+ Defaults to 0.1.
785
+ max_duration (float): Dataset parameter.
786
+ All training files which have a duration more than max_duration
787
+ are dropped. Note: Duration is read from the manifest JSON.
788
+ Defaults to None.
789
+ blank_index (int): Blank character index, defaults to -1.
790
+ unk_index (int): Unknown character index, defaults to -1.
791
+ normalize (bool): Dataset parameter.
792
+ Whether to use automatic text cleaning.
793
+ It is highly recommended to manually clean text for best results.
794
+ Defaults to True.
795
+ trim (bool): Whether to use trim silence from beginning and end
796
+ of audio signal using librosa.effects.trim().
797
+ Defaults to False.
798
+ bos_id (id): Dataset parameter.
799
+ Beginning of string symbol id used for seq2seq models.
800
+ Defaults to None.
801
+ eos_id (id): Dataset parameter.
802
+ End of string symbol id used for seq2seq models.
803
+ Defaults to None.
804
+ pad_id (id): Token used to pad when collating samples in batches.
805
+ If this is None, pads using 0s.
806
+ Defaults to None.
807
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
808
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
809
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
810
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
811
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
812
+ The benefit of replication is that it allows each node to sample data points from the entire
813
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
814
+
815
+ .. warning::
816
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
817
+ and therefore more than one node may sample the same tarfile, and even sample the same
818
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
819
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
820
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
821
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
822
+ or test datasets.
823
+ shard_manifests (bool): Whether or not to try / shard manifests. Defaults to False.
824
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
825
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
826
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
827
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
828
+ """
829
+
830
+ def __init__(
831
+ self,
832
+ audio_tar_filepaths: Union[str, List[str]],
833
+ manifest_filepath: str,
834
+ parser: Callable,
835
+ sample_rate: int,
836
+ int_values: bool = False,
837
+ augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,
838
+ shuffle_n: int = 0,
839
+ min_duration: Optional[float] = None,
840
+ max_duration: Optional[float] = None,
841
+ trim: bool = False,
842
+ bos_id: Optional[int] = None,
843
+ eos_id: Optional[int] = None,
844
+ pad_id: int = 0,
845
+ shard_strategy: str = "scatter",
846
+ shard_manifests: bool = False,
847
+ global_rank: int = 0,
848
+ world_size: int = 0,
849
+ return_sample_id: bool = False,
850
+ manifest_parse_func: Optional[Callable] = None,
851
+ ):
852
+ self.shard_manifests = shard_manifests
853
+
854
+ # Shard manifests if necessary and possible and then expand the paths
855
+ manifest_filepath = shard_manifests_if_needed(
856
+ shard_manifests=shard_manifests,
857
+ shard_strategy=shard_strategy,
858
+ manifest_filepaths=manifest_filepath,
859
+ world_size=world_size,
860
+ global_rank=global_rank,
861
+ )
862
+
863
+ # If necessary, cache manifests from object store
864
+ cache_datastore_manifests(manifest_filepaths=manifest_filepath)
865
+
866
+ self.manifest_processor = ASRManifestProcessor(
867
+ manifest_filepath=manifest_filepath,
868
+ parser=parser,
869
+ max_duration=max_duration,
870
+ min_duration=min_duration,
871
+ max_utts=0,
872
+ bos_id=bos_id,
873
+ eos_id=eos_id,
874
+ pad_id=pad_id,
875
+ index_by_file_id=True, # Must set this so the manifest lines can be indexed by file ID
876
+ manifest_parse_func=manifest_parse_func,
877
+ )
878
+
879
+ self.len = self._compute_len()
880
+
881
+ self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)
882
+ self.trim = trim
883
+ self.eos_id = eos_id
884
+ self.bos_id = bos_id
885
+ self.pad_id = pad_id
886
+ self.return_sample_id = return_sample_id
887
+
888
+ audio_tar_filepaths = expand_sharded_filepaths(
889
+ sharded_filepaths=audio_tar_filepaths,
890
+ shard_strategy=shard_strategy,
891
+ world_size=world_size,
892
+ global_rank=global_rank,
893
+ )
894
+
895
+ # Put together WebDataset pipeline
896
+ self._dataset = wds.DataPipeline(
897
+ wds.SimpleShardList(urls=audio_tar_filepaths),
898
+ webdataset_split_by_workers,
899
+ wds.shuffle(shuffle_n),
900
+ wds.tarfile_to_samples(),
901
+ wds.rename(audio=VALID_FILE_FORMATS, key='__key__'),
902
+ wds.to_tuple('audio', 'key'),
903
+ self._filter,
904
+ self._loop_offsets,
905
+ wds.map(self._build_sample),
906
+ )
907
+
908
+ def _filter(self, iterator):
909
+ """This function is used to remove samples that have been filtered out by ASRAudioText already.
910
+ Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample
911
+ that was filtered out (e.g. for duration).
912
+ Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard,
913
+ which may make your code hang as one process will finish before the other.
914
+ """
915
+
916
+ class TarredAudioFilter:
917
+ def __init__(self, collection):
918
+ self.iterator = iterator
919
+ self.collection = collection
920
+
921
+ def __iter__(self):
922
+ return self
923
+
924
+ def __next__(self):
925
+ while True:
926
+ audio_bytes, audio_filename = next(self.iterator)
927
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
928
+ if file_id in self.collection.mapping:
929
+ return audio_bytes, audio_filename
930
+
931
+ return TarredAudioFilter(self.manifest_processor.collection)
932
+
933
+ def _loop_offsets(self, iterator):
934
+ """This function is used to iterate through utterances with different offsets for each file."""
935
+
936
+ class TarredAudioLoopOffsets:
937
+ def __init__(self, collection):
938
+ self.iterator = iterator
939
+ self.collection = collection
940
+ self.current_fn = None
941
+ self.current_bytes = None
942
+ self.offset_id = 0
943
+
944
+ def __iter__(self):
945
+ return self
946
+
947
+ def __next__(self):
948
+ if self.current_fn is None:
949
+ self.current_bytes, self.current_fn = next(self.iterator)
950
+ self.offset_id = 0
951
+ else:
952
+ import os
953
+ file_id, _ = os.path.splitext(os.path.basename(self.current_fn))
954
+ offset_list = self.collection.mapping[file_id]
955
+ if len(offset_list) == self.offset_id + 1:
956
+ self.current_bytes, self.current_fn = next(self.iterator)
957
+ self.offset_id = 0
958
+ else:
959
+ self.offset_id += 1
960
+
961
+ return self.current_bytes, self.current_fn, self.offset_id
962
+
963
+ return TarredAudioLoopOffsets(self.manifest_processor.collection)
964
+
965
+ def _collate_fn(self, batch):
966
+ return _speech_collate_fn(batch, self.pad_id)
967
+
968
+ def _build_sample(self, tup):
969
+ """Builds the training sample by combining the data from the WebDataset with the manifest info."""
970
+ audio_bytes, audio_filename, offset_id = tup
971
+
972
+ # Grab manifest entry from self.manifest_preprocessor.collection
973
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
974
+
975
+ manifest_idx = self.manifest_processor.collection.mapping[file_id][offset_id]
976
+ manifest_entry = self.manifest_processor.collection[manifest_idx]
977
+
978
+ offset = manifest_entry.offset
979
+ if offset is None:
980
+ offset = 0
981
+
982
+ # Convert audio bytes to IO stream for processing (for SoundFile to read)
983
+ audio_filestream = io.BytesIO(audio_bytes)
984
+ features = self.featurizer.process(
985
+ audio_filestream,
986
+ offset=offset,
987
+ duration=manifest_entry.duration,
988
+ trim=self.trim,
989
+ orig_sr=manifest_entry.orig_sr,
990
+ )
991
+ audio_filestream.close()
992
+
993
+ # Audio features
994
+ f, fl = features, torch.tensor(features.shape[0]).long()
995
+
996
+ # Text features
997
+ t, tl = manifest_entry.text_tokens, len(manifest_entry.text_tokens)
998
+
999
+ self.manifest_processor.process_text_by_sample(sample=manifest_entry)
1000
+
1001
+ if self.bos_id is not None:
1002
+ t = [self.bos_id] + t
1003
+ tl += 1
1004
+ if self.eos_id is not None:
1005
+ t = t + [self.eos_id]
1006
+ tl += 1
1007
+
1008
+ if self.return_sample_id:
1009
+ return f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), manifest_idx
1010
+ else:
1011
+ return f, fl, torch.tensor(t).long(), torch.tensor(tl).long()
1012
+
1013
+ def get_manifest_sample(self, sample_id):
1014
+ return self.manifest_processor.collection[sample_id]
1015
+
1016
+ def __iter__(self):
1017
+ return self._dataset.__iter__()
1018
+
1019
+ def _compute_len(self):
1020
+ if self.shard_manifests and torch.distributed.is_available() and torch.distributed.is_initialized():
1021
+ my_len = torch.tensor(len(self.manifest_processor.collection), dtype=torch.int32).cuda()
1022
+ torch.distributed.all_reduce(my_len)
1023
+ my_len = my_len.int()
1024
+ logging.info(f'Sharded manifests: Total length: {my_len}')
1025
+ else:
1026
+ my_len = len(self.manifest_processor.collection)
1027
+
1028
+ return my_len
1029
+
1030
+ def __len__(self):
1031
+ return self.len
1032
+
1033
+
1034
+ class TarredAudioToCharDataset(_TarredAudioToTextDataset):
1035
+ """
1036
+ A similar Dataset to the AudioToCharDataset, but which loads tarred audio files.
1037
+
1038
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset),
1039
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
1040
+ contain the information for one audio file, including at least the transcript and name of the audio
1041
+ file within the tarball.
1042
+
1043
+ Valid formats for the audio_tar_filepaths argument include:
1044
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
1045
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
1046
+
1047
+ See the WebDataset documentation for more information about accepted data and input formats.
1048
+
1049
+ If using multiple workers the number of shards should be divisible by world_size to ensure an
1050
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
1051
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
1052
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
1053
+
1054
+ Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been
1055
+ replaced by shuffle_n (int).
1056
+
1057
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
1058
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
1059
+
1060
+ Args:
1061
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
1062
+ string (can be brace-expandable).
1063
+ manifest_filepath (str): Path to the manifest.
1064
+ labels (list): List of characters that can be output by the ASR model.
1065
+ For Jasper, this is the 28 character set {a-z '}. The CTC blank
1066
+ symbol is automatically added later for models using ctc.
1067
+ sample_rate (int): Sample rate to resample loaded audio to
1068
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
1069
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
1070
+ object used to augment loaded audio
1071
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
1072
+ See WebDataset documentation for more details.
1073
+ Defaults to 0.
1074
+ min_duration (float): Dataset parameter.
1075
+ All training files which have a duration less than min_duration
1076
+ are dropped. Note: Duration is read from the manifest JSON.
1077
+ Defaults to 0.1.
1078
+ max_duration (float): Dataset parameter.
1079
+ All training files which have a duration more than max_duration
1080
+ are dropped. Note: Duration is read from the manifest JSON.
1081
+ Defaults to None.
1082
+ blank_index (int): Blank character index, defaults to -1.
1083
+ unk_index (int): Unknown character index, defaults to -1.
1084
+ normalize (bool): Dataset parameter.
1085
+ Whether to use automatic text cleaning.
1086
+ It is highly recommended to manually clean text for best results.
1087
+ Defaults to True.
1088
+ trim (bool): Whether to use trim silence from beginning and end
1089
+ of audio signal using librosa.effects.trim().
1090
+ Defaults to False.
1091
+ bos_id (id): Dataset parameter.
1092
+ Beginning of string symbol id used for seq2seq models.
1093
+ Defaults to None.
1094
+ eos_id (id): Dataset parameter.
1095
+ End of string symbol id used for seq2seq models.
1096
+ Defaults to None.
1097
+ pad_id (id): Token used to pad when collating samples in batches.
1098
+ If this is None, pads using 0s.
1099
+ Defaults to None.
1100
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
1101
+
1102
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
1103
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
1104
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
1105
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
1106
+ The benefit of replication is that it allows each node to sample data points from the entire
1107
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
1108
+
1109
+ .. warning::
1110
+
1111
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
1112
+ and therefore more than one node may sample the same tarfile, and even sample the same
1113
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
1114
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
1115
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
1116
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
1117
+ or test datasets.
1118
+
1119
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
1120
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
1121
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
1122
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
1123
+ """
1124
+
1125
+ def __init__(
1126
+ self,
1127
+ audio_tar_filepaths: Union[str, List[str]],
1128
+ manifest_filepath: str,
1129
+ labels: List[str],
1130
+ sample_rate: int,
1131
+ int_values: bool = False,
1132
+ augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,
1133
+ shuffle_n: int = 0,
1134
+ min_duration: Optional[float] = None,
1135
+ max_duration: Optional[float] = None,
1136
+ blank_index: int = -1,
1137
+ unk_index: int = -1,
1138
+ normalize: bool = True,
1139
+ trim: bool = False,
1140
+ bos_id: Optional[int] = None,
1141
+ eos_id: Optional[int] = None,
1142
+ parser: Optional[str] = 'en',
1143
+ pad_id: int = 0,
1144
+ shard_strategy: str = "scatter",
1145
+ shard_manifests: bool = False,
1146
+ global_rank: int = 0,
1147
+ world_size: int = 0,
1148
+ return_sample_id: bool = False,
1149
+ manifest_parse_func: Optional[Callable] = None,
1150
+ ):
1151
+ self.labels = labels
1152
+
1153
+ parser = parsers.make_parser(
1154
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
1155
+ )
1156
+
1157
+ super().__init__(
1158
+ audio_tar_filepaths=audio_tar_filepaths,
1159
+ manifest_filepath=manifest_filepath,
1160
+ parser=parser,
1161
+ sample_rate=sample_rate,
1162
+ int_values=int_values,
1163
+ augmentor=augmentor,
1164
+ shuffle_n=shuffle_n,
1165
+ min_duration=min_duration,
1166
+ max_duration=max_duration,
1167
+ trim=trim,
1168
+ bos_id=bos_id,
1169
+ eos_id=eos_id,
1170
+ pad_id=pad_id,
1171
+ shard_strategy=shard_strategy,
1172
+ shard_manifests=shard_manifests,
1173
+ global_rank=global_rank,
1174
+ world_size=world_size,
1175
+ return_sample_id=return_sample_id,
1176
+ manifest_parse_func=manifest_parse_func,
1177
+ )
1178
+
1179
+
1180
+ class TarredAudioToBPEDataset(_TarredAudioToTextDataset):
1181
+ """
1182
+ A similar Dataset to the AudioToBPEDataset, but which loads tarred audio files.
1183
+
1184
+ Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToBPEDataset),
1185
+ as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should
1186
+ contain the information for one audio file, including at least the transcript and name of the audio
1187
+ file within the tarball.
1188
+
1189
+ Valid formats for the audio_tar_filepaths argument include:
1190
+ (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or
1191
+ (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].
1192
+
1193
+ See the WebDataset documentation for more information about accepted data and input formats.
1194
+
1195
+ If using multiple workers the number of shards should be divisible by world_size to ensure an
1196
+ even split among workers. If it is not divisible, logging will give a warning but training will proceed.
1197
+ In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering
1198
+ is applied. We currently do not check for this, but your program may hang if the shards are uneven!
1199
+
1200
+ Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been
1201
+ replaced by shuffle_n (int).
1202
+
1203
+ Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest
1204
+ after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.
1205
+
1206
+ Args:
1207
+ audio_tar_filepaths: Either a list of audio tarball filepaths, or a
1208
+ string (can be brace-expandable).
1209
+ manifest_filepath (str): Path to the manifest.
1210
+ tokenizer (TokenizerSpec): Either a Word Piece Encoding tokenizer (BERT),
1211
+ or a Sentence Piece Encoding tokenizer (BPE). The CTC blank
1212
+ symbol is automatically added later for models using ctc.
1213
+ sample_rate (int): Sample rate to resample loaded audio to
1214
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
1215
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
1216
+ object used to augment loaded audio
1217
+ shuffle_n (int): How many samples to look ahead and load to be shuffled.
1218
+ See WebDataset documentation for more details.
1219
+ Defaults to 0.
1220
+ min_duration (float): Dataset parameter.
1221
+ All training files which have a duration less than min_duration
1222
+ are dropped. Note: Duration is read from the manifest JSON.
1223
+ Defaults to 0.1.
1224
+ max_duration (float): Dataset parameter.
1225
+ All training files which have a duration more than max_duration
1226
+ are dropped. Note: Duration is read from the manifest JSON.
1227
+ Defaults to None.
1228
+ trim (bool): Whether to use trim silence from beginning and end
1229
+ of audio signal using librosa.effects.trim().
1230
+ Defaults to False.
1231
+ use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS]
1232
+ tokens to beginning and ending of speech respectively.
1233
+ pad_id (id): Token used to pad when collating samples in batches.
1234
+ If this is None, pads using 0s.
1235
+ Defaults to None.
1236
+ shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp.
1237
+
1238
+ - `scatter`: The default shard strategy applied by WebDataset, where each node gets
1239
+ a unique set of shards, which are permanently pre-allocated and never changed at runtime.
1240
+ - `replicate`: Optional shard strategy, where each node gets all of the set of shards
1241
+ available in the tarred dataset, which are permanently pre-allocated and never changed at runtime.
1242
+ The benefit of replication is that it allows each node to sample data points from the entire
1243
+ dataset independently of other nodes, and reduces dependence on value of `shuffle_n`.
1244
+
1245
+ .. warning::
1246
+
1247
+ Replicated strategy allows every node to sample the entire set of available tarfiles,
1248
+ and therefore more than one node may sample the same tarfile, and even sample the same
1249
+ data points! As such, there is no assured guarantee that all samples in the dataset will be
1250
+ sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific
1251
+ occasions (when the number of shards is not divisible with ``world_size``), will not sample
1252
+ the entire dataset. For these reasons it is not advisable to use tarred datasets as validation
1253
+ or test datasets.
1254
+
1255
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
1256
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.
1257
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
1258
+ manifest_parse_func: Optional function to parse manifest entries. Defaults to None.
1259
+ """
1260
+
1261
+ def __init__(
1262
+ self,
1263
+ audio_tar_filepaths: Union[str, List[str]],
1264
+ manifest_filepath: str,
1265
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
1266
+ sample_rate: int,
1267
+ int_values: bool = False,
1268
+ augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,
1269
+ shuffle_n: int = 0,
1270
+ min_duration: Optional[float] = None,
1271
+ max_duration: Optional[float] = None,
1272
+ trim: bool = False,
1273
+ use_start_end_token: bool = True,
1274
+ shard_strategy: str = "scatter",
1275
+ shard_manifests: bool = False,
1276
+ global_rank: int = 0,
1277
+ world_size: int = 0,
1278
+ return_sample_id: bool = False,
1279
+ manifest_parse_func: Optional[Callable] = None,
1280
+ ):
1281
+ if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0:
1282
+ bos_id = tokenizer.bos_id
1283
+ else:
1284
+ bos_id = None
1285
+
1286
+ if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0:
1287
+ eos_id = tokenizer.eos_id
1288
+ else:
1289
+ eos_id = None
1290
+
1291
+ if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0:
1292
+ pad_id = tokenizer.pad_id
1293
+ else:
1294
+ pad_id = 0
1295
+
1296
+ class TokenizerWrapper:
1297
+ def __init__(self, tokenizer):
1298
+ if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer):
1299
+ self.is_aggregate = True
1300
+ else:
1301
+ self.is_aggregate = False
1302
+ self._tokenizer = tokenizer
1303
+
1304
+ def __call__(self, *args):
1305
+ if isinstance(args[0], List) and self.is_aggregate:
1306
+ t = []
1307
+ for span in args[0]:
1308
+ t.extend(self._tokenizer.text_to_ids(span['str'], span['lang']))
1309
+ return t
1310
+
1311
+ t = self._tokenizer.text_to_ids(*args)
1312
+ return t
1313
+
1314
+ super().__init__(
1315
+ audio_tar_filepaths=audio_tar_filepaths,
1316
+ manifest_filepath=manifest_filepath,
1317
+ parser=TokenizerWrapper(tokenizer),
1318
+ sample_rate=sample_rate,
1319
+ int_values=int_values,
1320
+ augmentor=augmentor,
1321
+ shuffle_n=shuffle_n,
1322
+ min_duration=min_duration,
1323
+ max_duration=max_duration,
1324
+ trim=trim,
1325
+ bos_id=bos_id,
1326
+ eos_id=eos_id,
1327
+ pad_id=pad_id,
1328
+ shard_strategy=shard_strategy,
1329
+ shard_manifests=shard_manifests,
1330
+ global_rank=global_rank,
1331
+ world_size=world_size,
1332
+ return_sample_id=return_sample_id,
1333
+ manifest_parse_func=manifest_parse_func,
1334
+ )
1335
+
1336
+
1337
+ class BucketingDataset(IterableDataset):
1338
+ """
1339
+ A Dataset which wraps another IterableDataset and adopts it for bucketing
1340
+ Args:
1341
+ dataset (IterableDataset): The IterableDataset to get wrapped
1342
+ bucketing_batch_size (int): Number of samples to build a batch
1343
+ """
1344
+
1345
+ def __init__(
1346
+ self,
1347
+ dataset: IterableDataset,
1348
+ bucketing_batch_size: int,
1349
+ ):
1350
+ self.wrapped_dataset = dataset
1351
+ self.bucketing_batch_size = bucketing_batch_size
1352
+ super().__init__()
1353
+
1354
+ def _collate_fn(self, batch):
1355
+ return _speech_collate_fn(batch[0], self.wrapped_dataset.pad_id)
1356
+
1357
+ def __iter__(self):
1358
+ return BucketingIterator(
1359
+ wrapped_ds=self.wrapped_dataset._dataset, bucketing_batch_size=self.bucketing_batch_size
1360
+ ).__iter__()
1361
+
1362
+ def __len__(self):
1363
+ return int(math.ceil(len(self.wrapped_dataset) / float(self.bucketing_batch_size)))
1364
+
1365
+
1366
+ class BucketingIterator:
1367
+ def __init__(self, wrapped_ds, bucketing_batch_size):
1368
+ self.wrapped_ds = wrapped_ds
1369
+ self.wrapped_iter = None
1370
+ self.bucketing_batch_size = bucketing_batch_size
1371
+
1372
+ def __iter__(self):
1373
+ self.wrapped_iter = iter(self.wrapped_ds)
1374
+ return self
1375
+
1376
+ def __next__(self):
1377
+ batches = []
1378
+ for idx in range(self.bucketing_batch_size):
1379
+ try:
1380
+ sample = next(self.wrapped_iter)
1381
+ except StopIteration:
1382
+ break
1383
+ batches.append(sample)
1384
+ if len(batches) == 0:
1385
+ raise StopIteration
1386
+ return batches
1387
+
1388
+
1389
+ class RandomizedChainDataset(ChainDataset):
1390
+ def __init__(self, datasets: Iterable[Dataset], rnd_seed=0) -> None:
1391
+ super(RandomizedChainDataset, self).__init__(list(datasets))
1392
+ self.rnd_gen = np.random.RandomState(rnd_seed)
1393
+
1394
+ def __iter__(self):
1395
+ shuffled_order = self.rnd_gen.permutation(len(self.datasets))
1396
+ for dataset_idx in shuffled_order:
1397
+ d = self.datasets[dataset_idx]
1398
+ assert isinstance(d, IterableDataset), "ChainDataset only supports IterableDataset"
1399
+ for idx, x in enumerate(d):
1400
+ yield x
1401
+ # in case d is an infinite dataset, we want to break the loop
1402
+ # so that the other datasets get a chance to yield too
1403
+ if idx >= len(d) - 1:
1404
+ break
nemo/collections/asr/data/audio_to_text_dali.py ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ import operator
17
+ import os.path
18
+ import time
19
+ from collections.abc import Iterator
20
+ from typing import Callable, List, Optional, Union
21
+
22
+ import torch
23
+ from omegaconf import DictConfig
24
+
25
+ from nemo.collections.asr.data.audio_to_text import ASRManifestProcessor, expand_sharded_filepaths
26
+ from nemo.collections.common.parts.preprocessing import parsers
27
+ from nemo.utils import logging, model_utils
28
+
29
+ try:
30
+ import nvidia.dali as dali
31
+ from nvidia.dali.pipeline import Pipeline
32
+ from nvidia.dali.plugin.pytorch import DALIGenericIterator as DALIPytorchIterator
33
+ from nvidia.dali.plugin.pytorch import LastBatchPolicy as LastBatchPolicy
34
+
35
+ HAVE_DALI = True
36
+ except (ImportError, ModuleNotFoundError):
37
+ HAVE_DALI = False
38
+
39
+ __all__ = [
40
+ 'AudioToCharDALIDataset',
41
+ 'AudioToBPEDALIDataset',
42
+ ]
43
+
44
+ """
45
+ Below minimum version is required to access the "read_idxs" argument in
46
+ dali.fn.readers.nemo_asr
47
+ """
48
+ __DALI_MINIMUM_VERSION__ = "1.11"
49
+
50
+ DALI_INSTALLATION_MESSAGE = (
51
+ "Could not import `nvidia.dali`.\n"
52
+ "Please install DALI by following the steps provided here - \n"
53
+ "https://docs.nvidia.com/deeplearning/dali/user-guide/docs/installation.html"
54
+ )
55
+
56
+
57
+ def is_dali_supported(min_version: str, verbose: bool = False) -> bool:
58
+ """
59
+ Checks if DALI in installed, and version is >= min_verion.
60
+
61
+ Args:
62
+ min_version: A semver str that is the minimum requirement.
63
+ verbose: Whether to log the installation instructions if DALI is not found.
64
+
65
+ Returns:
66
+ bool - whether DALI could be imported or not.
67
+ """
68
+ module_available, _ = model_utils.check_lib_version(
69
+ 'nvidia.dali', checked_version=min_version, operator=operator.ge
70
+ )
71
+
72
+ # If DALI is not installed
73
+ if module_available is None:
74
+ if verbose:
75
+ logging.info(DALI_INSTALLATION_MESSAGE)
76
+
77
+ return False
78
+
79
+ return module_available
80
+
81
+
82
+ class DALIOutputs(object):
83
+ def __init__(self, out_dict):
84
+ self._has_processed_signal = 'processed_signal' in out_dict and 'processed_signal_len' in out_dict
85
+ if not self._has_processed_signal:
86
+ assert 'audio' in out_dict and 'audio_len' in out_dict
87
+ assert 'transcript' in out_dict and 'transcript_len' in out_dict
88
+ if self._has_processed_signal:
89
+ self._outs = (
90
+ out_dict['processed_signal'],
91
+ out_dict['processed_signal_len'].reshape(-1),
92
+ out_dict['transcript'],
93
+ out_dict['transcript_len'].reshape(-1),
94
+ )
95
+ else:
96
+ self._outs = (
97
+ out_dict['audio'],
98
+ out_dict['audio_len'].reshape(-1),
99
+ out_dict['transcript'],
100
+ out_dict['transcript_len'].reshape(-1),
101
+ )
102
+
103
+ @property
104
+ def has_processed_signal(self):
105
+ return self._has_processed_signal
106
+
107
+ def __getitem__(self, key):
108
+ return self._outs[key]
109
+
110
+ def __len__(self):
111
+ return len(self._outs)
112
+
113
+
114
+ class _AudioTextDALIDataset(Iterator):
115
+ """
116
+ NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a sample descriptor in JSON,
117
+ including audio files, transcripts, and durations (in seconds).
118
+ Here's an example:
119
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147}
120
+ ...
121
+ {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
122
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
123
+
124
+ Args:
125
+ manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths.
126
+ device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'.
127
+ batch_size (int): Number of samples in a batch.
128
+ parser (str, callable): A str for an inbuilt parser, or a callable with signature f(str) -> List[int].
129
+ sample_rate (int): Sample rate to resample loaded audio to.
130
+ num_threads (int): Number of CPU processing threads to be created by the DALI pipeline.
131
+ max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files.
132
+ min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files.
133
+ bos_id (int): Id of beginning of sequence symbol to append if not None
134
+ eos_id (int): Id of end of sequence symbol to append if not None
135
+ pad_id (int): Id used to pad the input. Defaults to 0 if not provided.
136
+ trim (bool): If True, it will extract the nonsilent region of the loaded audio signal.
137
+ shuffle (bool): If set to True, the dataset will shuffled after loading.
138
+ drop_last (bool): If set to True, the last batch will be dropped if incomplete. This will be the case when the shard size is not divisible by the batch size.
139
+ If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller.
140
+ device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0.
141
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
142
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 1.
143
+ preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor.
144
+ return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet).
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ manifest_filepath: str,
150
+ device: str,
151
+ batch_size: int,
152
+ parser: Union[str, Callable],
153
+ audio_tar_filepaths: Optional[Union[str, List[str]]] = None,
154
+ audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None,
155
+ sample_rate: int = 16000,
156
+ num_threads: int = 4,
157
+ max_duration: float = 0.0,
158
+ min_duration: float = 0.0,
159
+ bos_id: Optional[int] = None,
160
+ eos_id: Optional[int] = None,
161
+ pad_id: int = 0,
162
+ trim: bool = False,
163
+ shuffle: bool = False,
164
+ drop_last: bool = False,
165
+ shard_strategy: str = "scatter",
166
+ device_id: int = 0,
167
+ global_rank: int = 0,
168
+ world_size: int = 1,
169
+ preprocessor_cfg: DictConfig = None,
170
+ return_sample_id: bool = False,
171
+ ):
172
+ self.drop_last = drop_last # used by lr_scheduler
173
+ if return_sample_id:
174
+ raise ValueError(
175
+ "Currently DALI data layers don't support returning the sample_id and return_sample_id can not be enabled."
176
+ )
177
+ self.return_sample_id = return_sample_id
178
+
179
+ if not HAVE_DALI:
180
+ raise ModuleNotFoundError(
181
+ f"{self} requires NVIDIA DALI to be installed. "
182
+ f"See: https://docs.nvidia.com/deeplearning/dali/user-guide/docs/installation.html#id1"
183
+ )
184
+
185
+ if device not in ('cpu', 'gpu'):
186
+ raise ValueError(
187
+ f"{self} received an unexpected device argument {device}. Supported values are: 'cpu', 'gpu'"
188
+ )
189
+
190
+ device_id = device_id if device == 'gpu' else None
191
+
192
+ self.batch_size = batch_size # Used by NeMo
193
+
194
+ self.device = device
195
+ self.device_id = device_id
196
+
197
+ if world_size > 1:
198
+ self.shard_id = global_rank
199
+ self.num_shards = world_size
200
+ else:
201
+ self.shard_id = None
202
+ self.num_shards = None
203
+
204
+ self.eos_id = eos_id
205
+ self.bos_id = bos_id
206
+ self.sample_rate = sample_rate
207
+
208
+ self.pipe = Pipeline(
209
+ batch_size=batch_size,
210
+ num_threads=num_threads,
211
+ device_id=self.device_id,
212
+ exec_async=True,
213
+ exec_pipelined=True,
214
+ )
215
+
216
+ has_preprocessor = preprocessor_cfg is not None
217
+ if has_preprocessor:
218
+ if preprocessor_cfg._target_ == "nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor":
219
+ feature_type = "mel_spectrogram"
220
+ elif preprocessor_cfg._target_ == "nemo.collections.asr.modules.AudioToMFCCPreprocessor":
221
+ feature_type = "mfcc"
222
+ else:
223
+ raise ValueError(
224
+ f"{self} received an unexpected preprocessor configuration: {preprocessor_cfg._target_}."
225
+ f" Supported preprocessors are: AudioToMelSpectrogramPreprocessor, AudioToMFCCPreprocessor"
226
+ )
227
+
228
+ # Default values taken from AudioToMelSpectrogramPreprocessor
229
+ params = preprocessor_cfg
230
+ self.dither = params['dither'] if 'dither' in params else 0.0
231
+ self.preemph = params['preemph'] if 'preemph' in params else 0.97
232
+ self.window_size_sec = params['window_size'] if 'window_size' in params else 0.02
233
+ self.window_stride_sec = params['window_stride'] if 'window_stride' in params else 0.01
234
+ self.sample_rate = params['sample_rate'] if 'sample_rate' in params else sample_rate
235
+ self.window_size = int(self.window_size_sec * self.sample_rate)
236
+ self.window_stride = int(self.window_stride_sec * self.sample_rate)
237
+
238
+ normalize = params['normalize'] if 'normalize' in params else 'per_feature'
239
+ if normalize == 'per_feature': # Each freq channel independently
240
+ self.normalization_axes = (1,)
241
+ elif normalize == 'all_features':
242
+ self.normalization_axes = (0, 1)
243
+ else:
244
+ raise ValueError(
245
+ f"{self} received {normalize} for the normalize parameter."
246
+ f" It must be either 'per_feature' or 'all_features'."
247
+ )
248
+
249
+ self.window = None
250
+ window_name = params['window'] if 'window' in params else 'hann'
251
+ torch_windows = {
252
+ 'hann': torch.hann_window,
253
+ 'hamming': torch.hamming_window,
254
+ 'blackman': torch.blackman_window,
255
+ 'bartlett': torch.bartlett_window,
256
+ 'none': None,
257
+ }
258
+
259
+ if window_name == 'ones':
260
+ window_tensor = torch.ones(self.window_size)
261
+ else:
262
+ try:
263
+ window_fn = torch_windows.get(window_name, None)
264
+ except:
265
+ raise ValueError(
266
+ f"{self} received '{window_name}' for the window parameter."
267
+ f" It must be one of: ('hann', 'ones', 'hamming', 'blackman', 'bartlett', None)."
268
+ f" None is equivalent to 'hann'."
269
+ )
270
+ window_tensor = window_fn(self.window_size, periodic=False) if window_fn else None
271
+ self.window = window_tensor.numpy().tolist() if window_tensor is not None else None
272
+
273
+ self.n_fft = params['n_fft'] if 'n_fft' in params else 2 ** math.ceil(math.log2(self.window_size))
274
+ self.n_mels = params['n_mels'] if 'n_mels' in params else 64
275
+ self.n_mfcc = params['n_mfcc'] if 'n_mfcc' in params else 64
276
+
277
+ features = params['features'] if 'features' in params else 0
278
+ if features > 0:
279
+ if feature_type == 'mel_spectrogram':
280
+ self.n_mels = features
281
+ elif feature_type == 'mfcc':
282
+ self.n_mfcc = features
283
+
284
+ # TODO Implement frame splicing
285
+ if 'frame_splicing' in params:
286
+ assert params['frame_splicing'] == 1, "Frame splicing is not implemented"
287
+
288
+ self.freq_low = params['lowfreq'] if 'lowfreq' in params else 0.0
289
+ self.freq_high = params['highfreq'] if 'highfreq' in params else self.sample_rate / 2.0
290
+ self.log_features = params['log'] if 'log' in params else True
291
+
292
+ # We want to avoid taking the log of zero
293
+ # There are two options: either adding or clamping to a small value
294
+
295
+ self.log_zero_guard_type = params['log_zero_guard_type'] if 'log_zero_guard_type' in params else 'add'
296
+ if self.log_zero_guard_type not in ["add", "clamp"]:
297
+ raise ValueError(
298
+ f"{self} received {self.log_zero_guard_type} for the "
299
+ f"log_zero_guard_type parameter. It must be either 'add' or "
300
+ f"'clamp'."
301
+ )
302
+
303
+ self.log_zero_guard_value = (
304
+ params['log_zero_guard_value'] if 'log_zero_guard_value' in params else 2 ** -24
305
+ )
306
+ if isinstance(self.log_zero_guard_value, str):
307
+ if self.log_zero_guard_value == "tiny":
308
+ self.log_zero_guard_value = torch.finfo(torch.float32).tiny
309
+ elif self.log_zero_guard_value == "eps":
310
+ self.log_zero_guard_value = torch.finfo(torch.float32).eps
311
+ else:
312
+ raise ValueError(
313
+ f"{self} received {self.log_zero_guard_value} for the log_zero_guard_type parameter."
314
+ f"It must be either a number, 'tiny', or 'eps'"
315
+ )
316
+
317
+ self.mag_power = params['mag_power'] if 'mag_power' in params else 2
318
+ if self.mag_power != 1.0 and self.mag_power != 2.0:
319
+ raise ValueError(
320
+ f"{self} received {self.mag_power} for the mag_power parameter." f" It must be either 1.0 or 2.0."
321
+ )
322
+
323
+ self.pad_to = max(params['pad_to'], 1) if 'pad_to' in params else 16
324
+ self.pad_value = params['pad_value'] if 'pad_value' in params else 0.0
325
+
326
+ with self.pipe:
327
+ if audio_tar_filepaths is None and audio_tar_index_filepaths is None:
328
+ audio, indices = dali.fn.readers.nemo_asr(
329
+ name="Reader",
330
+ manifest_filepaths=manifest_filepath.split(','),
331
+ dtype=dali.types.FLOAT,
332
+ downmix=True,
333
+ sample_rate=float(self.sample_rate),
334
+ min_duration=min_duration,
335
+ max_duration=max_duration,
336
+ read_sample_rate=False,
337
+ read_text=False,
338
+ read_idxs=True,
339
+ random_shuffle=shuffle,
340
+ shard_id=self.shard_id,
341
+ num_shards=self.num_shards,
342
+ pad_last_batch=True,
343
+ )
344
+
345
+ self.is_tarred_dataset = False
346
+
347
+ elif audio_tar_filepaths is not None and audio_tar_index_filepaths is not None:
348
+ audio_tar_filepaths = expand_sharded_filepaths(
349
+ audio_tar_filepaths, shard_strategy=shard_strategy, world_size=world_size, global_rank=global_rank
350
+ )
351
+ audio_tar_index_filepaths = expand_sharded_filepaths(
352
+ audio_tar_index_filepaths,
353
+ shard_strategy=shard_strategy,
354
+ world_size=world_size,
355
+ global_rank=global_rank,
356
+ )
357
+
358
+ if len(audio_tar_filepaths) != len(audio_tar_index_filepaths) and len(audio_tar_index_filepaths) != 0:
359
+ raise ValueError(
360
+ f"Number of filepaths provided for `audio_tar_filepaths` must match "
361
+ f"`audio_tar_index_filepaths`. Got {len(audio_tar_filepaths)} audio_tar_filepaths and "
362
+ f"{len(audio_tar_index_filepaths)} audio_tar_index_filepaths."
363
+ )
364
+
365
+ tar_file = dali.fn.readers.webdataset(
366
+ paths=audio_tar_filepaths,
367
+ index_paths=audio_tar_index_filepaths,
368
+ name="Reader",
369
+ ext=["wav"],
370
+ missing_component_behavior="error",
371
+ random_shuffle=shuffle,
372
+ shard_id=self.shard_id,
373
+ num_shards=self.num_shards,
374
+ pad_last_batch=True,
375
+ )
376
+ audio, _ = dali.fn.decoders.audio(
377
+ tar_file, dtype=dali.types.FLOAT, downmix=True, sample_rate=float(self.sample_rate),
378
+ )
379
+ indices = dali.fn.get_property(tar_file, key="source_info")
380
+ indices = dali.fn.pad(indices)
381
+
382
+ self.is_tarred_dataset = True
383
+
384
+ else:
385
+ raise RuntimeError(
386
+ "When using DALI datasets, either `audio_tar_filepaths` "
387
+ "and `audio_tar_index_filepaths` should either both be None (sequential dataset)"
388
+ "or provided (tarred dataset)."
389
+ )
390
+
391
+ # Extract nonsilent region, if necessary
392
+ if trim:
393
+ # Need to extract non-silent region before moving to the GPU
394
+ roi_start, roi_len = dali.fn.nonsilent_region(audio, cutoff_db=-60)
395
+ audio = audio.gpu() if self.device == 'gpu' else audio
396
+ audio = dali.fn.slice(
397
+ audio, roi_start, roi_len, normalized_anchor=False, normalized_shape=False, axes=[0]
398
+ )
399
+ else:
400
+ audio = audio.gpu() if self.device == 'gpu' else audio
401
+
402
+ if not has_preprocessor:
403
+ # No preprocessing, the output is the audio signal
404
+ audio_len = dali.fn.shapes(dali.fn.reshape(audio, shape=[-1]))
405
+ audio = dali.fn.pad(audio)
406
+ self.pipe.set_outputs(audio, audio_len, indices)
407
+ else:
408
+ # Additive gaussian noise (dither)
409
+ if self.dither > 0.0:
410
+ gaussian_noise = dali.fn.random.normal(audio)
411
+ audio = audio + self.dither * gaussian_noise
412
+
413
+ # Preemphasis filter
414
+ if self.preemph > 0.0:
415
+ audio = dali.fn.preemphasis_filter(audio, preemph_coeff=self.preemph, border='zero')
416
+
417
+ # Power spectrogram
418
+ spec = dali.fn.spectrogram(
419
+ audio,
420
+ nfft=self.n_fft,
421
+ window_length=self.window_size,
422
+ window_step=self.window_stride,
423
+ window_fn=self.window,
424
+ )
425
+
426
+ if feature_type == 'mel_spectrogram' or feature_type == 'mfcc':
427
+ # Spectrogram to Mel Spectrogram
428
+ spec = dali.fn.mel_filter_bank(
429
+ spec,
430
+ sample_rate=self.sample_rate,
431
+ nfilter=self.n_mels,
432
+ normalize=True,
433
+ freq_low=self.freq_low,
434
+ freq_high=self.freq_high,
435
+ )
436
+ # Mel Spectrogram to MFCC
437
+ if feature_type == 'mfcc':
438
+ spec = dali.fn.mfcc(spec, n_mfcc=self.n_mfcc)
439
+
440
+ # Logarithm
441
+ if self.log_zero_guard_type == 'add':
442
+ spec = spec + self.log_zero_guard_value
443
+
444
+ spec = dali.fn.to_decibels(
445
+ spec, multiplier=math.log(10), reference=1.0, cutoff_db=math.log(self.log_zero_guard_value)
446
+ )
447
+
448
+ # Normalization
449
+ spec = dali.fn.normalize(spec, axes=self.normalization_axes, epsilon=1e-5 ** 2, ddof=1)
450
+
451
+ # Extracting the length of the spectrogram
452
+ spec_len = dali.fn.slice(dali.fn.shapes(spec), 1, 1, axes=(0,))
453
+
454
+ # Pads feature dimension to be a multiple of `pad_to` and the temporal dimension to be as big as the largest sample (shape -1)
455
+ spec = dali.fn.pad(spec, fill_value=self.pad_value, axes=(0, 1), align=(self.pad_to, 1), shape=(1, -1))
456
+ self.pipe.set_outputs(spec, spec_len, indices)
457
+
458
+ x = time.time()
459
+ # Building DALI pipeline
460
+ self.pipe.build()
461
+ y = time.time()
462
+
463
+ logging.info(f"Time for pipe.build() : {(y - x)} seconds")
464
+
465
+ if has_preprocessor:
466
+ output_names = ['processed_signal', 'processed_signal_len', 'manifest_indices']
467
+ else:
468
+ output_names = ['audio', 'audio_len', 'manifest_indices']
469
+
470
+ x = time.time()
471
+ last_batch_policy = LastBatchPolicy.DROP if drop_last else LastBatchPolicy.PARTIAL
472
+ self._iter = DALIPytorchIterator(
473
+ [self.pipe],
474
+ output_map=output_names,
475
+ reader_name="Reader",
476
+ last_batch_policy=last_batch_policy,
477
+ dynamic_shape=True,
478
+ auto_reset=True,
479
+ )
480
+ y = time.time()
481
+ logging.info(f"Time for DALIPytorchIterator to initialize : {(y - x)} seconds")
482
+
483
+ # TODO come up with a better solution
484
+ class DummyDataset:
485
+ def __init__(self, parent):
486
+ self.parent = parent
487
+
488
+ def __len__(self):
489
+ return self.parent.size
490
+
491
+ self.dataset = DummyDataset(self) # Used by NeMo
492
+
493
+ x = time.time()
494
+ self.manifest_processor = ASRManifestProcessor(
495
+ manifest_filepath=manifest_filepath,
496
+ parser=parser,
497
+ max_duration=max_duration,
498
+ min_duration=min_duration,
499
+ max_utts=0,
500
+ bos_id=bos_id,
501
+ eos_id=eos_id,
502
+ pad_id=pad_id,
503
+ index_by_file_id=self.is_tarred_dataset,
504
+ )
505
+ y = time.time()
506
+ logging.info(f"Time to build nemo manifest processor - {(y - x)} seconds")
507
+
508
+ def reset(self):
509
+ self._iter.reset()
510
+
511
+ def __iter__(self):
512
+ return self
513
+
514
+ def next(self):
515
+ return self.__next__()
516
+
517
+ @property
518
+ def size(self):
519
+ return self._iter.size
520
+
521
+ def __len__(self):
522
+ return len(self._iter)
523
+
524
+ def __next__(self):
525
+ outputs = self._iter.next()
526
+ assert len(outputs) == 1
527
+ dali_out = outputs[0]
528
+ manifest_indices = dali_out['manifest_indices'].numpy()
529
+
530
+ out = {}
531
+ out_names = ['processed_signal', 'processed_signal_len', 'audio', 'audio_len']
532
+ for out_name in out_names:
533
+ if out_name in dali_out:
534
+ out[out_name] = dali_out[out_name].detach().clone()
535
+
536
+ text_tokens = []
537
+ text_tokens_len = []
538
+ max_len = 0
539
+ batch_size = manifest_indices.shape[0]
540
+ for i, manifest_index in enumerate(manifest_indices):
541
+
542
+ if not self.is_tarred_dataset:
543
+ # Loose-file dataset. Index is integer based.
544
+ manifest_index = manifest_index[0]
545
+ text, text_length = self.manifest_processor.process_text_by_id(manifest_index)
546
+ else:
547
+ # Tarred-file dataset. Index is filename based.
548
+ resolved_manifest_indices = manifest_index.tobytes().decode().split(":")
549
+ resolved_manifest_index = resolved_manifest_indices[2] # we require just the filename segment
550
+ resolved_manifest_index = os.path.splitext(resolved_manifest_index)[0] # we dont need file extension
551
+ text, text_length = self.manifest_processor.process_text_by_file_id(resolved_manifest_index)
552
+
553
+ text_tokens_len.append(text_length)
554
+ text_tokens.append(text)
555
+ if text_length > max_len:
556
+ max_len = text_length
557
+
558
+ transcript_out = torch.full([batch_size, max_len], fill_value=self.manifest_processor.pad_id, dtype=torch.long)
559
+ for i, n in enumerate(text_tokens_len):
560
+ transcript_out[i, :n] = torch.tensor(text_tokens[i], dtype=torch.long)
561
+ transcript_len_out = torch.tensor(text_tokens_len, dtype=torch.long)
562
+
563
+ out['transcript'] = transcript_out
564
+ out['transcript_len'] = transcript_len_out
565
+ return DALIOutputs(out)
566
+
567
+
568
+ class AudioToCharDALIDataset(_AudioTextDALIDataset):
569
+ """
570
+ Character based NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a
571
+ sample descriptor in JSON, including audio files, transcripts, and durations (in seconds).
572
+ Here's an example:
573
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147}
574
+ ...
575
+ {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
576
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
577
+
578
+ Args:
579
+ manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths.
580
+ device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'.
581
+ batch_size (int): Number of samples in a batch.
582
+ labels (List[str]): String containing all the possible characters to map to.
583
+ sample_rate (int): Sample rate to resample loaded audio to.
584
+ num_threads (int): Number of CPU processing threads to be created by the DALI pipeline.
585
+ max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files.
586
+ min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files.
587
+ blank_index (int): blank character index, default = -1
588
+ unk_index (int): unk_character index, default = -1
589
+ normalize (bool): whether to normalize transcript text (default): True
590
+ bos_id (int): Id of beginning of sequence symbol to append if not None
591
+ eos_id (int): Id of end of sequence symbol to append if not None
592
+ pad_id (int): Id used to pad the input. Defaults to 0 if not provided.
593
+ trim (bool): If True, it will extract the nonsilent region of the loaded audio signal.
594
+ shuffle (bool): If set to True, the dataset will shuffled after loading.
595
+ drop_last (bool): If set to True, the last batch will be dropped if incomplete. This will be the case when the shard size is not divisible by the batch size.
596
+ If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller.
597
+ parser (str, callable): A str for an inbuilt parser, or a callable with signature f(str) -> List[int].
598
+ device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0.
599
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
600
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 1.
601
+ preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor.
602
+ return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet).
603
+ """
604
+
605
+ def __init__(
606
+ self,
607
+ manifest_filepath: str,
608
+ device: str,
609
+ batch_size: int,
610
+ labels: Union[str, List[str]],
611
+ sample_rate: int = 16000,
612
+ audio_tar_filepaths: Optional[Union[str, List[str]]] = None,
613
+ audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None,
614
+ num_threads: int = 4,
615
+ max_duration: float = 0.0,
616
+ min_duration: float = 0.0,
617
+ blank_index: int = -1,
618
+ unk_index: int = -1,
619
+ normalize: bool = True,
620
+ bos_id: Optional[int] = None,
621
+ eos_id: Optional[int] = None,
622
+ pad_id: int = 0,
623
+ trim: bool = False,
624
+ shuffle: bool = False,
625
+ drop_last: bool = False,
626
+ parser: Union[str, Callable] = 'en',
627
+ shard_strategy: str = "scatter",
628
+ device_id: int = 0,
629
+ global_rank: int = 0,
630
+ world_size: int = 1,
631
+ preprocessor_cfg: DictConfig = None,
632
+ return_sample_id: bool = False,
633
+ ):
634
+ self.labels = labels
635
+
636
+ parser = parsers.make_parser(
637
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
638
+ )
639
+
640
+ super().__init__(
641
+ manifest_filepath=manifest_filepath,
642
+ device=device,
643
+ batch_size=batch_size,
644
+ audio_tar_filepaths=audio_tar_filepaths,
645
+ audio_tar_index_filepaths=audio_tar_index_filepaths,
646
+ sample_rate=sample_rate,
647
+ num_threads=num_threads,
648
+ max_duration=max_duration,
649
+ min_duration=min_duration,
650
+ bos_id=bos_id,
651
+ eos_id=eos_id,
652
+ pad_id=pad_id,
653
+ trim=trim,
654
+ shuffle=shuffle,
655
+ drop_last=drop_last,
656
+ parser=parser,
657
+ shard_strategy=shard_strategy,
658
+ device_id=device_id,
659
+ global_rank=global_rank,
660
+ world_size=world_size,
661
+ preprocessor_cfg=preprocessor_cfg,
662
+ return_sample_id=return_sample_id,
663
+ )
664
+
665
+
666
+ class AudioToBPEDALIDataset(_AudioTextDALIDataset):
667
+ """
668
+ Subword based NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a
669
+ sample descriptor in JSON, including audio files, transcripts, and durations (in seconds).
670
+ Here's an example:
671
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147}
672
+ ...
673
+ {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
674
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
675
+
676
+ Args:
677
+ manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths.
678
+ tokenizer (TokenizerSpec): A TokenizerSpec implementation that wraps a tokenization implementation.
679
+ device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'.
680
+ batch_size (int): Number of samples in a batch.
681
+ sample_rate (int): Sample rate to resample loaded audio to.
682
+ num_threads (int): Number of CPU processing threads to be created by the DALI pipeline.
683
+ max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files.
684
+ min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files.
685
+ bos_id (int): Id of beginning of sequence symbol to append if not None. Injected from the tokenizer.
686
+ eos_id (int): Id of end of sequence symbol to append if not None. Injected from the tokenizer.
687
+ pad_id (int): Id used to pad the input. Defaults to 0 if not provided. Injected from the tokenizer.
688
+ trim (bool): If True, it will extract the nonsilent region of the loaded audio signal.
689
+ shuffle (bool): If set to True, the dataset will shuffled after loading.
690
+ drop_last (bool): If set to True, the last batch will be dropped if incomplete. This will be the case when the shard size is not divisible by the batch size.
691
+ If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller.
692
+
693
+ device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0.
694
+ global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.
695
+ world_size (int): Total number of processes, used for partitioning shards. Defaults to 1.
696
+ preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor.
697
+ use_start_end_token (bool): Boolean which dictates whether to add [BOS] and [EOS] tokens to beginning and
698
+ ending of speech respectively.
699
+ return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet).
700
+ """
701
+
702
+ def __init__(
703
+ self,
704
+ manifest_filepath: str,
705
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
706
+ device: str,
707
+ batch_size: int,
708
+ sample_rate: int = 16000,
709
+ audio_tar_filepaths: Optional[Union[str, List[str]]] = None,
710
+ audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None,
711
+ num_threads: int = 4,
712
+ max_duration: float = 0.0,
713
+ min_duration: float = 0.0,
714
+ trim: bool = False,
715
+ shuffle: bool = False,
716
+ drop_last: bool = False,
717
+ shard_strategy: str = "scatter",
718
+ device_id: int = 0,
719
+ global_rank: int = 0,
720
+ world_size: int = 1,
721
+ preprocessor_cfg: DictConfig = None,
722
+ use_start_end_token: bool = True,
723
+ return_sample_id: bool = False,
724
+ ):
725
+
726
+ if use_start_end_token and hasattr(tokenizer, 'bos_token'):
727
+ bos_id = tokenizer.bos_id
728
+ else:
729
+ bos_id = None
730
+
731
+ if use_start_end_token and hasattr(tokenizer, 'eos_token'):
732
+ eos_id = tokenizer.eos_id
733
+ else:
734
+ eos_id = None
735
+
736
+ if hasattr(tokenizer, 'pad_token'):
737
+ pad_id = tokenizer.pad_id
738
+ else:
739
+ pad_id = 0
740
+
741
+ class TokenizerWrapper:
742
+ def __init__(self, tokenizer):
743
+ self._tokenizer = tokenizer
744
+
745
+ def __call__(self, text):
746
+ t = self._tokenizer.text_to_ids(text)
747
+ return t
748
+
749
+ super().__init__(
750
+ manifest_filepath=manifest_filepath,
751
+ device=device,
752
+ batch_size=batch_size,
753
+ sample_rate=sample_rate,
754
+ audio_tar_filepaths=audio_tar_filepaths,
755
+ audio_tar_index_filepaths=audio_tar_index_filepaths,
756
+ num_threads=num_threads,
757
+ max_duration=max_duration,
758
+ min_duration=min_duration,
759
+ bos_id=bos_id,
760
+ eos_id=eos_id,
761
+ pad_id=pad_id,
762
+ trim=trim,
763
+ shuffle=shuffle,
764
+ drop_last=drop_last,
765
+ parser=TokenizerWrapper(tokenizer),
766
+ shard_strategy=shard_strategy,
767
+ device_id=device_id,
768
+ global_rank=global_rank,
769
+ world_size=world_size,
770
+ preprocessor_cfg=preprocessor_cfg,
771
+ return_sample_id=return_sample_id,
772
+ )
nemo/collections/asr/data/audio_to_text_dataset.py ADDED
@@ -0,0 +1,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import copy
16
+ import json
17
+ import random
18
+ from math import isclose
19
+ from typing import Any, List, Optional, Union
20
+
21
+ import torch
22
+ from lightning.pytorch.callbacks import BasePredictionWriter
23
+ from omegaconf import DictConfig, OmegaConf, open_dict
24
+ from omegaconf.listconfig import ListConfig
25
+ from torch.utils.data import ChainDataset
26
+
27
+ from nemo.collections.asr.data import audio_to_text, audio_to_text_dali
28
+ from nemo.collections.asr.data.huggingface.hf_audio_to_text_dataset import (
29
+ get_hf_audio_to_text_bpe_dataset,
30
+ get_hf_audio_to_text_char_dataset,
31
+ )
32
+ from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations
33
+ from nemo.collections.common.data.dataset import CodeSwitchedDataset, ConcatDataset
34
+ from nemo.utils import logging
35
+
36
+
37
+ def inject_dataloader_value_from_model_config(model_cfg: dict, dataloader_cfg: DictConfig, key: str):
38
+ """
39
+ Extracts the label set provided at the top level of the model, and propagates it to the dataloader
40
+ config.
41
+
42
+ Args:
43
+ model_cfg: A DictConfig representing the model's config.
44
+ dataloader_cfg: A DictConfig representing the individual data loader
45
+ key: A str value representing a key in the model_cfg whose value will be propagated to the
46
+ dataloader config.
47
+ """
48
+ if key not in model_cfg:
49
+ logging.info(
50
+ f"Model level config does not contain `{key}`, please explicitly provide `{key}` to the dataloaders."
51
+ )
52
+ return
53
+
54
+ if not isinstance(dataloader_cfg, DictConfig):
55
+ dataloader_cfg = DictConfig(dataloader_cfg)
56
+
57
+ # If key exists in the data loader config (either set explicitly or as a placeholder (via None))
58
+ if key in dataloader_cfg:
59
+ # Dataloader `labels` is provided and is non-null
60
+ if dataloader_cfg[key] is not None and model_cfg[key] != dataloader_cfg[key]:
61
+ # Model level `labels` dont match Dataloader level `labels`
62
+ logging.warning(
63
+ f'`{key}` is explicitly provided to the data loader, and is different from '
64
+ f'the `{key}` provided at the model level config.\n'
65
+ f'If this is incorrect, please set the dataloader\'s `{key}` to None.'
66
+ )
67
+
68
+ else:
69
+ # Dataloader `key` is None or values match
70
+ # Propagate from model level `key` (even if they match)
71
+ with open_dict(dataloader_cfg):
72
+ dataloader_cfg[key] = model_cfg[key]
73
+
74
+ else:
75
+ # If key key doesnt even exist in dataloader_cfg, inject it explicitly
76
+ with open_dict(dataloader_cfg):
77
+ dataloader_cfg[key] = model_cfg[key]
78
+
79
+
80
+ def get_concat_char_dataset(
81
+ config: dict, global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor'] = None
82
+ ) -> ConcatDataset:
83
+ """
84
+ Instantiates an instance of ConcatDataset containing one or more intances of
85
+ Character Encoding based AudioToCharDataset.
86
+
87
+ Args:
88
+ config: Config of the AudioToCharDataset.
89
+ global_rank: Global rank of this device.
90
+ world_size: Global world size in the training method.
91
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
92
+
93
+ Returns:
94
+ An instance of ConcatDataset containing one or more instances of AudioToCharDataset.
95
+ """
96
+ if 'labels' not in config:
97
+ logging.warning(f"dataset does not have explicitly defined labels")
98
+
99
+ manifest_filepaths = config['manifest_filepath']
100
+ datasets = []
101
+
102
+ # needed to support validation Concat Datasets that arrive here as
103
+ # [[dataset1,dataset2]] otherwise ModelPT would interfere
104
+ if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str):
105
+ logging.info(f"removing an extra nesting level from {manifest_filepaths}")
106
+ manifest_filepaths = config['manifest_filepath'][0]
107
+
108
+ for manifest_filepath in manifest_filepaths:
109
+ conf = copy.deepcopy(config)
110
+ conf['manifest_filepath'] = manifest_filepath
111
+
112
+ dataset = get_char_dataset(config=conf, augmentor=augmentor)
113
+ datasets.append(dataset)
114
+
115
+ dataset = ConcatDataset(
116
+ datasets,
117
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
118
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
119
+ sampling_scale=config.get('concat_sampling_scale', 1),
120
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
121
+ shuffle=config.get('concat_shuffle', True),
122
+ seed=config.get('concat_sampling_seed', None),
123
+ global_rank=global_rank,
124
+ world_size=world_size,
125
+ )
126
+ return dataset
127
+
128
+
129
+ def get_char_dataset(config: dict, augmentor: Optional['AudioAugmentor'] = None) -> audio_to_text.AudioToCharDataset:
130
+ """
131
+ Instantiates a Character Encoding based AudioToCharDataset.
132
+
133
+ Args:
134
+ config: Config of the AudioToCharDataset.
135
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
136
+
137
+ Returns:
138
+ An instance of AudioToCharDataset.
139
+ """
140
+ if 'labels' not in config:
141
+ logging.warning(f"dataset does not have explicitly defined labels")
142
+
143
+ dataset = audio_to_text.AudioToCharDataset(
144
+ manifest_filepath=config['manifest_filepath'],
145
+ labels=config.get('labels', None),
146
+ sample_rate=config['sample_rate'],
147
+ int_values=config.get('int_values', False),
148
+ augmentor=augmentor,
149
+ max_duration=config.get('max_duration', None),
150
+ min_duration=config.get('min_duration', None),
151
+ max_utts=config.get('max_utts', 0),
152
+ blank_index=config.get('blank_index', -1),
153
+ unk_index=config.get('unk_index', -1),
154
+ normalize=config.get('normalize_transcripts', False),
155
+ trim=config.get('trim_silence', False),
156
+ parser=config.get('parser', 'en'),
157
+ return_sample_id=config.get('return_sample_id', False),
158
+ channel_selector=config.get('channel_selector', None),
159
+ )
160
+ return dataset
161
+
162
+
163
+ def get_concat_bpe_dataset(
164
+ config: dict,
165
+ tokenizer: 'TokenizerSpec',
166
+ global_rank: int,
167
+ world_size: int,
168
+ augmentor: Optional['AudioAugmentor'] = None,
169
+ ) -> ConcatDataset:
170
+ """
171
+ Instantiates a ContactDataset based on several Byte Pair Encoding / Word Piece Encoding based AudioToBPEDatasets.
172
+
173
+ Args:
174
+ config: Config of the AudioToBPEDataset.
175
+ tokenizer: An instance of a TokenizerSpec object.
176
+ global_rank: Global rank of this device.
177
+ world_size: Global world size in the training method.
178
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
179
+
180
+ Returns:
181
+ An instance of ConcatDataset containing several instances of AudioToBPEDataset.
182
+ """
183
+ manifest_filepaths = config['manifest_filepath']
184
+ datasets = []
185
+
186
+ # needed to support validation Concat Datasets that arrive here as
187
+ # [[dataset1,dataset2]] otherwise ModelPT would interfere
188
+ if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str):
189
+ logging.info(f"removing an extra nesting level from {manifest_filepaths}")
190
+ manifest_filepaths = config['manifest_filepath'][0]
191
+
192
+ for manifest_filepath in manifest_filepaths:
193
+ conf = copy.deepcopy(config)
194
+ conf['manifest_filepath'] = manifest_filepath
195
+ dataset = get_bpe_dataset(config=conf, tokenizer=tokenizer, augmentor=augmentor)
196
+ datasets.append(dataset)
197
+
198
+ dataset = ConcatDataset(
199
+ datasets,
200
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
201
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
202
+ sampling_scale=config.get('concat_sampling_scale', 1),
203
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
204
+ shuffle=config.get('concat_shuffle', True),
205
+ seed=config.get('concat_sampling_seed', None),
206
+ global_rank=global_rank,
207
+ world_size=world_size,
208
+ )
209
+ return dataset
210
+
211
+
212
+ def get_bpe_dataset(
213
+ config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['AudioAugmentor'] = None
214
+ ) -> audio_to_text.AudioToBPEDataset:
215
+ """
216
+ Instantiates a Byte Pair Encoding / Word Piece Encoding based AudioToBPEDataset.
217
+
218
+ Args:
219
+ config: Config of the AudioToBPEDataset.
220
+ tokenizer: An instance of a TokenizerSpec object.
221
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
222
+
223
+ Returns:
224
+ An instance of AudioToBPEDataset.
225
+ """
226
+ dataset = audio_to_text.AudioToBPEDataset(
227
+ manifest_filepath=config['manifest_filepath'],
228
+ tokenizer=tokenizer,
229
+ sample_rate=config['sample_rate'],
230
+ int_values=config.get('int_values', False),
231
+ augmentor=augmentor,
232
+ max_duration=config.get('max_duration', None),
233
+ min_duration=config.get('min_duration', None),
234
+ max_utts=config.get('max_utts', 0),
235
+ trim=config.get('trim_silence', False),
236
+ use_start_end_token=config.get('use_start_end_token', True),
237
+ return_sample_id=config.get('return_sample_id', False),
238
+ channel_selector=config.get('channel_selector', None),
239
+ )
240
+ return dataset
241
+
242
+
243
+ def get_concat_tarred_dataset(
244
+ config: dict,
245
+ shuffle_n: int,
246
+ global_rank: int,
247
+ world_size: int,
248
+ tokenizer: Optional['TokenizerSpec'] = None,
249
+ augmentor: Optional['AudioAugmentor'] = None,
250
+ ) -> ConcatDataset:
251
+ """
252
+ Instantiates a ConcatDataset containing multiple Word Piece/BPE Encoding based TarredAudioToBPEDataset or a char based TarredAudioToCharDataset.
253
+
254
+ Args:
255
+ config: Config of the TarredAudioToBPEDataset or TarredAudioToCharDataset.
256
+ shuffle_n: How many samples to look ahead and load to be shuffled.
257
+ See WebDataset documentation for more details.
258
+ tokenizer: An instance of a TokenizerSpec object if BPE dataset is needed.
259
+ global_rank: Global rank of this device.
260
+ world_size: Global world size in the training method.
261
+ Passsing None would return a char-based dataset.
262
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
263
+
264
+ Returns:
265
+ An instance of ConcatDataset containing one or more TarredAudioToBPEDatasets or TarredAudioToCharDatasets.
266
+ """
267
+
268
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
269
+ manifest_filepaths = config['manifest_filepath']
270
+ datasets = []
271
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
272
+ zip(tarred_audio_filepaths, manifest_filepaths)
273
+ ):
274
+ conf = copy.deepcopy(config)
275
+ conf['manifest_filepath'] = manifest_filepath
276
+ conf['tarred_audio_filepaths'] = tarred_audio_filepath
277
+ dataset = get_tarred_dataset(
278
+ config=conf,
279
+ tokenizer=tokenizer,
280
+ shuffle_n=shuffle_n,
281
+ global_rank=global_rank,
282
+ world_size=world_size,
283
+ augmentor=augmentor,
284
+ )
285
+ datasets.append(dataset)
286
+
287
+ dataset = ConcatDataset(
288
+ datasets,
289
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
290
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
291
+ sampling_scale=config.get('concat_sampling_scale', 1),
292
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
293
+ shuffle=config.get('concat_shuffle', True),
294
+ seed=config.get('concat_sampling_seed', None),
295
+ global_rank=global_rank,
296
+ world_size=world_size,
297
+ )
298
+ return dataset
299
+
300
+
301
+ def get_tarred_dataset(
302
+ config: dict,
303
+ shuffle_n: int,
304
+ global_rank: int,
305
+ world_size: int,
306
+ tokenizer: Optional['TokenizerSpec'] = None,
307
+ augmentor: Optional['AudioAugmentor'] = None,
308
+ ) -> Union[audio_to_text.TarredAudioToBPEDataset, audio_to_text.TarredAudioToCharDataset]:
309
+ """
310
+ Instantiates a Word Piece/BPE Encoding based TarredAudioToBPEDataset or a char based TarredAudioToCharDataset.
311
+
312
+ Args:
313
+ config: Config of the TarredAudioToBPEDataset or TarredAudioToCharDataset.
314
+ shuffle_n: How many samples to look ahead and load to be shuffled.
315
+ See WebDataset documentation for more details.
316
+ tokenizer: An instance of a TokenizerSpec object if BPE dataset is needed.
317
+ global_rank: Global rank of this device.
318
+ world_size: Global world size in the training method.
319
+ Passsing None would return a char-based dataset.
320
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
321
+
322
+ Returns:
323
+ An instance of TarredAudioToBPEDataset or TarredAudioToCharDataset.
324
+ """
325
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
326
+ manifest_filepaths = config['manifest_filepath']
327
+ datasets = []
328
+ tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths)
329
+ manifest_filepaths = convert_to_config_list(manifest_filepaths)
330
+
331
+ bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets
332
+ if bucketing_weights:
333
+ for idx, weight in enumerate(bucketing_weights):
334
+ if not isinstance(weight, int) or weight <= 0:
335
+ raise ValueError(f"bucket weights must be positive integers")
336
+
337
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
338
+ raise ValueError(
339
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets."
340
+ )
341
+
342
+ if 'labels' not in config:
343
+ logging.warning(f"dataset does not have explicitly defined labels")
344
+
345
+ if 'max_utts' in config:
346
+ raise ValueError('"max_utts" parameter is not supported for tarred datasets')
347
+
348
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
349
+ zip(tarred_audio_filepaths, manifest_filepaths)
350
+ ):
351
+ if len(tarred_audio_filepath) == 1:
352
+ tarred_audio_filepath = tarred_audio_filepath[0]
353
+ if len(manifest_filepath) == 1:
354
+ manifest_filepath = manifest_filepath[0]
355
+
356
+ if tokenizer is None:
357
+ dataset = audio_to_text.TarredAudioToCharDataset(
358
+ audio_tar_filepaths=tarred_audio_filepath,
359
+ manifest_filepath=manifest_filepath,
360
+ labels=config.get('labels', None),
361
+ sample_rate=config['sample_rate'],
362
+ int_values=config.get('int_values', False),
363
+ augmentor=augmentor,
364
+ shuffle_n=shuffle_n,
365
+ max_duration=config.get('max_duration', None),
366
+ min_duration=config.get('min_duration', None),
367
+ blank_index=config.get('blank_index', -1),
368
+ unk_index=config.get('unk_index', -1),
369
+ normalize=config.get('normalize_transcripts', False),
370
+ trim=config.get('trim_silence', False),
371
+ parser=config.get('parser', 'en'),
372
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
373
+ shard_manifests=config.get('shard_manifests', False),
374
+ global_rank=global_rank,
375
+ world_size=world_size,
376
+ return_sample_id=config.get('return_sample_id', False),
377
+ )
378
+ else:
379
+ dataset = audio_to_text.TarredAudioToBPEDataset(
380
+ audio_tar_filepaths=tarred_audio_filepath,
381
+ manifest_filepath=manifest_filepath,
382
+ tokenizer=tokenizer,
383
+ sample_rate=config['sample_rate'],
384
+ int_values=config.get('int_values', False),
385
+ augmentor=augmentor,
386
+ shuffle_n=shuffle_n,
387
+ max_duration=config.get('max_duration', None),
388
+ min_duration=config.get('min_duration', None),
389
+ trim=config.get('trim_silence', False),
390
+ use_start_end_token=config.get('use_start_end_token', True),
391
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
392
+ shard_manifests=config.get('shard_manifests', False),
393
+ global_rank=global_rank,
394
+ world_size=world_size,
395
+ return_sample_id=config.get('return_sample_id', False),
396
+ )
397
+ if bucketing_weights:
398
+ [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])]
399
+ else:
400
+ datasets.append(dataset)
401
+
402
+ return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank)
403
+
404
+
405
+ def get_code_switched_dataset(
406
+ config: dict,
407
+ shuffle_n: int,
408
+ global_rank: int,
409
+ world_size: int,
410
+ tokenizer: Optional['TokenizerSpec'] = None,
411
+ augmentor: Optional['AudioAugmentor'] = None,
412
+ ) -> CodeSwitchedDataset:
413
+
414
+ if 'manifest_filepath' not in config:
415
+ raise ValueError("`manifest_filepath` must be provided in the dataset config if `is_code_switched=True`")
416
+ if 'code_switched' not in config:
417
+ raise ValueError("`code_switched` param group must be in the dataset config if `is_code_switched=True`")
418
+
419
+ manifest_filepaths = config['manifest_filepath']
420
+ tarred_audio_filepaths = config.get('tarred_audio_filepaths', None)
421
+
422
+ cs_config = OmegaConf.to_container(config['code_switched'])
423
+
424
+ # needed to support validation Datasets that arrive here as
425
+ # [[dataset1,dataset2]] otherwise ModelPT would interfere
426
+ if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str):
427
+ manifest_filepaths = config['manifest_filepath'][0]
428
+ if tarred_audio_filepaths is None:
429
+ tarred_audio_filepaths = [None] * len(manifest_filepaths)
430
+
431
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
432
+ raise ValueError(
433
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of items."
434
+ )
435
+
436
+ datasets = []
437
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
438
+ zip(tarred_audio_filepaths, manifest_filepaths)
439
+ ):
440
+ conf = copy.deepcopy(config)
441
+ conf['manifest_filepath'] = manifest_filepath
442
+ with open_dict(conf):
443
+ conf['tarred_audio_filepaths'] = tarred_audio_filepath
444
+ if tarred_audio_filepath is None or len(tarred_audio_filepath) == 0:
445
+ if tokenizer is None:
446
+ dataset = get_char_dataset(config=conf, augmentor=None)
447
+ else:
448
+ dataset = get_bpe_dataset(config=conf, tokenizer=tokenizer, augmentor=None)
449
+ else:
450
+ dataset = get_tarred_dataset(
451
+ config=conf,
452
+ tokenizer=tokenizer,
453
+ shuffle_n=shuffle_n,
454
+ global_rank=global_rank,
455
+ world_size=world_size,
456
+ augmentor=None,
457
+ )
458
+ datasets.append(dataset)
459
+
460
+ config = OmegaConf.to_container(config)
461
+
462
+ dataset = CodeSwitchedDataset(
463
+ datasets,
464
+ shuffle=cs_config.get('shuffle', True),
465
+ min_duration=cs_config.get('min_duration', 4),
466
+ max_duration=cs_config.get('max_duration', 20),
467
+ min_monolingual=cs_config.get('min_monolingual', 0.3),
468
+ lang_probs=cs_config.get('probs', None),
469
+ db_norm=cs_config.get('db_norm', -25.0),
470
+ pause_start=cs_config.get('pause_start', 0),
471
+ pause_join=cs_config.get('pause_join', 0),
472
+ pause_end=cs_config.get('pause_end', 0),
473
+ sampling_scales=cs_config.get('sampling_scales', None),
474
+ seed=cs_config.get('seed', None),
475
+ global_rank=global_rank,
476
+ world_size=world_size,
477
+ pure_random=cs_config.get('pure_random', False),
478
+ force_monochannel=cs_config.get('force_monochannel', True),
479
+ infinity_mode=cs_config.get('infinity_mode', False),
480
+ sample_rate=config['sample_rate'],
481
+ augmentor=augmentor,
482
+ )
483
+
484
+ return dataset
485
+
486
+
487
+ def get_dali_char_dataset(
488
+ config: dict,
489
+ shuffle: bool,
490
+ device_id: int,
491
+ global_rank: int,
492
+ world_size: int,
493
+ preprocessor_cfg: Optional[DictConfig] = None,
494
+ ) -> audio_to_text_dali.AudioToCharDALIDataset:
495
+ """
496
+ Instantiates a Character Encoding based AudioToCharDALIDataset.
497
+
498
+ Args:
499
+ config: Config of the AudioToCharDALIDataset.
500
+ shuffle: Bool flag whether to shuffle the dataset.
501
+ device_id: Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0.
502
+ global_rank: Global rank of this device.
503
+ world_size: Global world size in the training method.
504
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
505
+ preprocessor_cfg: Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor.
506
+
507
+ Returns:
508
+ An instance of AudioToCharDALIDataset.
509
+ """
510
+ device = 'gpu' if torch.cuda.is_available() else 'cpu'
511
+ dataset = audio_to_text_dali.AudioToCharDALIDataset(
512
+ manifest_filepath=config['manifest_filepath'],
513
+ device=device,
514
+ batch_size=config['batch_size'],
515
+ labels=config['labels'],
516
+ sample_rate=config['sample_rate'],
517
+ audio_tar_filepaths=config.get('tarred_audio_filepaths', None),
518
+ audio_tar_index_filepaths=config.get('tarred_audio_index_filepaths', None),
519
+ max_duration=config.get('max_duration', None),
520
+ min_duration=config.get('min_duration', None),
521
+ blank_index=config.get('blank_index', -1),
522
+ unk_index=config.get('unk_index', -1),
523
+ normalize=config.get('normalize_transcripts', False),
524
+ trim=config.get('trim_silence', False),
525
+ parser=config.get('parser', 'en'),
526
+ shuffle=shuffle,
527
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
528
+ device_id=device_id,
529
+ global_rank=global_rank,
530
+ world_size=world_size,
531
+ preprocessor_cfg=preprocessor_cfg,
532
+ return_sample_id=config.get('return_sample_id', False),
533
+ )
534
+ return dataset
535
+
536
+
537
+ def get_dali_bpe_dataset(
538
+ config: dict,
539
+ tokenizer,
540
+ shuffle: bool,
541
+ device_id: int,
542
+ global_rank: int,
543
+ world_size: int,
544
+ preprocessor_cfg: Optional[DictConfig] = None,
545
+ ) -> audio_to_text_dali.AudioToCharDALIDataset:
546
+ """
547
+ Instantiates a Subword Encoding based AudioToBPEDALIDataset.
548
+
549
+ Args:
550
+ config: Config of the AudioToBPEDALIDataset.
551
+ tokenizer: An implementation of NeMo TokenizerSpec.
552
+ shuffle: Bool flag whether to shuffle the dataset.
553
+ device_id: Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0.
554
+ global_rank: Global rank of this device.
555
+ world_size: Global world size in the training method.
556
+ preprocessor_cfg: Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor.
557
+
558
+ Returns:
559
+ An instance of AudioToCharDALIDataset.
560
+ """
561
+ device = 'gpu' if torch.cuda.is_available() else 'cpu'
562
+ dataset = audio_to_text_dali.AudioToBPEDALIDataset(
563
+ manifest_filepath=config['manifest_filepath'],
564
+ tokenizer=tokenizer,
565
+ device=device,
566
+ batch_size=config['batch_size'],
567
+ sample_rate=config['sample_rate'],
568
+ audio_tar_filepaths=config.get('tarred_audio_filepaths', None),
569
+ audio_tar_index_filepaths=config.get('tarred_audio_index_filepaths', None),
570
+ max_duration=config.get('max_duration', None),
571
+ min_duration=config.get('min_duration', None),
572
+ trim=config.get('trim_silence', False),
573
+ use_start_end_token=config.get('use_start_end_token', True),
574
+ shuffle=shuffle,
575
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
576
+ device_id=device_id,
577
+ global_rank=global_rank,
578
+ world_size=world_size,
579
+ preprocessor_cfg=preprocessor_cfg,
580
+ return_sample_id=config.get('return_sample_id', False),
581
+ )
582
+ return dataset
583
+
584
+
585
+ def get_audio_to_text_char_dataset_from_config(
586
+ config, local_rank: int, global_rank: int, world_size: int, preprocessor_cfg: Optional[DictConfig] = None
587
+ ):
588
+ """
589
+ Construct Audio-To-Text Char dataset from a config.
590
+ Args:
591
+ config: dataset config
592
+ local_rank: model local rank
593
+ global_rank: model global rand
594
+ world_size: world size
595
+ preprocessor_cfg: preprocessor config, for DALI dataset
596
+
597
+ Returns:
598
+ constructed dataset or None if dataset config is invalid or nothing to load
599
+ """
600
+ if 'augmentor' in config:
601
+ augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size)
602
+ else:
603
+ augmentor = None
604
+
605
+ if 'hf_data_cfg' in config:
606
+ return get_hf_audio_to_text_char_dataset(
607
+ config=config, global_rank=global_rank, world_size=world_size, augmentor=augmentor
608
+ )
609
+
610
+ is_concat = config.get('is_concat', False)
611
+ if is_concat:
612
+ if 'concat_sampling_technique' in config and config['concat_sampling_technique'] is None:
613
+ logging.warning(
614
+ f"Concat dataset requires `concat_sampling_technique` but it was not provided. Config: {config}"
615
+ )
616
+ return None
617
+ if config['concat_sampling_technique'] == 'random':
618
+ if not 'concat_sampling_probabilities' in config:
619
+ logging.warning(f"Concat dataset requires `concat_sampling_probabilities` list. Config: {config}")
620
+ return None
621
+ else:
622
+ if not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6):
623
+ logging.warning(f"`concat_sampling_probabilities` need to sum to 1. Config: {config}")
624
+ return None
625
+
626
+ shuffle = config['shuffle']
627
+ device = 'gpu' if torch.cuda.is_available() else 'cpu'
628
+ if config.get('use_dali', False):
629
+ device_id = local_rank if device == 'gpu' else None
630
+ dataset = get_dali_char_dataset(
631
+ config=config,
632
+ shuffle=shuffle,
633
+ device_id=device_id,
634
+ global_rank=global_rank,
635
+ world_size=world_size,
636
+ preprocessor_cfg=preprocessor_cfg,
637
+ )
638
+ return dataset
639
+
640
+ # Instantiate a code-switched dataset if config is present
641
+ if config.get('is_code_switched', False):
642
+ if 'manifest_filepath' in config and config['manifest_filepath'] is None:
643
+ logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}")
644
+ return None
645
+ if not ('code_switched' in config and config['code_switched'] is not None):
646
+ logging.warning(
647
+ f"Code switched dataset requires `*_ds.code_switched.*` dict but it was not provided. Config: {config}"
648
+ )
649
+ return None
650
+ if (
651
+ ('probs' in config['code_switched'])
652
+ and (config['code_switched']['probs'] is not None)
653
+ and (not isclose(sum(config['code_switched']['probs']), 1, abs_tol=1e-6))
654
+ ):
655
+ logging.warning(f"`.code_switched.probs` need to sum to 1. Config: {config['code_switched']}")
656
+ return None
657
+
658
+ shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0
659
+ dataset = get_code_switched_dataset(
660
+ config=config,
661
+ shuffle_n=shuffle_n,
662
+ global_rank=global_rank,
663
+ world_size=world_size,
664
+ tokenizer=None,
665
+ augmentor=augmentor,
666
+ )
667
+ # Instantiate tarred dataset loader or normal dataset loader
668
+ elif config.get('is_tarred', False):
669
+ if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or (
670
+ 'manifest_filepath' in config and config['manifest_filepath'] is None
671
+ ):
672
+ logging.warning(
673
+ "Could not load dataset as `manifest_filepath` was None or "
674
+ f"`tarred_audio_filepaths` is None. Provided config : {config}"
675
+ )
676
+ return None
677
+
678
+ shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0
679
+ if is_concat:
680
+ dataset = get_concat_tarred_dataset(
681
+ config=config,
682
+ shuffle_n=shuffle_n,
683
+ global_rank=global_rank,
684
+ world_size=world_size,
685
+ augmentor=augmentor,
686
+ )
687
+ else:
688
+ dataset = get_tarred_dataset(
689
+ config=config,
690
+ shuffle_n=shuffle_n,
691
+ global_rank=global_rank,
692
+ world_size=world_size,
693
+ augmentor=augmentor,
694
+ )
695
+ else:
696
+ if 'manifest_filepath' in config and config['manifest_filepath'] is None:
697
+ logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}")
698
+ return None
699
+ if is_concat:
700
+ dataset = get_concat_char_dataset(
701
+ config=config, global_rank=global_rank, world_size=world_size, augmentor=augmentor
702
+ )
703
+ else:
704
+ dataset = get_char_dataset(config=config, augmentor=augmentor)
705
+ return dataset
706
+
707
+
708
+ def get_audio_to_text_bpe_dataset_from_config(
709
+ config,
710
+ local_rank: int,
711
+ global_rank: int,
712
+ world_size: int,
713
+ tokenizer,
714
+ preprocessor_cfg: Optional[DictConfig] = None,
715
+ ):
716
+ """
717
+ Construct Audio-To-Text BPE dataset from a config.
718
+ Args:
719
+ config: BPE dataset config
720
+ local_rank: model local rank
721
+ global_rank: model global rand
722
+ world_size: world size
723
+ tokenizer: BPE tokenizer
724
+ preprocessor_cfg: preprocessor config, for DALI BPE dataset
725
+
726
+ Returns:
727
+ constructed dataset or None if dataset config is invalid or nothing to load
728
+ """
729
+ if 'augmentor' in config:
730
+ augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size)
731
+ else:
732
+ augmentor = None
733
+
734
+ if 'hf_data_cfg' in config:
735
+ return get_hf_audio_to_text_bpe_dataset(
736
+ config=config, global_rank=global_rank, world_size=world_size, tokenizer=tokenizer, augmentor=augmentor
737
+ )
738
+
739
+ is_concat = config.get('is_concat', False)
740
+ if is_concat:
741
+ if 'concat_sampling_technique' in config and config['concat_sampling_technique'] is None:
742
+ logging.warning(
743
+ f"Concat dataset requires `concat_sampling_technique` but it was not provided. Config: {config}"
744
+ )
745
+ return None
746
+
747
+ if config['concat_sampling_technique'] == 'random':
748
+ if not 'concat_sampling_probabilities' in config:
749
+ logging.warning(f"Concat dataset requires `concat_sampling_probabilities` list. Config: {config}")
750
+ return None
751
+ else:
752
+ if not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6):
753
+ logging.warning(f"`concat_sampling_probabilities` need to sum to 1. Config: {config}")
754
+ return None
755
+
756
+ shuffle = config['shuffle']
757
+ device = 'gpu' if torch.cuda.is_available() else 'cpu'
758
+ if config.get('use_dali', False):
759
+ device_id = local_rank if device == 'gpu' else None
760
+ dataset = get_dali_bpe_dataset(
761
+ config=config,
762
+ tokenizer=tokenizer,
763
+ shuffle=shuffle,
764
+ device_id=device_id,
765
+ global_rank=global_rank,
766
+ world_size=world_size,
767
+ preprocessor_cfg=preprocessor_cfg,
768
+ )
769
+ return dataset
770
+
771
+ # Instantiate a code-switched dataset if config is present
772
+ if config.get('is_code_switched', False):
773
+ if 'manifest_filepath' in config and config['manifest_filepath'] is None:
774
+ logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}")
775
+ return None
776
+ if not ('code_switched' in config and config['code_switched'] is not None):
777
+ logging.warning(
778
+ f"Code switched dataset requires `*_ds.code_switched.*` dict but it was not provided. Config: {config}"
779
+ )
780
+ return None
781
+ if (
782
+ ('probs' in config['code_switched'])
783
+ and (config['code_switched']['probs'] is not None)
784
+ and (not isclose(sum(config['code_switched']['probs']), 1, abs_tol=1e-6))
785
+ ):
786
+ logging.warning(f"`.code_switched.probs` need to sum to 1. Config: {config['code_switched']}")
787
+ return None
788
+
789
+ shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0
790
+ dataset = get_code_switched_dataset(
791
+ config=config,
792
+ shuffle_n=shuffle_n,
793
+ global_rank=global_rank,
794
+ world_size=world_size,
795
+ tokenizer=tokenizer,
796
+ augmentor=augmentor,
797
+ )
798
+ # Instantiate tarred dataset loader or normal dataset loader
799
+ elif config.get('is_tarred', False):
800
+ if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or (
801
+ 'manifest_filepath' in config and config['manifest_filepath'] is None
802
+ ):
803
+ logging.warning(
804
+ "Could not load dataset as `manifest_filepath` was None or "
805
+ f"`tarred_audio_filepaths` is None. Provided config : {config}"
806
+ )
807
+ return None
808
+
809
+ shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0
810
+ if is_concat:
811
+ dataset = get_concat_tarred_dataset(
812
+ config=config,
813
+ tokenizer=tokenizer,
814
+ shuffle_n=shuffle_n,
815
+ global_rank=global_rank,
816
+ world_size=world_size,
817
+ augmentor=augmentor,
818
+ )
819
+ else:
820
+ dataset = get_tarred_dataset(
821
+ config=config,
822
+ tokenizer=tokenizer,
823
+ shuffle_n=shuffle_n,
824
+ global_rank=global_rank,
825
+ world_size=world_size,
826
+ augmentor=augmentor,
827
+ )
828
+ else:
829
+ if 'manifest_filepath' in config and config['manifest_filepath'] is None:
830
+ logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}")
831
+ return None
832
+ if is_concat:
833
+ dataset = get_concat_bpe_dataset(
834
+ config=config,
835
+ global_rank=global_rank,
836
+ world_size=world_size,
837
+ tokenizer=tokenizer,
838
+ augmentor=augmentor,
839
+ )
840
+ else:
841
+ dataset = get_bpe_dataset(config=config, tokenizer=tokenizer, augmentor=augmentor)
842
+ return dataset
843
+
844
+
845
+ class ASRPredictionWriter(BasePredictionWriter):
846
+ def __init__(self, dataset, output_file: str):
847
+ super().__init__(write_interval="batch")
848
+ self.outf = open(output_file, 'w', encoding='utf-8')
849
+ self.dataset = dataset
850
+ self.samples_num = 0
851
+
852
+ def write_on_batch_end(
853
+ self,
854
+ trainer,
855
+ pl_module: 'LightningModule',
856
+ prediction: Any,
857
+ batch_indices: List[int],
858
+ batch: Any,
859
+ batch_idx: int,
860
+ dataloader_idx: int,
861
+ ):
862
+ import lhotse
863
+
864
+ for sample_id, transcribed_text in prediction:
865
+ item = {}
866
+ if isinstance(sample_id, lhotse.cut.Cut):
867
+ sample = sample_id
868
+ if isinstance(sample, lhotse.cut.MixedCut):
869
+ sample = sample.first_non_padding_cut
870
+ if sample.recording.sources[0].source != '':
871
+ item["audio_filepath"] = sample.recording.sources[0].source
872
+ else:
873
+ item["audio_filepath"] = sample.id
874
+ item["offset"] = sample.start
875
+ item["duration"] = sample.duration
876
+ item["text"] = sample.supervisions[0].text or ''
877
+ if hasattr(sample, 'shard_id'):
878
+ item["shard_id"] = sample.shard_id
879
+ item["pred_text"] = transcribed_text
880
+ self.outf.write(json.dumps(item) + "\n")
881
+ self.samples_num += 1
882
+ else:
883
+ sample = self.dataset.get_manifest_sample(sample_id)
884
+ item["audio_filepath"] = sample.audio_file
885
+ item["offset"] = sample.offset
886
+ item["duration"] = sample.duration
887
+ item["text"] = sample.text_raw
888
+ item["pred_text"] = transcribed_text
889
+ self.outf.write(json.dumps(item) + "\n")
890
+ self.samples_num += 1
891
+ return
892
+
893
+ def close_output_file(self):
894
+ self.outf.close()
895
+ return self.samples_num
896
+
897
+
898
+ def convert_to_config_list(initial_list):
899
+ if type(initial_list) is str:
900
+ initial_list = initial_list.split(",")
901
+ if initial_list is None or initial_list == []:
902
+ raise ValueError("manifest_filepaths and tarred_audio_filepaths must not be empty.")
903
+ if not isinstance(initial_list, ListConfig):
904
+ initial_list = ListConfig([initial_list])
905
+
906
+ for list_idx, list_val in enumerate(initial_list):
907
+ if type(list_val) != type(initial_list[0]):
908
+ raise ValueError(
909
+ "manifest_filepaths and tarred_audio_filepaths need to be a list of lists for bucketing or just a list of strings"
910
+ )
911
+ if type(initial_list[0]) is not ListConfig:
912
+ initial_list = ListConfig([initial_list])
913
+ return initial_list
914
+
915
+
916
+ def get_chain_dataset(datasets, ds_config, rank=0):
917
+ if len(datasets) > 1:
918
+ if ds_config.get('bucketing_batch_size', None) is not None:
919
+ bucketing_batch_sizes = calc_bucketing_batch_sizes(ds_config, len(datasets))
920
+ logging.info(
921
+ f"Batch bucketing is enabled for {len(datasets)} buckets with adaptive batch sizes of {bucketing_batch_sizes}!"
922
+ )
923
+ for idx, dataset in enumerate(datasets):
924
+ datasets[idx] = audio_to_text.BucketingDataset(
925
+ dataset=dataset, bucketing_batch_size=bucketing_batch_sizes[idx]
926
+ )
927
+ else:
928
+ logging.info(
929
+ f"Batch bucketing is enabled for {len(datasets)} buckets with fixed batch size of {ds_config['batch_size']}!"
930
+ )
931
+
932
+ if len(datasets) == 1:
933
+ return datasets[0]
934
+ bucketing_strategy = ds_config.get('bucketing_strategy', 'synced_randomized')
935
+ if bucketing_strategy == 'fixed_order':
936
+ return ChainDataset(datasets)
937
+ elif bucketing_strategy == 'synced_randomized':
938
+ return audio_to_text.RandomizedChainDataset(datasets=datasets, rnd_seed=0)
939
+ elif bucketing_strategy == 'fully_randomized':
940
+ return audio_to_text.RandomizedChainDataset(datasets=datasets, rnd_seed=random.randint(0, 30000) + rank)
941
+ else:
942
+ raise ValueError(
943
+ f'bucketing_strategy={bucketing_strategy} is not supported! Supported strategies are [fixed_order, fully_randomized, synced_randomized].'
944
+ )
945
+
946
+
947
+ def calc_bucketing_batch_sizes(ds_config, datasets_len):
948
+ bucketing_batch_size = ds_config['bucketing_batch_size']
949
+ bucketing_weights = ds_config.get('bucketing_weights', None) # To adjust for upsampled buckets
950
+
951
+ bucketing_batch_sizes = []
952
+
953
+ if ds_config['batch_size'] != 1:
954
+ raise ValueError(
955
+ f"batch_size should be set to one when bucketing_batch_size is set and adaptive bucketing is enabled (batch_size={ds_config['batch_size']}!"
956
+ )
957
+ if type(bucketing_batch_size) == int: # linear scaling
958
+ if bucketing_weights: # Want same batchsize for the same duplicated bucket
959
+ for idx, weight in enumerate(bucketing_weights):
960
+ scale_factor = datasets_len - idx
961
+ [bucketing_batch_sizes.append(scale_factor * bucketing_batch_size) for _ in range(weight)]
962
+ else:
963
+ for idx in range(datasets_len):
964
+ scale_factor = datasets_len - idx
965
+ bucketing_batch_sizes.append(scale_factor * bucketing_batch_size)
966
+ elif isinstance(bucketing_batch_size, ListConfig) or isinstance(
967
+ bucketing_batch_size, list
968
+ ): # assigned bucket sizes
969
+ if bucketing_weights: # Want same batchsize for same duplicated bucket
970
+ for idx, weight in enumerate(bucketing_weights):
971
+ [bucketing_batch_sizes.append(bucketing_batch_size[idx]) for _ in range(weight)]
972
+ else:
973
+ bucketing_batch_sizes = bucketing_batch_size
974
+ else:
975
+ raise ValueError(
976
+ f"bucketing_batch_size should be an integer or a list (bucketing_batch_size={bucketing_batch_size})!"
977
+ )
978
+
979
+ if len(bucketing_batch_sizes) != datasets_len:
980
+ raise ValueError(
981
+ f"batch_size should have the same length as the number of buckets ({len(bucketing_batch_sizes)}!={datasets_len}) "
982
+ )
983
+ return bucketing_batch_sizes
nemo/collections/asr/data/audio_to_text_lhotse.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict, Optional, Tuple
16
+
17
+ import torch.utils.data
18
+ from lhotse.dataset import AudioSamples
19
+ from lhotse.dataset.collation import collate_vectors
20
+
21
+ from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper
22
+ from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec
23
+ from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType
24
+
25
+
26
+ class LhotseSpeechToTextBpeDataset(torch.utils.data.Dataset):
27
+ """
28
+ This dataset is based on BPE datasets from audio_to_text.py.
29
+ Unlike native NeMo datasets, Lhotse dataset defines only the mapping from
30
+ a CutSet (meta-data) to a mini-batch with PyTorch tensors.
31
+ Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any).
32
+ Managing data, sampling, de-duplication across workers/nodes etc. is all handled
33
+ by Lhotse samplers instead.
34
+ """
35
+
36
+ @property
37
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
38
+ return {
39
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
40
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
41
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
42
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
43
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
44
+ }
45
+
46
+ def __init__(self, tokenizer: TokenizerSpec, return_cuts: bool = False):
47
+ super().__init__()
48
+ self.tokenizer = TokenizerWrapper(tokenizer)
49
+ self.load_audio = AudioSamples(fault_tolerant=True)
50
+ self.return_cuts = return_cuts
51
+
52
+ def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]:
53
+ audio, audio_lens, cuts = self.load_audio(cuts)
54
+ tokens = [
55
+ torch.cat(
56
+ [
57
+ torch.as_tensor(s.tokens if hasattr(s, "tokens") else self.tokenizer(s.text or "", s.language))
58
+ for s in c.supervisions
59
+ ],
60
+ dim=0,
61
+ )
62
+ for c in cuts
63
+ ]
64
+ token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long)
65
+ tokens = collate_vectors(tokens, padding_value=0)
66
+ if self.return_cuts:
67
+ return audio, audio_lens, tokens, token_lens, cuts.drop_in_memory_data()
68
+ return audio, audio_lens, tokens, token_lens
nemo/collections/asr/data/audio_to_text_lhotse_prompted.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Callable, Optional, Union
16
+
17
+ import torch.utils.data
18
+ from lhotse import CutSet
19
+ from lhotse.cut import MixedCut
20
+ from lhotse.dataset import AudioSamples
21
+ from lhotse.dataset.collation import collate_vectors
22
+
23
+ from nemo.collections.common.data import apply_prompt_format_fn
24
+ from nemo.collections.common.prompts import CanaryPromptFormatter, PromptFormatter
25
+ from nemo.collections.common.tokenizers import TokenizerSpec
26
+
27
+
28
+ @dataclass
29
+ class PromptedAudioToTextMiniBatch:
30
+ audio: torch.Tensor
31
+ audio_lens: torch.Tensor
32
+ transcript: torch.Tensor
33
+ transcript_lens: torch.Tensor
34
+ prompt: torch.Tensor
35
+ prompt_lens: torch.Tensor
36
+ prompted_transcript: torch.Tensor
37
+ prompted_transcript_lens: torch.Tensor
38
+ cuts: Optional[CutSet] = None
39
+
40
+ def get_decoder_inputs_outputs(self) -> tuple[torch.Tensor, torch.Tensor]:
41
+ """
42
+ Returns the inputs and outputs of transformer decoder for training.
43
+ The input is ``prompted_transcript`` (minus last token),
44
+ and the output is ``prompted_transcript`` (minus first token).
45
+ """
46
+ return self.prompted_transcript[:, :-1], self.prompted_transcript[:, 1:]
47
+
48
+
49
+ class PromptedAudioToTextLhotseDataset(torch.utils.data.Dataset):
50
+ """
51
+ This dataset is based on :class:`~nemo.collections.asr.data.audio_to_text_lhotse.LhotseSpeechToTextBpeDataset`.
52
+ It is a Lhotse-style dataset that converts a mini-batch of Cuts into tensors.
53
+ The main difference from ``LhotseSpeechToTextBpeDataset`` is that we introduce
54
+ a special prompt format for multitask encoder-decoder models.
55
+
56
+ To perform the prompt formatting, we accept a ``prompt_format_fn``.
57
+ It's expected to accept:
58
+ * a ``CutSet`` which it will internally iterate over for utterances, and
59
+ * a ``TokenizerWrapper`` object that will be internally used to tokenize the utterances
60
+
61
+ Tokenized utterances will be extended with special prompt tokens according to ``prompt_format_fn`` logic.
62
+ We support cuts with multiple supervision segments -- their tokenized texts will be concatenated before we add the prompt tokens.
63
+ This is useful, for example, in code-switched scenarios where each segment is spoken in a different language.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ tokenizer: TokenizerSpec,
69
+ prompt: PromptFormatter,
70
+ ):
71
+ super().__init__()
72
+ self.tokenizer = tokenizer
73
+ self.load_audio = AudioSamples(fault_tolerant=True)
74
+ self.padding_value = self.tokenizer.pad_id
75
+ self.prompt = prompt
76
+
77
+ def __getitem__(self, cuts: CutSet) -> PromptedAudioToTextMiniBatch:
78
+ audio, audio_lens, cuts = self.load_audio(cuts)
79
+
80
+ # Fast-path: the tokenization and prompt formatting was already done before sampling.
81
+ attrs = ("input_ids", "context_ids", "answer_ids")
82
+ pre_formatted = all(hasattr(c, a) for c in cuts for a in attrs)
83
+ if pre_formatted:
84
+ prompts_with_answers, prompts, answers = zip(*((c.input_ids, c.context_ids, c.answer_ids) for c in cuts))
85
+ else:
86
+ formatted = [apply_prompt_format_fn(cut, self.prompt) for cut in cuts]
87
+ prompts_with_answers = [ex["input_ids"] for ex in formatted]
88
+ prompts = [ex["context_ids"] for ex in formatted]
89
+ answers = [ex["answer_ids"] for ex in formatted]
90
+
91
+ transcript, transcript_lens = self._collate_tokens(answers)
92
+ prompts_with_answers, prompts_with_answers_lens = self._collate_tokens(prompts_with_answers)
93
+ prompts, prompt_lens = self._collate_tokens(prompts)
94
+
95
+ return PromptedAudioToTextMiniBatch(
96
+ audio=audio,
97
+ audio_lens=audio_lens,
98
+ transcript=transcript,
99
+ transcript_lens=transcript_lens,
100
+ prompt=prompts,
101
+ prompt_lens=prompt_lens,
102
+ prompted_transcript=prompts_with_answers,
103
+ prompted_transcript_lens=prompts_with_answers_lens,
104
+ cuts=_drop_in_memory_data(cuts),
105
+ )
106
+
107
+ def _collate_tokens(self, tokens: list[Union[list[int], torch.Tensor]]) -> tuple[torch.Tensor, torch.Tensor]:
108
+ tokens = [torch.as_tensor(t) for t in tokens]
109
+ token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long)
110
+ tokens = collate_vectors(tokens, padding_value=self.padding_value)
111
+ return tokens, token_lens
112
+
113
+
114
+ class ProbablyIncorrectLanguageKeyError(RuntimeError):
115
+ pass
116
+
117
+
118
+ def _drop_in_memory_data(
119
+ cuts: CutSet,
120
+ _fields=frozenset(MixedCut.__dataclass_fields__.keys()),
121
+ ) -> CutSet:
122
+ """Workaround for an edge case in cuts.drop_in_memory_data() on MixedCut with Lhotse<1.29.0"""
123
+ ans = []
124
+ for c in cuts:
125
+ # Not a mixed cut or a mixed cut that wasn't assigned any extra attributes.
126
+ if not isinstance(c, MixedCut) or _fields.issuperset(c.__dict__.keys()):
127
+ ans.append(c.drop_in_memory_data())
128
+ else:
129
+ extra_attrs = {k: v for k, v in c.__dict__.items() if k not in _fields}
130
+ for k in extra_attrs:
131
+ delattr(c, k)
132
+ ans.append(c.drop_in_memory_data())
133
+ for k, v in extra_attrs.items():
134
+ setattr(ans[-1], k, v)
135
+ setattr(c, k, v)
136
+ return CutSet(ans)
nemo/collections/asr/data/data_simulation.py ADDED
@@ -0,0 +1,1700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import concurrent
16
+ import os
17
+ import warnings
18
+ from typing import Dict, List, Tuple
19
+
20
+ import numpy as np
21
+ import soundfile as sf
22
+ import torch
23
+ from omegaconf import OmegaConf
24
+ from scipy.signal import convolve
25
+ from scipy.signal.windows import cosine, hamming, hann
26
+ from tqdm import tqdm
27
+
28
+ from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations
29
+ from nemo.collections.asr.parts.utils.data_simulation_utils import (
30
+ DataAnnotator,
31
+ SpeechSampler,
32
+ build_speaker_samples_map,
33
+ get_background_noise,
34
+ get_cleaned_base_path,
35
+ get_random_offset_index,
36
+ get_speaker_ids,
37
+ get_speaker_samples,
38
+ get_split_points_in_alignments,
39
+ load_speaker_sample,
40
+ normalize_audio,
41
+ per_speaker_normalize,
42
+ perturb_audio,
43
+ read_audio_from_buffer,
44
+ read_noise_manifest,
45
+ )
46
+ from nemo.collections.asr.parts.utils.manifest_utils import read_manifest
47
+ from nemo.collections.asr.parts.utils.speaker_utils import get_overlap_range, is_overlap, merge_float_intervals
48
+ from nemo.utils import logging
49
+
50
+ try:
51
+ import pyroomacoustics as pra
52
+ from pyroomacoustics.directivities import CardioidFamily, DirectionVector, DirectivityPattern
53
+
54
+ PRA = True
55
+ except ImportError:
56
+ PRA = False
57
+ try:
58
+ from gpuRIR import att2t_SabineEstimator, beta_SabineEstimation, simulateRIR, t2n
59
+
60
+ GPURIR = True
61
+ except ImportError:
62
+ GPURIR = False
63
+
64
+
65
+ class MultiSpeakerSimulator(object):
66
+ """
67
+ Multispeaker Audio Session Simulator - Simulates multispeaker audio sessions using single-speaker audio files and
68
+ corresponding word alignments.
69
+
70
+ Change Log:
71
+ v1.0: Dec 2022
72
+ - First working verison, supports multispeaker simulation with overlaps, silence and RIR
73
+ v1.0.1: Feb 2023
74
+ - Multi-GPU support for speed up
75
+ - Faster random sampling routine
76
+ - Fixed sentence duration bug
77
+ - Silence and overlap length sampling algorithms are updated to guarantee `mean_silence` approximation
78
+ v1.0.2: March 2023
79
+ - Added support for segment-level gain perturbation and session-level white-noise perturbation
80
+ - Modified speaker sampling mechanism to include as many speakers as possible in each data-generation run
81
+ - Added chunking mechanism to avoid freezing in multiprocessing processes
82
+
83
+ v1.1.0 March 2023
84
+ - Faster audio-file loading with maximum audio duration parameter
85
+ - Re-organized MultiSpeakerSimulator class and moved util functions to util files.
86
+ v1.1.1 March 2023
87
+ - Changed `silence_mean` to use exactly the same sampling equation as `overlap_mean`.
88
+
89
+
90
+ Args:
91
+ cfg: OmegaConf configuration loaded from yaml file.
92
+
93
+ Parameters:
94
+ manifest_filepath (str): Manifest file with paths to single speaker audio files
95
+ sr (int): Sampling rate of the input audio files from the manifest
96
+ random_seed (int): Seed to random number generator
97
+
98
+ session_config:
99
+ num_speakers (int): Number of unique speakers per multispeaker audio session
100
+ num_sessions (int): Number of sessions to simulate
101
+ session_length (int): Length of each simulated multispeaker audio session (seconds). Short sessions
102
+ (e.g. ~240 seconds) tend to fall short of the expected overlap-ratio and silence-ratio.
103
+
104
+ session_params:
105
+ max_audio_read_sec (int): The maximum audio length in second when loading an audio file.
106
+ The bigger the number, the slower the reading speed. Should be greater than 2.5 second.
107
+ sentence_length_params (list): k,p values for a negative_binomial distribution which is sampled to get the
108
+ sentence length (in number of words)
109
+ dominance_var (float): Variance in speaker dominance (where each speaker's dominance is sampled from a normal
110
+ distribution centered on 1/`num_speakers`, and then the dominance values are together
111
+ normalized to 1)
112
+ min_dominance (float): Minimum percentage of speaking time per speaker (note that this can cause the dominance of
113
+ the other speakers to be slightly reduced)
114
+ turn_prob (float): Probability of switching speakers after each utterance
115
+
116
+ mean_silence (float): Mean proportion of silence to speaking time in the audio session. Should be in range [0, 1).
117
+ mean_silence_var (float): Variance for mean silence in all audio sessions.
118
+ This value should be 0 <= mean_silence_var < mean_silence * (1 - mean_silence).
119
+ per_silence_var (float): Variance for each silence in an audio session, set large values (e.g., 20) for de-correlation.
120
+ per_silence_min (float): Minimum duration for each silence, default to 0.
121
+ per_silence_max (float): Maximum duration for each silence, default to -1 for no maximum.
122
+ mean_overlap (float): Mean proportion of overlap in the overall non-silence duration. Should be in range [0, 1) and
123
+ recommend [0, 0.15] range for accurate results.
124
+ mean_overlap_var (float): Variance for mean overlap in all audio sessions.
125
+ This value should be 0 <= mean_overlap_var < mean_overlap * (1 - mean_overlap).
126
+ per_overlap_var (float): Variance for per overlap in each session, set large values to de-correlate silence lengths
127
+ with the latest speech segment lengths
128
+ per_overlap_min (float): Minimum per overlap duration in seconds
129
+ per_overlap_max (float): Maximum per overlap duration in seconds, set -1 for no maximum
130
+ start_window (bool): Whether to window the start of sentences to smooth the audio signal (and remove silence at
131
+ the start of the clip)
132
+ window_type (str): Type of windowing used when segmenting utterances ("hamming", "hann", "cosine")
133
+ window_size (float): Length of window at the start or the end of segmented utterance (seconds)
134
+ start_buffer (float): Buffer of silence before the start of the sentence (to avoid cutting off speech or starting
135
+ abruptly)
136
+ split_buffer (float): Split RTTM labels if greater than twice this amount of silence (to avoid long gaps between
137
+ utterances as being labelled as speech)
138
+ release_buffer (float): Buffer before window at end of sentence (to avoid cutting off speech or ending abruptly)
139
+ normalize (bool): Normalize speaker volumes
140
+ normalization_type (str): Normalizing speakers ("equal" - same volume per speaker, "var" - variable volume per
141
+ speaker)
142
+ normalization_var (str): Variance in speaker volume (sample from standard deviation centered at 1)
143
+ min_volume (float): Minimum speaker volume (only used when variable normalization is used)
144
+ max_volume (float): Maximum speaker volume (only used when variable normalization is used)
145
+ end_buffer (float): Buffer at the end of the session to leave blank
146
+
147
+ outputs:
148
+ output_dir (str): Output directory for audio sessions and corresponding label files
149
+ output_filename (str): Output filename for the wav and RTTM files
150
+ overwrite_output (bool): If true, delete the output directory if it exists
151
+ output_precision (int): Number of decimal places in output files
152
+
153
+ background_noise:
154
+ add_bg (bool): Add ambient background noise if true
155
+ background_manifest (str): Path to background noise manifest file
156
+ snr (int): SNR for background noise (using average speaker power), set `snr_min` and `snr_max` values to enable random SNR
157
+ snr_min (int): Min random SNR for background noise (using average speaker power), set `null` to use fixed SNR
158
+ snr_max (int): Max random SNR for background noise (using average speaker power), set `null` to use fixed SNR
159
+
160
+ segment_augmentor:
161
+ add_seg_aug (bool): Set True to enable augmentation on each speech segment (Default: False)
162
+ segmentor:
163
+ gain:
164
+ prob (float): Probability range (uniform distribution) gain augmentation for individual segment
165
+ min_gain_dbfs (float): minimum gain in terms of dB
166
+ max_gain_dbfs (float): maximum gain in terms of dB
167
+
168
+ session_augmentor:
169
+ add_sess_aug: (bool) set True to enable audio augmentation on the whole session (Default: False)
170
+ segmentor:
171
+ white_noise:
172
+ prob (float): Probability of adding white noise (Default: 1.0)
173
+ min_level (float): minimum gain in terms of dB
174
+ max_level (float): maximum gain in terms of dB
175
+
176
+ speaker_enforcement:
177
+ enforce_num_speakers (bool): Enforce that all requested speakers are present in the output wav file
178
+ enforce_time (list): Percentage of the way through the audio session that enforcement mode is triggered (sampled
179
+ between time 1 and 2)
180
+
181
+ segment_manifest: (parameters for regenerating the segment manifest file)
182
+ window (float): Window length for segmentation
183
+ shift (float): Shift length for segmentation
184
+ step_count (int): Number of the unit segments you want to create per utterance
185
+ deci (int): Rounding decimals for segment manifest file
186
+ """
187
+
188
+ def __init__(self, cfg):
189
+ self._params = cfg
190
+ self.annotator = DataAnnotator(cfg)
191
+ self.sampler = SpeechSampler(cfg)
192
+ # internal params
193
+ self._manifest = read_manifest(self._params.data_simulator.manifest_filepath)
194
+ self._speaker_samples = build_speaker_samples_map(self._manifest)
195
+ self._noise_samples = []
196
+ self._sentence = None
197
+ self._text = ""
198
+ self._words = []
199
+ self._alignments = []
200
+ # minimum number of alignments for a manifest to be considered valid
201
+ self._min_alignment_count = 2
202
+ self._merged_speech_intervals = []
203
+ # keep track of furthest sample per speaker to avoid overlapping same speaker
204
+ self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)]
205
+ # use to ensure overlap percentage is correct
206
+ self._missing_overlap = 0
207
+ # creating manifests during online data simulation
208
+ self.base_manifest_filepath = None
209
+ self.segment_manifest_filepath = None
210
+ self._max_audio_read_sec = self._params.data_simulator.session_params.max_audio_read_sec
211
+ self._turn_prob_min = self._params.data_simulator.session_params.get("turn_prob_min", 0.5)
212
+ # variable speaker volume
213
+ self._volume = None
214
+ self._speaker_ids = None
215
+ self._device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
216
+ self._audio_read_buffer_dict = {}
217
+ self.add_missing_overlap = self._params.data_simulator.session_params.get("add_missing_overlap", False)
218
+
219
+ if (
220
+ self._params.data_simulator.segment_augmentor.get("augmentor", None)
221
+ and self._params.data_simulator.segment_augmentor.add_seg_aug
222
+ ):
223
+ self.segment_augmentor = process_augmentations(
224
+ augmenter=self._params.data_simulator.segment_augmentor.augmentor
225
+ )
226
+ else:
227
+ self.segment_augmentor = None
228
+
229
+ if (
230
+ self._params.data_simulator.session_augmentor.get("augmentor", None)
231
+ and self._params.data_simulator.session_augmentor.add_sess_aug
232
+ ):
233
+ self.session_augmentor = process_augmentations(
234
+ augmenter=self._params.data_simulator.session_augmentor.augmentor
235
+ )
236
+ else:
237
+ self.session_augmentor = None
238
+
239
+ # Error check the input arguments for simulation
240
+ self._check_args()
241
+
242
+ # Initialize speaker permutations to maximize the number of speakers in the created dataset
243
+ self._permutated_speaker_inds = self._init_speaker_permutations(
244
+ num_sess=self._params.data_simulator.session_config.num_sessions,
245
+ num_speakers=self._params.data_simulator.session_config.num_speakers,
246
+ all_speaker_ids=self._speaker_samples.keys(),
247
+ random_seed=self._params.data_simulator.random_seed,
248
+ )
249
+
250
+ # Intialize multiprocessing related variables
251
+ self.num_workers = self._params.get("num_workers", 1)
252
+ self.multiprocessing_chunksize = self._params.data_simulator.get('multiprocessing_chunksize', 10000)
253
+ self.chunk_count = self._init_chunk_count()
254
+
255
+ def _init_speaker_permutations(self, num_sess: int, num_speakers: int, all_speaker_ids: List, random_seed: int):
256
+ """
257
+ Initialize the speaker permutations for the number of speakers in the session.
258
+ When generating the simulated sessions, we want to include as many speakers as possible.
259
+ This function generates a set of permutations that can be used to sweep all speakers in
260
+ the source dataset to make sure we maximize the total number of speakers included in
261
+ the simulated sessions.
262
+
263
+ Args:
264
+ num_sess (int): Number of sessions to generate
265
+ num_speakers (int): Number of speakers in each session
266
+ all_speaker_ids (list): List of all speaker IDs
267
+
268
+ Returns:
269
+ permuted_inds (np.array):
270
+ Array of permuted speaker indices to use for each session
271
+ Dimensions: (num_sess, num_speakers)
272
+ """
273
+ np.random.seed(random_seed)
274
+ all_speaker_id_counts = len(list(all_speaker_ids))
275
+
276
+ # Calculate how many permutations are needed
277
+ perm_set_count = int(np.ceil(num_speakers * num_sess / all_speaker_id_counts))
278
+
279
+ target_count = num_speakers * num_sess
280
+ for count in range(perm_set_count):
281
+ if target_count < all_speaker_id_counts:
282
+ seq_len = target_count
283
+ else:
284
+ seq_len = all_speaker_id_counts
285
+ if seq_len <= 0:
286
+ raise ValueError(f"seq_len is {seq_len} at count {count} and should be greater than 0")
287
+
288
+ if count == 0:
289
+ permuted_inds = np.random.permutation(len(all_speaker_ids))[:seq_len]
290
+ else:
291
+ permuted_inds = np.hstack((permuted_inds, np.random.permutation(len(all_speaker_ids))[:seq_len]))
292
+ target_count -= seq_len
293
+
294
+ logging.info(f"Total {all_speaker_id_counts} speakers in the source dataset.")
295
+ logging.info(f"Initialized speaker permutations for {num_sess} sessions with {num_speakers} speakers each.")
296
+ return permuted_inds.reshape(num_sess, num_speakers)
297
+
298
+ def _init_chunk_count(self):
299
+ """
300
+ Initialize the chunk count for multi-processing to prevent over-flow of job counts.
301
+ The multi-processing pipeline can freeze if there are more than approximately 10,000 jobs
302
+ in the pipeline at the same time.
303
+ """
304
+ return int(np.ceil(self._params.data_simulator.session_config.num_sessions / self.multiprocessing_chunksize))
305
+
306
+ def _check_args(self):
307
+ """
308
+ Checks YAML arguments to ensure they are within valid ranges.
309
+ """
310
+ if self._params.data_simulator.session_config.num_speakers < 1:
311
+ raise Exception("At least one speaker is required for making audio sessions (num_speakers < 1)")
312
+ if (
313
+ self._params.data_simulator.session_params.turn_prob < 0
314
+ or self._params.data_simulator.session_params.turn_prob > 1
315
+ ):
316
+ raise Exception("Turn probability is outside of [0,1]")
317
+ if (
318
+ self._params.data_simulator.session_params.turn_prob < 0
319
+ or self._params.data_simulator.session_params.turn_prob > 1
320
+ ):
321
+ raise Exception("Turn probability is outside of [0,1]")
322
+ elif (
323
+ self._params.data_simulator.session_params.turn_prob < self._turn_prob_min
324
+ and self._params.data_simulator.speaker_enforcement.enforce_num_speakers == True
325
+ ):
326
+ logging.warning(
327
+ "Turn probability is less than {self._turn_prob_min} while enforce_num_speakers=True, which may result in excessive session lengths. Forcing turn_prob to 0.5."
328
+ )
329
+ self._params.data_simulator.session_params.turn_prob = self._turn_prob_min
330
+ if self._params.data_simulator.session_params.max_audio_read_sec < 2.5:
331
+ raise Exception("Max audio read time must be greater than 2.5 seconds")
332
+
333
+ if self._params.data_simulator.session_params.sentence_length_params[0] <= 0:
334
+ raise Exception(
335
+ "k (number of success until the exp. ends) in Sentence length parameter value must be a positive number"
336
+ )
337
+
338
+ if not (0 < self._params.data_simulator.session_params.sentence_length_params[1] <= 1):
339
+ raise Exception("p (success probability) value in sentence length parameter must be in range (0,1]")
340
+
341
+ if (
342
+ self._params.data_simulator.session_params.mean_overlap < 0
343
+ or self._params.data_simulator.session_params.mean_overlap > 1
344
+ ):
345
+ raise Exception("Mean overlap is outside of [0,1]")
346
+ if (
347
+ self._params.data_simulator.session_params.mean_silence < 0
348
+ or self._params.data_simulator.session_params.mean_silence > 1
349
+ ):
350
+ raise Exception("Mean silence is outside of [0,1]")
351
+ if self._params.data_simulator.session_params.mean_silence_var < 0:
352
+ raise Exception("Mean silence variance is not below 0")
353
+ if (
354
+ self._params.data_simulator.session_params.mean_silence > 0
355
+ and self._params.data_simulator.session_params.mean_silence_var
356
+ >= self._params.data_simulator.session_params.mean_silence
357
+ * (1 - self._params.data_simulator.session_params.mean_silence)
358
+ ):
359
+ raise Exception("Mean silence variance should be lower than mean_silence * (1-mean_silence)")
360
+ if self._params.data_simulator.session_params.per_silence_var < 0:
361
+ raise Exception("Per silence variance is below 0")
362
+
363
+ if self._params.data_simulator.session_params.mean_overlap_var < 0:
364
+ raise Exception("Mean overlap variance is not larger than 0")
365
+ if (
366
+ self._params.data_simulator.session_params.mean_overlap > 0
367
+ and self._params.data_simulator.session_params.mean_overlap_var
368
+ >= self._params.data_simulator.session_params.mean_overlap
369
+ * (1 - self._params.data_simulator.session_params.mean_overlap)
370
+ ):
371
+ raise Exception("Mean overlap variance should be lower than mean_overlap * (1-mean_overlap)")
372
+ if self._params.data_simulator.session_params.per_overlap_var < 0:
373
+ raise Exception("Per overlap variance is not larger than 0")
374
+
375
+ if (
376
+ self._params.data_simulator.session_params.min_dominance < 0
377
+ or self._params.data_simulator.session_params.min_dominance > 1
378
+ ):
379
+ raise Exception("Minimum dominance is outside of [0,1]")
380
+ if (
381
+ self._params.data_simulator.speaker_enforcement.enforce_time[0] < 0
382
+ or self._params.data_simulator.speaker_enforcement.enforce_time[0] > 1
383
+ ):
384
+ raise Exception("Speaker enforcement start is outside of [0,1]")
385
+ if (
386
+ self._params.data_simulator.speaker_enforcement.enforce_time[1] < 0
387
+ or self._params.data_simulator.speaker_enforcement.enforce_time[1] > 1
388
+ ):
389
+ raise Exception("Speaker enforcement end is outside of [0,1]")
390
+
391
+ if (
392
+ self._params.data_simulator.session_params.min_dominance
393
+ * self._params.data_simulator.session_config.num_speakers
394
+ > 1
395
+ ):
396
+ raise Exception("Number of speakers times minimum dominance is greater than 1")
397
+
398
+ if (
399
+ self._params.data_simulator.session_params.window_type not in ['hamming', 'hann', 'cosine']
400
+ and self._params.data_simulator.session_params.window_type is not None
401
+ ):
402
+ raise Exception("Incorrect window type provided")
403
+
404
+ if len(self._manifest) == 0:
405
+ raise Exception("Manifest file is empty. Check that the source path is correct.")
406
+
407
+ def clean_up(self):
408
+ """
409
+ Clear the system memory. Cache data for audio files and alignments are removed.
410
+ """
411
+ self._sentence = None
412
+ self._words = []
413
+ self._alignments = []
414
+ self._audio_read_buffer_dict = {}
415
+ torch.cuda.empty_cache()
416
+
417
+ def _get_speaker_dominance(self) -> List[float]:
418
+ """
419
+ Get the dominance value for each speaker, accounting for the dominance variance and
420
+ the minimum per-speaker dominance.
421
+
422
+ Returns:
423
+ dominance (list): Per-speaker dominance
424
+ """
425
+ dominance_mean = 1.0 / self._params.data_simulator.session_config.num_speakers
426
+ dominance = np.random.normal(
427
+ loc=dominance_mean,
428
+ scale=self._params.data_simulator.session_params.dominance_var,
429
+ size=self._params.data_simulator.session_config.num_speakers,
430
+ )
431
+ dominance = np.clip(dominance, a_min=0, a_max=np.inf)
432
+ # normalize while maintaining minimum dominance
433
+ total = np.sum(dominance)
434
+ if total == 0:
435
+ for i in range(len(dominance)):
436
+ dominance[i] += self._params.data_simulator.session_params.min_dominance
437
+ # scale accounting for min_dominance which has to be added after
438
+ dominance = (dominance / total) * (
439
+ 1
440
+ - self._params.data_simulator.session_params.min_dominance
441
+ * self._params.data_simulator.session_config.num_speakers
442
+ )
443
+ for i in range(len(dominance)):
444
+ dominance[i] += self._params.data_simulator.session_params.min_dominance
445
+ if (
446
+ i > 0
447
+ ): # dominance values are cumulative to make it easy to select the speaker using a random value in [0,1]
448
+ dominance[i] = dominance[i] + dominance[i - 1]
449
+ return dominance
450
+
451
+ def _increase_speaker_dominance(
452
+ self, base_speaker_dominance: List[float], factor: int
453
+ ) -> Tuple[List[float], bool]:
454
+ """
455
+ Increase speaker dominance for unrepresented speakers (used only in enforce mode).
456
+ Increases the dominance for these speakers by the input factor (and then re-normalizes the probabilities to 1).
457
+
458
+ Args:
459
+ base_speaker_dominance (list): Dominance values for each speaker.
460
+ factor (int): Factor to increase dominance of unrepresented speakers by.
461
+ Returns:
462
+ dominance (list): Per-speaker dominance
463
+ enforce (bool): Whether to keep enforce mode turned on
464
+ """
465
+ increase_percent = []
466
+ for i in range(self._params.data_simulator.session_config.num_speakers):
467
+ if self._furthest_sample[i] == 0:
468
+ increase_percent.append(i)
469
+ # ramp up enforce counter until speaker is sampled, then reset once all speakers have spoken
470
+ if len(increase_percent) > 0:
471
+ # extract original per-speaker probabilities
472
+ dominance = np.copy(base_speaker_dominance)
473
+ for i in range(len(dominance) - 1, 0, -1):
474
+ dominance[i] = dominance[i] - dominance[i - 1]
475
+ # increase specified speakers by the desired factor
476
+ for i in increase_percent:
477
+ dominance[i] = dominance[i] * factor
478
+ # renormalize
479
+ dominance = dominance / np.sum(dominance)
480
+ for i in range(1, len(dominance)):
481
+ dominance[i] = dominance[i] + dominance[i - 1]
482
+ enforce = True
483
+ else: # no unrepresented speakers, so enforce mode can be turned off
484
+ dominance = base_speaker_dominance
485
+ enforce = False
486
+ return dominance, enforce
487
+
488
+ def _set_speaker_volume(self):
489
+ """
490
+ Set the volume for each speaker (either equal volume or variable speaker volume).
491
+ """
492
+ if self._params.data_simulator.session_params.normalization_type == 'equal':
493
+ self._volume = np.ones(self._params.data_simulator.session_config.num_speakers)
494
+ elif self._params.data_simulator.session_params.normalization_type == 'variable':
495
+ self._volume = np.random.normal(
496
+ loc=1.0,
497
+ scale=self._params.data_simulator.session_params.normalization_var,
498
+ size=self._params.data_simulator.session_config.num_speakers,
499
+ )
500
+ self._volume = np.clip(
501
+ np.array(self._volume),
502
+ a_min=self._params.data_simulator.session_params.min_volume,
503
+ a_max=self._params.data_simulator.session_params.max_volume,
504
+ ).tolist()
505
+
506
+ def _get_next_speaker(self, prev_speaker: int, dominance: List[float]) -> int:
507
+ """
508
+ Get the next speaker (accounting for turn probability and dominance distribution).
509
+
510
+ Args:
511
+ prev_speaker (int): Previous speaker turn.
512
+ dominance (list): Dominance values for each speaker.
513
+ Returns:
514
+ prev_speaker/speaker_turn (int): Speaker turn
515
+ """
516
+ if self._params.data_simulator.session_config.num_speakers == 1:
517
+ prev_speaker = 0 if prev_speaker is None else prev_speaker
518
+ return prev_speaker
519
+ else:
520
+ if (
521
+ np.random.uniform(0, 1) > self._params.data_simulator.session_params.turn_prob
522
+ and prev_speaker is not None
523
+ ):
524
+ return prev_speaker
525
+ else:
526
+ speaker_turn = prev_speaker
527
+ while speaker_turn == prev_speaker: # ensure another speaker goes next
528
+ rand = np.random.uniform(0, 1)
529
+ speaker_turn = 0
530
+ while rand > dominance[speaker_turn]:
531
+ speaker_turn += 1
532
+ return speaker_turn
533
+
534
+ def _get_window(self, window_amount: int, start: bool = False):
535
+ """
536
+ Get window curve to alleviate abrupt change of time-series signal when segmenting audio samples.
537
+
538
+ Args:
539
+ window_amount (int): Window length (in terms of number of samples).
540
+ start (bool): If true, return the first half of the window.
541
+
542
+ Returns:
543
+ window (tensor): Half window (either first half or second half)
544
+ """
545
+ if self._params.data_simulator.session_params.window_type == 'hamming':
546
+ window = hamming(window_amount * 2)
547
+ elif self._params.data_simulator.session_params.window_type == 'hann':
548
+ window = hann(window_amount * 2)
549
+ elif self._params.data_simulator.session_params.window_type == 'cosine':
550
+ window = cosine(window_amount * 2)
551
+ else:
552
+ raise Exception("Incorrect window type provided")
553
+
554
+ window = torch.from_numpy(window).to(self._device)
555
+
556
+ # return the first half or second half of the window
557
+ if start:
558
+ return window[:window_amount]
559
+ else:
560
+ return window[window_amount:]
561
+
562
+ def _get_start_buffer_and_window(self, first_alignment: int) -> Tuple[int, int]:
563
+ """
564
+ Get the start cutoff and window length for smoothing the start of the sentence.
565
+
566
+ Args:
567
+ first_alignment (int): Start of the first word (in terms of number of samples).
568
+ Returns:
569
+ start_cutoff (int): Amount into the audio clip to start
570
+ window_amount (int): Window length
571
+ """
572
+ window_amount = int(self._params.data_simulator.session_params.window_size * self._params.data_simulator.sr)
573
+ start_buffer = int(self._params.data_simulator.session_params.start_buffer * self._params.data_simulator.sr)
574
+
575
+ if first_alignment < start_buffer:
576
+ window_amount = 0
577
+ start_cutoff = 0
578
+ elif first_alignment < start_buffer + window_amount:
579
+ window_amount = first_alignment - start_buffer
580
+ start_cutoff = 0
581
+ else:
582
+ start_cutoff = first_alignment - start_buffer - window_amount
583
+
584
+ return start_cutoff, window_amount
585
+
586
+ def _get_end_buffer_and_window(
587
+ self, current_sample_cursor: int, remaining_dur_samples: int, remaining_len_audio_file: int
588
+ ) -> Tuple[int, int]:
589
+ """
590
+ Get the end buffer and window length for smoothing the end of the sentence.
591
+
592
+ Args:
593
+ current_sample_cursor (int): Current location in the target file (in terms of number of samples).
594
+ remaining_dur_samples (int): Remaining duration in the target file (in terms of number of samples).
595
+ remaining_len_audio_file (int): Length remaining in audio file (in terms of number of samples).
596
+ Returns:
597
+ release_buffer (int): Amount after the end of the last alignment to include
598
+ window_amount (int): Window length
599
+ """
600
+ window_amount = int(self._params.data_simulator.session_params.window_size * self._params.data_simulator.sr)
601
+ release_buffer = int(
602
+ self._params.data_simulator.session_params.release_buffer * self._params.data_simulator.sr
603
+ )
604
+
605
+ if current_sample_cursor + release_buffer > remaining_dur_samples:
606
+ release_buffer = remaining_dur_samples - current_sample_cursor
607
+ window_amount = 0
608
+ elif current_sample_cursor + window_amount + release_buffer > remaining_dur_samples:
609
+ window_amount = remaining_dur_samples - current_sample_cursor - release_buffer
610
+
611
+ if remaining_len_audio_file < release_buffer:
612
+ release_buffer = remaining_len_audio_file
613
+ window_amount = 0
614
+ elif remaining_len_audio_file < release_buffer + window_amount:
615
+ window_amount = remaining_len_audio_file - release_buffer
616
+
617
+ return release_buffer, window_amount
618
+
619
+ def _check_missing_speakers(self, num_missing: int = 0):
620
+ """
621
+ Check if any speakers were not included in the clip and display a warning.
622
+
623
+ Args:
624
+ num_missing (int): Number of missing speakers.
625
+ """
626
+ for k in range(len(self._furthest_sample)):
627
+ if self._furthest_sample[k] == 0:
628
+ num_missing += 1
629
+ if num_missing != 0:
630
+ warnings.warn(
631
+ f"{self._params.data_simulator.session_config.num_speakers - num_missing}"
632
+ f"speakers were included in the clip instead of the requested amount of "
633
+ f"{self._params.data_simulator.session_config.num_speakers}"
634
+ )
635
+
636
+ def _add_file(
637
+ self,
638
+ audio_manifest: dict,
639
+ audio_file,
640
+ sentence_word_count: int,
641
+ max_word_count_in_sentence: int,
642
+ max_samples_in_sentence: int,
643
+ random_offset: bool = False,
644
+ ) -> Tuple[int, torch.Tensor]:
645
+ """
646
+ Add audio file to current sentence (up to the desired number of words).
647
+ Uses the alignments to segment the audio file.
648
+ NOTE: 0 index is always silence in `audio_manifest['words']`, so we choose `offset_idx=1` as the first word
649
+
650
+ Args:
651
+ audio_manifest (dict): Line from manifest file for current audio file
652
+ audio_file (tensor): Current loaded audio file
653
+ sentence_word_count (int): Running count for number of words in sentence
654
+ max_word_count_in_sentence (int): Maximum count for number of words in sentence
655
+ max_samples_in_sentence (int): Maximum length for sentence in terms of samples
656
+
657
+ Returns:
658
+ sentence_word_count+current_word_count (int): Running word count
659
+ len(self._sentence) (tensor): Current length of the audio file
660
+ """
661
+ # In general, random offset is not needed since random silence index has already been chosen
662
+ if random_offset:
663
+ offset_idx = np.random.randint(low=1, high=len(audio_manifest['words']))
664
+ else:
665
+ offset_idx = 1
666
+
667
+ first_alignment = int(audio_manifest['alignments'][offset_idx - 1] * self._params.data_simulator.sr)
668
+ start_cutoff, start_window_amount = self._get_start_buffer_and_window(first_alignment)
669
+ if not self._params.data_simulator.session_params.start_window: # cut off the start of the sentence
670
+ start_window_amount = 0
671
+
672
+ # Ensure the desired number of words are added and the length of the output session isn't exceeded
673
+ sentence_samples = len(self._sentence)
674
+
675
+ remaining_dur_samples = max_samples_in_sentence - sentence_samples
676
+ remaining_duration = max_word_count_in_sentence - sentence_word_count
677
+ prev_dur_samples, dur_samples, curr_dur_samples = 0, 0, 0
678
+ current_word_count = 0
679
+ word_idx = offset_idx
680
+ silence_count = 1
681
+ while (
682
+ current_word_count < remaining_duration
683
+ and dur_samples < remaining_dur_samples
684
+ and word_idx < len(audio_manifest['words'])
685
+ ):
686
+ dur_samples = int(audio_manifest['alignments'][word_idx] * self._params.data_simulator.sr) - start_cutoff
687
+
688
+ # check the length of the generated sentence in terms of sample count (int).
689
+ if curr_dur_samples + dur_samples > remaining_dur_samples:
690
+ # if the upcoming loop will exceed the remaining sample count, break out of the loop.
691
+ break
692
+
693
+ word = audio_manifest['words'][word_idx]
694
+
695
+ if silence_count > 0 and word == "":
696
+ break
697
+
698
+ self._words.append(word)
699
+ self._alignments.append(
700
+ float(sentence_samples * 1.0 / self._params.data_simulator.sr)
701
+ - float(start_cutoff * 1.0 / self._params.data_simulator.sr)
702
+ + audio_manifest['alignments'][word_idx]
703
+ )
704
+
705
+ if word == "":
706
+ word_idx += 1
707
+ silence_count += 1
708
+ continue
709
+ elif self._text == "":
710
+ self._text += word
711
+ else:
712
+ self._text += " " + word
713
+
714
+ word_idx += 1
715
+ current_word_count += 1
716
+ prev_dur_samples = dur_samples
717
+ curr_dur_samples += dur_samples
718
+
719
+ # add audio clip up to the final alignment
720
+ if self._params.data_simulator.session_params.window_type is not None: # cut off the start of the sentence
721
+ if start_window_amount > 0: # include window
722
+ window = self._get_window(start_window_amount, start=True)
723
+ self._sentence = self._sentence.to(self._device)
724
+ self._sentence = torch.cat(
725
+ (
726
+ self._sentence,
727
+ torch.multiply(audio_file[start_cutoff : start_cutoff + start_window_amount], window),
728
+ ),
729
+ 0,
730
+ )
731
+ self._sentence = torch.cat(
732
+ (
733
+ self._sentence,
734
+ audio_file[start_cutoff + start_window_amount : start_cutoff + prev_dur_samples],
735
+ ),
736
+ 0,
737
+ ).to(self._device)
738
+
739
+ else:
740
+ self._sentence = torch.cat(
741
+ (self._sentence, audio_file[start_cutoff : start_cutoff + prev_dur_samples]), 0
742
+ ).to(self._device)
743
+
744
+ # windowing at the end of the sentence
745
+ if (
746
+ word_idx < len(audio_manifest['words'])
747
+ ) and self._params.data_simulator.session_params.window_type is not None:
748
+ release_buffer, end_window_amount = self._get_end_buffer_and_window(
749
+ prev_dur_samples,
750
+ remaining_dur_samples,
751
+ len(audio_file[start_cutoff + prev_dur_samples :]),
752
+ )
753
+ self._sentence = torch.cat(
754
+ (
755
+ self._sentence,
756
+ audio_file[start_cutoff + prev_dur_samples : start_cutoff + prev_dur_samples + release_buffer],
757
+ ),
758
+ 0,
759
+ ).to(self._device)
760
+
761
+ if end_window_amount > 0: # include window
762
+ window = self._get_window(end_window_amount, start=False)
763
+ sig_start = start_cutoff + prev_dur_samples + release_buffer
764
+ sig_end = start_cutoff + prev_dur_samples + release_buffer + end_window_amount
765
+ windowed_audio_file = torch.multiply(audio_file[sig_start:sig_end], window)
766
+ self._sentence = torch.cat((self._sentence, windowed_audio_file), 0).to(self._device)
767
+
768
+ del audio_file
769
+ return sentence_word_count + current_word_count, len(self._sentence)
770
+
771
+ def _build_sentence(
772
+ self,
773
+ speaker_turn: int,
774
+ speaker_ids: List[str],
775
+ speaker_wav_align_map: Dict[str, list],
776
+ max_samples_in_sentence: int,
777
+ ):
778
+ """
779
+ Build a new sentence by attaching utterance samples together until the sentence has reached a desired length.
780
+ While generating the sentence, alignment information is used to segment the audio.
781
+
782
+ Args:
783
+ speaker_turn (int): Current speaker turn.
784
+ speaker_ids (list): LibriSpeech speaker IDs for each speaker in the current session.
785
+ speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments.
786
+ max_samples_in_sentence (int): Maximum length for sentence in terms of samples
787
+ """
788
+ # select speaker length
789
+ sl = (
790
+ np.random.negative_binomial(
791
+ self._params.data_simulator.session_params.sentence_length_params[0],
792
+ self._params.data_simulator.session_params.sentence_length_params[1],
793
+ )
794
+ + 1
795
+ )
796
+
797
+ # initialize sentence, text, words, alignments
798
+ self._sentence = torch.zeros(0, dtype=torch.float64, device=self._device)
799
+ self._text = ""
800
+ self._words, self._alignments = [], []
801
+ sentence_word_count, sentence_samples = 0, 0
802
+
803
+ # build sentence
804
+ while sentence_word_count < sl and sentence_samples < max_samples_in_sentence:
805
+ audio_manifest = load_speaker_sample(
806
+ speaker_wav_align_map=speaker_wav_align_map,
807
+ speaker_ids=speaker_ids,
808
+ speaker_turn=speaker_turn,
809
+ min_alignment_count=self._min_alignment_count,
810
+ )
811
+
812
+ offset_index = get_random_offset_index(
813
+ audio_manifest=audio_manifest,
814
+ audio_read_buffer_dict=self._audio_read_buffer_dict,
815
+ offset_min=0,
816
+ max_audio_read_sec=self._max_audio_read_sec,
817
+ min_alignment_count=self._min_alignment_count,
818
+ )
819
+
820
+ audio_file, sr, audio_manifest = read_audio_from_buffer(
821
+ audio_manifest=audio_manifest,
822
+ buffer_dict=self._audio_read_buffer_dict,
823
+ offset_index=offset_index,
824
+ device=self._device,
825
+ max_audio_read_sec=self._max_audio_read_sec,
826
+ min_alignment_count=self._min_alignment_count,
827
+ read_subset=True,
828
+ )
829
+
830
+ # Step 6-2: Add optional perturbations to the specific audio segment (i.e. to `self._sentnece`)
831
+ if self._params.data_simulator.segment_augmentor.add_seg_aug:
832
+ audio_file = perturb_audio(audio_file, sr, self.segment_augmentor, device=self._device)
833
+
834
+ sentence_word_count, sentence_samples = self._add_file(
835
+ audio_manifest, audio_file, sentence_word_count, sl, max_samples_in_sentence
836
+ )
837
+
838
+ # per-speaker normalization (accounting for active speaker time)
839
+ if self._params.data_simulator.session_params.normalize and torch.max(torch.abs(self._sentence)) > 0:
840
+ splits = get_split_points_in_alignments(
841
+ words=self._words,
842
+ alignments=self._alignments,
843
+ split_buffer=self._params.data_simulator.session_params.split_buffer,
844
+ sr=self._params.data_simulator.sr,
845
+ sentence_audio_len=len(self._sentence),
846
+ )
847
+ self._sentence = per_speaker_normalize(
848
+ sentence_audio=self._sentence,
849
+ splits=splits,
850
+ speaker_turn=speaker_turn,
851
+ volume=self._volume,
852
+ device=self._device,
853
+ )
854
+
855
+ def _add_silence_or_overlap(
856
+ self,
857
+ speaker_turn: int,
858
+ prev_speaker: int,
859
+ start: int,
860
+ length: int,
861
+ session_len_samples: int,
862
+ prev_len_samples: int,
863
+ enforce: bool,
864
+ ) -> int:
865
+ """
866
+ Returns new overlapped (or shifted) start position after inserting overlap or silence.
867
+
868
+ Args:
869
+ speaker_turn (int): The integer index of the current speaker turn.
870
+ prev_speaker (int): The integer index of the previous speaker turn.
871
+ start (int): Current start of the audio file being inserted.
872
+ length (int): Length of the audio file being inserted.
873
+ session_len_samples (int): Maximum length of the session in terms of number of samples
874
+ prev_len_samples (int): Length of previous sentence (in terms of number of samples)
875
+ enforce (bool): Whether speaker enforcement mode is being used
876
+ Returns:
877
+ new_start (int): New starting position in the session accounting for overlap or silence
878
+ """
879
+ running_len_samples = start + length
880
+ # `length` is the length of the current sentence to be added, so not included in self.sampler.running_speech_len_samples
881
+ non_silence_len_samples = self.sampler.running_speech_len_samples + length
882
+
883
+ # compare silence and overlap ratios
884
+ add_overlap = self.sampler.silence_vs_overlap_selector(running_len_samples, non_silence_len_samples)
885
+
886
+ # choose overlap if this speaker is not the same as the previous speaker and add_overlap is True.
887
+ if prev_speaker != speaker_turn and prev_speaker is not None and add_overlap:
888
+ desired_overlap_amount = self.sampler.sample_from_overlap_model(non_silence_len_samples)
889
+ new_start = start - desired_overlap_amount
890
+
891
+ # avoid overlap at start of clip
892
+ if new_start < 0:
893
+ desired_overlap_amount -= 0 - new_start
894
+ self._missing_overlap += 0 - new_start
895
+ new_start = 0
896
+
897
+ # if same speaker ends up overlapping from any previous clip, pad with silence instead
898
+ if new_start < self._furthest_sample[speaker_turn]:
899
+ desired_overlap_amount -= self._furthest_sample[speaker_turn] - new_start
900
+ self._missing_overlap += self._furthest_sample[speaker_turn] - new_start
901
+ new_start = self._furthest_sample[speaker_turn]
902
+
903
+ prev_start = start - prev_len_samples
904
+ prev_end = start
905
+ new_end = new_start + length
906
+
907
+ # check overlap amount to calculate the actual amount of generated overlaps
908
+ overlap_amount = 0
909
+ if is_overlap([prev_start, prev_end], [new_start, new_end]):
910
+ overlap_range = get_overlap_range([prev_start, prev_end], [new_start, new_end])
911
+ overlap_amount = max(overlap_range[1] - overlap_range[0], 0)
912
+
913
+ if overlap_amount < desired_overlap_amount:
914
+ self._missing_overlap += desired_overlap_amount - overlap_amount
915
+ self.sampler.running_overlap_len_samples += overlap_amount
916
+
917
+ # if we are not adding overlap, add silence
918
+ else:
919
+ silence_amount = self.sampler.sample_from_silence_model(running_len_samples)
920
+ if start + length + silence_amount > session_len_samples and not enforce:
921
+ new_start = max(session_len_samples - length, start)
922
+ else:
923
+ new_start = start + silence_amount
924
+ return new_start
925
+
926
+ def _get_session_meta_data(self, array: np.ndarray, snr: float) -> dict:
927
+ """
928
+ Get meta data for the current session.
929
+
930
+ Args:
931
+ array (np.ndarray): audio array
932
+ snr (float): signal-to-noise ratio
933
+
934
+ Returns:
935
+ dict: meta data
936
+ """
937
+ meta_data = {
938
+ "duration": array.shape[0] / self._params.data_simulator.sr,
939
+ "silence_mean": self.sampler.sess_silence_mean,
940
+ "overlap_mean": self.sampler.sess_overlap_mean,
941
+ "bg_snr": snr,
942
+ "speaker_ids": self._speaker_ids,
943
+ "speaker_volumes": list(self._volume),
944
+ }
945
+ return meta_data
946
+
947
+ def _get_session_silence_from_rttm(self, rttm_list: List[str], running_len_samples: int):
948
+ """
949
+ Calculate the total speech and silence duration in the current session using RTTM file.
950
+
951
+ Args:
952
+ rttm_list (list):
953
+ List of RTTM timestamps
954
+ running_len_samples (int):
955
+ Total number of samples generated so far in the current session
956
+
957
+ Returns:
958
+ sess_speech_len_rttm (int):
959
+ The total number of speech samples in the current session
960
+ sess_silence_len_rttm (int):
961
+ The total number of silence samples in the current session
962
+ """
963
+ all_sample_list = []
964
+ for x_raw in rttm_list:
965
+ x = [token for token in x_raw.split()]
966
+ all_sample_list.append([float(x[0]), float(x[1])])
967
+
968
+ self._merged_speech_intervals = merge_float_intervals(all_sample_list)
969
+ total_speech_in_secs = sum([x[1] - x[0] for x in self._merged_speech_intervals])
970
+ total_silence_in_secs = running_len_samples / self._params.data_simulator.sr - total_speech_in_secs
971
+ sess_speech_len = int(total_speech_in_secs * self._params.data_simulator.sr)
972
+ sess_silence_len = int(total_silence_in_secs * self._params.data_simulator.sr)
973
+ return sess_speech_len, sess_silence_len
974
+
975
+ def _add_sentence_to_array(
976
+ self, start: int, length: int, array: torch.Tensor, is_speech: torch.Tensor
977
+ ) -> Tuple[torch.Tensor, torch.Tensor, int]:
978
+ """
979
+ Add a sentence to the session array containing time-series signal.
980
+
981
+ Args:
982
+ start (int): Starting position in the session
983
+ length (int): Length of the sentence
984
+ array (torch.Tensor): Session array
985
+ is_speech (torch.Tensor): Session array containing speech/non-speech labels
986
+
987
+ Returns:
988
+ array (torch.Tensor): Session array in torch.Tensor format
989
+ is_speech (torch.Tensor): Session array containing speech/non-speech labels in torch.Tensor format
990
+ """
991
+ end = start + length
992
+ if end > len(array): # only occurs in enforce mode
993
+ array = torch.nn.functional.pad(array, (0, end - len(array)))
994
+ is_speech = torch.nn.functional.pad(is_speech, (0, end - len(is_speech)))
995
+ array[start:end] += self._sentence
996
+ is_speech[start:end] = 1
997
+ return array, is_speech, end
998
+
999
+ def _generate_session(
1000
+ self,
1001
+ idx: int,
1002
+ basepath: str,
1003
+ filename: str,
1004
+ speaker_ids: List[str],
1005
+ speaker_wav_align_map: Dict[str, list],
1006
+ noise_samples: list,
1007
+ device: torch.device,
1008
+ enforce_counter: int = 2,
1009
+ ):
1010
+ """
1011
+ _generate_session function without RIR simulation.
1012
+ Generate a multispeaker audio session and corresponding label files.
1013
+
1014
+ Args:
1015
+ idx (int): Index for current session (out of total number of sessions).
1016
+ basepath (str): Path to output directory.
1017
+ filename (str): Filename for output files.
1018
+ speaker_ids (list): List of speaker IDs that will be used in this session.
1019
+ speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments.
1020
+ noise_samples (list): List of randomly sampled noise source files that will be used for generating this session.
1021
+ device (torch.device): Device to use for generating this session.
1022
+ enforce_counter (int): In enforcement mode, dominance is increased by a factor of enforce_counter for unrepresented speakers
1023
+ """
1024
+ random_seed = self._params.data_simulator.random_seed
1025
+ np.random.seed(random_seed + idx)
1026
+
1027
+ self._device = device
1028
+ speaker_dominance = self._get_speaker_dominance() # randomly determine speaker dominance
1029
+ base_speaker_dominance = np.copy(speaker_dominance)
1030
+ self._set_speaker_volume()
1031
+
1032
+ running_len_samples, prev_len_samples = 0, 0
1033
+ prev_speaker = None
1034
+ self.annotator.init_annotation_lists()
1035
+ self._noise_samples = noise_samples
1036
+ self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)]
1037
+ self._missing_silence = 0
1038
+
1039
+ # hold enforce until all speakers have spoken
1040
+ enforce_time = np.random.uniform(
1041
+ self._params.data_simulator.speaker_enforcement.enforce_time[0],
1042
+ self._params.data_simulator.speaker_enforcement.enforce_time[1],
1043
+ )
1044
+ enforce = self._params.data_simulator.speaker_enforcement.enforce_num_speakers
1045
+
1046
+ session_len_samples = int(
1047
+ (self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr)
1048
+ )
1049
+ array = torch.zeros(session_len_samples).to(self._device)
1050
+ is_speech = torch.zeros(session_len_samples).to(self._device)
1051
+
1052
+ self.sampler.get_session_silence_mean()
1053
+ self.sampler.get_session_overlap_mean()
1054
+
1055
+ while running_len_samples < session_len_samples or enforce:
1056
+ # Step 1: Prepare parameters for sentence generation
1057
+ # Enforce speakers depending on running length
1058
+ if running_len_samples > enforce_time * session_len_samples and enforce:
1059
+ speaker_dominance, enforce = self._increase_speaker_dominance(base_speaker_dominance, enforce_counter)
1060
+ if enforce:
1061
+ enforce_counter += 1
1062
+
1063
+ # Step 2: Select a speaker
1064
+ speaker_turn = self._get_next_speaker(prev_speaker, speaker_dominance)
1065
+
1066
+ # Calculate parameters for building a sentence (only add if remaining length > specific time)
1067
+ max_samples_in_sentence = session_len_samples - running_len_samples
1068
+ if enforce:
1069
+ max_samples_in_sentence = float('inf')
1070
+ elif (
1071
+ max_samples_in_sentence
1072
+ < self._params.data_simulator.session_params.end_buffer * self._params.data_simulator.sr
1073
+ ):
1074
+ break
1075
+
1076
+ # Step 3: Generate a sentence
1077
+ self._build_sentence(speaker_turn, speaker_ids, speaker_wav_align_map, max_samples_in_sentence)
1078
+ length = len(self._sentence)
1079
+
1080
+ # Step 4: Generate a timestamp for either silence or overlap
1081
+ start = self._add_silence_or_overlap(
1082
+ speaker_turn=speaker_turn,
1083
+ prev_speaker=prev_speaker,
1084
+ start=running_len_samples,
1085
+ length=length,
1086
+ session_len_samples=session_len_samples,
1087
+ prev_len_samples=prev_len_samples,
1088
+ enforce=enforce,
1089
+ )
1090
+ # step 5: add sentence to array
1091
+ array, is_speech, end = self._add_sentence_to_array(
1092
+ start=start,
1093
+ length=length,
1094
+ array=array,
1095
+ is_speech=is_speech,
1096
+ )
1097
+
1098
+ # Step 6: Build entries for output files
1099
+ new_rttm_entries = self.annotator.create_new_rttm_entry(
1100
+ words=self._words,
1101
+ alignments=self._alignments,
1102
+ start=start / self._params.data_simulator.sr,
1103
+ end=end / self._params.data_simulator.sr,
1104
+ speaker_id=speaker_ids[speaker_turn],
1105
+ )
1106
+
1107
+ self.annotator.annote_lists['rttm'].extend(new_rttm_entries)
1108
+
1109
+ new_json_entry = self.annotator.create_new_json_entry(
1110
+ text=self._text,
1111
+ wav_filename=os.path.join(basepath, filename + '.wav'),
1112
+ start=start / self._params.data_simulator.sr,
1113
+ length=length / self._params.data_simulator.sr,
1114
+ speaker_id=speaker_ids[speaker_turn],
1115
+ rttm_filepath=os.path.join(basepath, filename + '.rttm'),
1116
+ ctm_filepath=os.path.join(basepath, filename + '.ctm'),
1117
+ )
1118
+ self.annotator.annote_lists['json'].append(new_json_entry)
1119
+
1120
+ new_ctm_entries = self.annotator.create_new_ctm_entry(
1121
+ words=self._words,
1122
+ alignments=self._alignments,
1123
+ session_name=filename,
1124
+ speaker_id=speaker_ids[speaker_turn],
1125
+ start=float(start / self._params.data_simulator.sr),
1126
+ )
1127
+
1128
+ self.annotator.annote_lists['ctm'].extend(new_ctm_entries)
1129
+
1130
+ running_len_samples = np.maximum(running_len_samples, end)
1131
+ (
1132
+ self.sampler.running_speech_len_samples,
1133
+ self.sampler.running_silence_len_samples,
1134
+ ) = self._get_session_silence_from_rttm(
1135
+ rttm_list=self.annotator.annote_lists['rttm'], running_len_samples=running_len_samples
1136
+ )
1137
+
1138
+ self._furthest_sample[speaker_turn] = running_len_samples
1139
+ prev_speaker = speaker_turn
1140
+ prev_len_samples = length
1141
+
1142
+ # Step 7-1: Add optional perturbations to the whole session, such as white noise.
1143
+ if self._params.data_simulator.session_augmentor.add_sess_aug:
1144
+ # NOTE: This perturbation is not reflected in the session SNR in meta dictionary.
1145
+ array = perturb_audio(array, self._params.data_simulator.sr, self.session_augmentor, device=array.device)
1146
+
1147
+ # Step 7-2: Additive background noise from noise manifest files
1148
+ if self._params.data_simulator.background_noise.add_bg:
1149
+ if len(self._noise_samples) > 0:
1150
+ avg_power_array = torch.mean(array[is_speech == 1] ** 2)
1151
+ bg, snr = get_background_noise(
1152
+ len_array=len(array),
1153
+ power_array=avg_power_array,
1154
+ noise_samples=self._noise_samples,
1155
+ audio_read_buffer_dict=self._audio_read_buffer_dict,
1156
+ snr_min=self._params.data_simulator.background_noise.snr_min,
1157
+ snr_max=self._params.data_simulator.background_noise.snr_max,
1158
+ background_noise_snr=self._params.data_simulator.background_noise.snr,
1159
+ seed=(random_seed + idx),
1160
+ device=self._device,
1161
+ )
1162
+ array += bg
1163
+ else:
1164
+ raise ValueError('No background noise samples found in self._noise_samples.')
1165
+ else:
1166
+ snr = "N/A"
1167
+
1168
+ # Step 7: Normalize and write to disk
1169
+ array = normalize_audio(array)
1170
+
1171
+ if torch.is_tensor(array):
1172
+ array = array.cpu().numpy()
1173
+ sf.write(os.path.join(basepath, filename + '.wav'), array, self._params.data_simulator.sr)
1174
+
1175
+ self.annotator.write_annotation_files(
1176
+ basepath=basepath,
1177
+ filename=filename,
1178
+ meta_data=self._get_session_meta_data(array=array, snr=snr),
1179
+ )
1180
+
1181
+ # Step 8: Clean up memory
1182
+ del array
1183
+ self.clean_up()
1184
+ return basepath, filename
1185
+
1186
+ def generate_sessions(self, random_seed: int = None):
1187
+ """
1188
+ Generate several multispeaker audio sessions and corresponding list files.
1189
+
1190
+ Args:
1191
+ random_seed (int): random seed for reproducibility
1192
+ """
1193
+ logging.info(f"Generating Diarization Sessions")
1194
+ if random_seed is None:
1195
+ random_seed = self._params.data_simulator.random_seed
1196
+ np.random.seed(random_seed)
1197
+
1198
+ output_dir = self._params.data_simulator.outputs.output_dir
1199
+
1200
+ basepath = get_cleaned_base_path(
1201
+ output_dir, overwrite_output=self._params.data_simulator.outputs.overwrite_output
1202
+ )
1203
+ OmegaConf.save(self._params, os.path.join(output_dir, "params.yaml"))
1204
+
1205
+ tp = concurrent.futures.ProcessPoolExecutor(max_workers=self.num_workers)
1206
+ futures = []
1207
+
1208
+ num_sessions = self._params.data_simulator.session_config.num_sessions
1209
+ source_noise_manifest = read_noise_manifest(
1210
+ add_bg=self._params.data_simulator.background_noise.add_bg,
1211
+ background_manifest=self._params.data_simulator.background_noise.background_manifest,
1212
+ )
1213
+ queue = []
1214
+
1215
+ # add radomly sampled arguments to a list(queue) for multiprocessing
1216
+ for sess_idx in range(num_sessions):
1217
+ filename = self._params.data_simulator.outputs.output_filename + f"_{sess_idx}"
1218
+ speaker_ids = get_speaker_ids(
1219
+ sess_idx=sess_idx,
1220
+ speaker_samples=self._speaker_samples,
1221
+ permutated_speaker_inds=self._permutated_speaker_inds,
1222
+ )
1223
+ speaker_wav_align_map = get_speaker_samples(speaker_ids=speaker_ids, speaker_samples=self._speaker_samples)
1224
+ noise_samples = self.sampler.sample_noise_manifest(noise_manifest=source_noise_manifest)
1225
+
1226
+ if torch.cuda.is_available():
1227
+ device = torch.device(f"cuda:{sess_idx % torch.cuda.device_count()}")
1228
+ else:
1229
+ device = self._device
1230
+ queue.append((sess_idx, basepath, filename, speaker_ids, speaker_wav_align_map, noise_samples, device))
1231
+
1232
+ # for multiprocessing speed, we avoid loading potentially huge manifest list and speaker sample files into each process.
1233
+ if self.num_workers > 1:
1234
+ self._manifest = None
1235
+ self._speaker_samples = None
1236
+
1237
+ # Chunk the sessions into smaller chunks for very large number of sessions (10K+ sessions)
1238
+ for chunk_idx in range(self.chunk_count):
1239
+ futures = []
1240
+ stt_idx, end_idx = (
1241
+ chunk_idx * self.multiprocessing_chunksize,
1242
+ min((chunk_idx + 1) * self.multiprocessing_chunksize, num_sessions),
1243
+ )
1244
+ for sess_idx in range(stt_idx, end_idx):
1245
+ self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)]
1246
+ self._audio_read_buffer_dict = {}
1247
+ if self.num_workers > 1:
1248
+ futures.append(tp.submit(self._generate_session, *queue[sess_idx]))
1249
+ else:
1250
+ futures.append(queue[sess_idx])
1251
+
1252
+ if self.num_workers > 1:
1253
+ generator = concurrent.futures.as_completed(futures)
1254
+ else:
1255
+ generator = futures
1256
+
1257
+ for future in tqdm(
1258
+ generator,
1259
+ desc=f"[{chunk_idx+1}/{self.chunk_count}] Waiting jobs from {stt_idx+1: 2} to {end_idx: 2}",
1260
+ unit="jobs",
1261
+ total=len(futures),
1262
+ ):
1263
+ if self.num_workers > 1:
1264
+ basepath, filename = future.result()
1265
+ else:
1266
+ self._noise_samples = self.sampler.sample_noise_manifest(
1267
+ noise_manifest=source_noise_manifest,
1268
+ )
1269
+ basepath, filename = self._generate_session(*future)
1270
+
1271
+ self.annotator.add_to_filename_lists(basepath=basepath, filename=filename)
1272
+
1273
+ # throw warning if number of speakers is less than requested
1274
+ self._check_missing_speakers()
1275
+
1276
+ tp.shutdown()
1277
+ self.annotator.write_filelist_files(basepath=basepath)
1278
+ logging.info(f"Data simulation has been completed, results saved at: {basepath}")
1279
+
1280
+
1281
+ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator):
1282
+ """
1283
+ RIR Augmented Multispeaker Audio Session Simulator - simulates multispeaker audio sessions using single-speaker
1284
+ audio files and corresponding word alignments, as well as simulated RIRs for augmentation.
1285
+
1286
+ Args:
1287
+ cfg: OmegaConf configuration loaded from yaml file.
1288
+
1289
+ Parameters (in addition to the base MultiSpeakerSimulator parameters):
1290
+ rir_generation:
1291
+ use_rir (bool): Whether to generate synthetic RIR
1292
+ toolkit (str): Which toolkit to use ("pyroomacoustics", "gpuRIR")
1293
+ room_config:
1294
+ room_sz (list): Size of the shoebox room environment (1d array for specific, 2d array for random range to be
1295
+ sampled from)
1296
+ pos_src (list): Positions of the speakers in the simulated room environment (2d array for specific, 3d array
1297
+ for random ranges to be sampled from)
1298
+ noise_src_pos (list): Position in room for the ambient background noise source
1299
+ mic_config:
1300
+ num_channels (int): Number of output audio channels
1301
+ pos_rcv (list): Microphone positions in the simulated room environment (1d/2d array for specific, 2d/3d array
1302
+ for range assuming num_channels is 1/2+)
1303
+ orV_rcv (list or null): Microphone orientations (needed for non-omnidirectional microphones)
1304
+ mic_pattern (str): Microphone type ("omni" - omnidirectional) - currently only omnidirectional microphones are
1305
+ supported for pyroomacoustics
1306
+ absorbtion_params: (Note that only `T60` is used for pyroomacoustics simulations)
1307
+ abs_weights (list): Absorption coefficient ratios for each surface
1308
+ T60 (float): Room reverberation time (`T60` is the time it takes for the RIR to decay by 60DB)
1309
+ att_diff (float): Starting attenuation (if this is different than att_max, the diffuse reverberation model is
1310
+ used by gpuRIR)
1311
+ att_max (float): End attenuation when using the diffuse reverberation model (gpuRIR)
1312
+ """
1313
+
1314
+ def __init__(self, cfg):
1315
+ super().__init__(cfg)
1316
+ self._check_args_rir()
1317
+
1318
+ def _check_args_rir(self):
1319
+ """
1320
+ Checks RIR YAML arguments to ensure they are within valid ranges
1321
+ """
1322
+
1323
+ if not (self._params.data_simulator.rir_generation.toolkit in ['pyroomacoustics', 'gpuRIR']):
1324
+ raise Exception("Toolkit must be pyroomacoustics or gpuRIR")
1325
+ if self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics' and not PRA:
1326
+ raise ImportError("pyroomacoustics should be installed to run this simulator with RIR augmentation")
1327
+
1328
+ if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR' and not GPURIR:
1329
+ raise ImportError("gpuRIR should be installed to run this simulator with RIR augmentation")
1330
+
1331
+ if len(self._params.data_simulator.rir_generation.room_config.room_sz) != 3:
1332
+ raise Exception("Incorrect room dimensions provided")
1333
+ if self._params.data_simulator.rir_generation.mic_config.num_channels == 0:
1334
+ raise Exception("Number of channels should be greater or equal to 1")
1335
+ if len(self._params.data_simulator.rir_generation.room_config.pos_src) < 2:
1336
+ raise Exception("Less than 2 provided source positions")
1337
+ for sublist in self._params.data_simulator.rir_generation.room_config.pos_src:
1338
+ if len(sublist) != 3:
1339
+ raise Exception("Three coordinates must be provided for sources positions")
1340
+ if len(self._params.data_simulator.rir_generation.mic_config.pos_rcv) == 0:
1341
+ raise Exception("No provided mic positions")
1342
+ for sublist in self._params.data_simulator.rir_generation.room_config.pos_src:
1343
+ if len(sublist) != 3:
1344
+ raise Exception("Three coordinates must be provided for mic positions")
1345
+
1346
+ if self._params.data_simulator.session_config.num_speakers != len(
1347
+ self._params.data_simulator.rir_generation.room_config.pos_src
1348
+ ):
1349
+ raise Exception("Number of speakers is not equal to the number of provided source positions")
1350
+ if self._params.data_simulator.rir_generation.mic_config.num_channels != len(
1351
+ self._params.data_simulator.rir_generation.mic_config.pos_rcv
1352
+ ):
1353
+ raise Exception("Number of channels is not equal to the number of provided microphone positions")
1354
+
1355
+ if (
1356
+ not self._params.data_simulator.rir_generation.mic_config.orV_rcv
1357
+ and self._params.data_simulator.rir_generation.mic_config.mic_pattern != 'omni'
1358
+ ):
1359
+ raise Exception("Microphone orientations must be provided if mic_pattern != omni")
1360
+ if self._params.data_simulator.rir_generation.mic_config.orV_rcv is not None:
1361
+ if len(self._params.data_simulator.rir_generation.mic_config.orV_rcv) != len(
1362
+ self._params.data_simulator.rir_generation.mic_config.pos_rcv
1363
+ ):
1364
+ raise Exception("A different number of microphone orientations and microphone positions were provided")
1365
+ for sublist in self._params.data_simulator.rir_generation.mic_config.orV_rcv:
1366
+ if len(sublist) != 3:
1367
+ raise Exception("Three coordinates must be provided for orientations")
1368
+
1369
+ def _generate_rir_gpuRIR(self):
1370
+ """
1371
+ Create simulated RIR using the gpuRIR library
1372
+
1373
+ Returns:
1374
+ RIR (tensor): Generated RIR
1375
+ RIR_pad (int): Length of padding added when convolving the RIR with an audio file
1376
+ """
1377
+ room_sz_tmp = np.array(self._params.data_simulator.rir_generation.room_config.room_sz)
1378
+ if room_sz_tmp.ndim == 2: # randomize
1379
+ room_sz = np.zeros(room_sz_tmp.shape[0])
1380
+ for i in range(room_sz_tmp.shape[0]):
1381
+ room_sz[i] = np.random.uniform(room_sz_tmp[i, 0], room_sz_tmp[i, 1])
1382
+ else:
1383
+ room_sz = room_sz_tmp
1384
+
1385
+ pos_src_tmp = np.array(self._params.data_simulator.rir_generation.room_config.pos_src)
1386
+ if pos_src_tmp.ndim == 3: # randomize
1387
+ pos_src = np.zeros((pos_src_tmp.shape[0], pos_src_tmp.shape[1]))
1388
+ for i in range(pos_src_tmp.shape[0]):
1389
+ for j in range(pos_src_tmp.shape[1]):
1390
+ pos_src[i] = np.random.uniform(pos_src_tmp[i, j, 0], pos_src_tmp[i, j, 1])
1391
+ else:
1392
+ pos_src = pos_src_tmp
1393
+
1394
+ if self._params.data_simulator.background_noise.add_bg:
1395
+ pos_src = np.vstack((pos_src, self._params.data_simulator.rir_generation.room_config.noise_src_pos))
1396
+
1397
+ mic_pos_tmp = np.array(self._params.data_simulator.rir_generation.mic_config.pos_rcv)
1398
+ if mic_pos_tmp.ndim == 3: # randomize
1399
+ mic_pos = np.zeros((mic_pos_tmp.shape[0], mic_pos_tmp.shape[1]))
1400
+ for i in range(mic_pos_tmp.shape[0]):
1401
+ for j in range(mic_pos_tmp.shape[1]):
1402
+ mic_pos[i] = np.random.uniform(mic_pos_tmp[i, j, 0], mic_pos_tmp[i, j, 1])
1403
+ else:
1404
+ mic_pos = mic_pos_tmp
1405
+
1406
+ orV_rcv = self._params.data_simulator.rir_generation.mic_config.orV_rcv
1407
+ if orV_rcv: # not needed for omni mics
1408
+ orV_rcv = np.array(orV_rcv)
1409
+ mic_pattern = self._params.data_simulator.rir_generation.mic_config.mic_pattern
1410
+ abs_weights = self._params.data_simulator.rir_generation.absorbtion_params.abs_weights
1411
+ T60 = self._params.data_simulator.rir_generation.absorbtion_params.T60
1412
+ att_diff = self._params.data_simulator.rir_generation.absorbtion_params.att_diff
1413
+ att_max = self._params.data_simulator.rir_generation.absorbtion_params.att_max
1414
+ sr = self._params.data_simulator.sr
1415
+
1416
+ beta = beta_SabineEstimation(room_sz, T60, abs_weights=abs_weights) # Reflection coefficients
1417
+ Tdiff = att2t_SabineEstimator(att_diff, T60) # Time to start the diffuse reverberation model [s]
1418
+ Tmax = att2t_SabineEstimator(att_max, T60) # Time to stop the simulation [s]
1419
+ nb_img = t2n(Tdiff, room_sz) # Number of image sources in each dimension
1420
+ RIR = simulateRIR(
1421
+ room_sz, beta, pos_src, mic_pos, nb_img, Tmax, sr, Tdiff=Tdiff, orV_rcv=orV_rcv, mic_pattern=mic_pattern
1422
+ )
1423
+ RIR_pad = RIR.shape[2] - 1
1424
+ return RIR, RIR_pad
1425
+
1426
+ def _generate_rir_pyroomacoustics(self) -> Tuple[torch.Tensor, int]:
1427
+ """
1428
+ Create simulated RIR using the pyroomacoustics library
1429
+
1430
+ Returns:
1431
+ RIR (tensor): Generated RIR
1432
+ RIR_pad (int): Length of padding added when convolving the RIR with an audio file
1433
+ """
1434
+
1435
+ rt60 = self._params.data_simulator.rir_generation.absorbtion_params.T60 # The desired reverberation time
1436
+ sr = self._params.data_simulator.sr
1437
+
1438
+ room_sz_tmp = np.array(self._params.data_simulator.rir_generation.room_config.room_sz)
1439
+ if room_sz_tmp.ndim == 2: # randomize
1440
+ room_sz = np.zeros(room_sz_tmp.shape[0])
1441
+ for i in range(room_sz_tmp.shape[0]):
1442
+ room_sz[i] = np.random.uniform(room_sz_tmp[i, 0], room_sz_tmp[i, 1])
1443
+ else:
1444
+ room_sz = room_sz_tmp
1445
+
1446
+ pos_src_tmp = np.array(self._params.data_simulator.rir_generation.room_config.pos_src)
1447
+ if pos_src_tmp.ndim == 3: # randomize
1448
+ pos_src = np.zeros((pos_src_tmp.shape[0], pos_src_tmp.shape[1]))
1449
+ for i in range(pos_src_tmp.shape[0]):
1450
+ for j in range(pos_src_tmp.shape[1]):
1451
+ pos_src[i] = np.random.uniform(pos_src_tmp[i, j, 0], pos_src_tmp[i, j, 1])
1452
+ else:
1453
+ pos_src = pos_src_tmp
1454
+
1455
+ # We invert Sabine's formula to obtain the parameters for the ISM simulator
1456
+ e_absorption, max_order = pra.inverse_sabine(rt60, room_sz)
1457
+ room = pra.ShoeBox(room_sz, fs=sr, materials=pra.Material(e_absorption), max_order=max_order)
1458
+
1459
+ if self._params.data_simulator.background_noise.add_bg:
1460
+ pos_src = np.vstack((pos_src, self._params.data_simulator.rir_generation.room_config.noise_src_pos))
1461
+ for pos in pos_src:
1462
+ room.add_source(pos)
1463
+
1464
+ # currently only supports omnidirectional microphones
1465
+ mic_pattern = self._params.data_simulator.rir_generation.mic_config.mic_pattern
1466
+ if self._params.data_simulator.rir_generation.mic_config.mic_pattern == 'omni':
1467
+ mic_pattern = DirectivityPattern.OMNI
1468
+ dir_vec = DirectionVector(azimuth=0, colatitude=90, degrees=True)
1469
+ dir_obj = CardioidFamily(
1470
+ orientation=dir_vec,
1471
+ pattern_enum=mic_pattern,
1472
+ )
1473
+
1474
+ mic_pos_tmp = np.array(self._params.data_simulator.rir_generation.mic_config.pos_rcv)
1475
+ if mic_pos_tmp.ndim == 3: # randomize
1476
+ mic_pos = np.zeros((mic_pos_tmp.shape[0], mic_pos_tmp.shape[1]))
1477
+ for i in range(mic_pos_tmp.shape[0]):
1478
+ for j in range(mic_pos_tmp.shape[1]):
1479
+ mic_pos[i] = np.random.uniform(mic_pos_tmp[i, j, 0], mic_pos_tmp[i, j, 1])
1480
+ else:
1481
+ mic_pos = mic_pos_tmp
1482
+
1483
+ room.add_microphone_array(mic_pos.T, directivity=dir_obj)
1484
+
1485
+ room.compute_rir()
1486
+ rir_pad = 0
1487
+ for channel in room.rir:
1488
+ for pos in channel:
1489
+ if pos.shape[0] - 1 > rir_pad:
1490
+ rir_pad = pos.shape[0] - 1
1491
+ return room.rir, rir_pad
1492
+
1493
+ def _convolve_rir(self, input, speaker_turn: int, RIR: torch.Tensor) -> Tuple[list, int]:
1494
+ """
1495
+ Augment one sentence (or background noise segment) using a synthetic RIR.
1496
+
1497
+ Args:
1498
+ input (torch.tensor): Input audio.
1499
+ speaker_turn (int): Current speaker turn.
1500
+ RIR (torch.tensor): Room Impulse Response.
1501
+ Returns:
1502
+ output_sound (list): List of tensors containing augmented audio
1503
+ length (int): Length of output audio channels (or of the longest if they have different lengths)
1504
+ """
1505
+ output_sound = []
1506
+ length = 0
1507
+ for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels):
1508
+ if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR':
1509
+ out_channel = convolve(input, RIR[speaker_turn, channel, : len(input)]).tolist()
1510
+ elif self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics':
1511
+ out_channel = convolve(input, RIR[channel][speaker_turn][: len(input)]).tolist()
1512
+ if len(out_channel) > length:
1513
+ length = len(out_channel)
1514
+ output_sound.append(torch.tensor(out_channel))
1515
+ return output_sound, length
1516
+
1517
+ def _generate_session(
1518
+ self,
1519
+ idx: int,
1520
+ basepath: str,
1521
+ filename: str,
1522
+ speaker_ids: list,
1523
+ speaker_wav_align_map: dict,
1524
+ noise_samples: list,
1525
+ device: torch.device,
1526
+ enforce_counter: int = 2,
1527
+ ):
1528
+ """
1529
+ Generate a multispeaker audio session and corresponding label files.
1530
+
1531
+ Args:
1532
+ idx (int): Index for current session (out of total number of sessions).
1533
+ basepath (str): Path to output directory.
1534
+ filename (str): Filename for output files.
1535
+ speaker_ids (list): List of speaker IDs that will be used in this session.
1536
+ speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments.
1537
+ noise_samples (list): List of randomly sampled noise source files that will be used for generating this session.
1538
+ device (torch.device): Device to use for generating this session.
1539
+ enforce_counter (int): In enforcement mode, dominance is increased by a factor of enforce_counter for unrepresented speakers
1540
+ """
1541
+ random_seed = self._params.data_simulator.random_seed
1542
+ np.random.seed(random_seed + idx)
1543
+
1544
+ self._device = device
1545
+ speaker_dominance = self._get_speaker_dominance() # randomly determine speaker dominance
1546
+ base_speaker_dominance = np.copy(speaker_dominance)
1547
+ self._set_speaker_volume()
1548
+
1549
+ running_len_samples, prev_len_samples = 0, 0 # starting point for each sentence
1550
+ prev_speaker = None
1551
+ self.annotator.init_annotation_lists()
1552
+ self._noise_samples = noise_samples
1553
+ self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)]
1554
+
1555
+ # Room Impulse Response Generation (performed once per batch of sessions)
1556
+ if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR':
1557
+ RIR, RIR_pad = self._generate_rir_gpuRIR()
1558
+ elif self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics':
1559
+ RIR, RIR_pad = self._generate_rir_pyroomacoustics()
1560
+ else:
1561
+ raise Exception("Toolkit must be pyroomacoustics or gpuRIR")
1562
+
1563
+ # hold enforce until all speakers have spoken
1564
+ enforce_time = np.random.uniform(
1565
+ self._params.data_simulator.speaker_enforcement.enforce_time[0],
1566
+ self._params.data_simulator.speaker_enforcement.enforce_time[1],
1567
+ )
1568
+ enforce = self._params.data_simulator.speaker_enforcement.enforce_num_speakers
1569
+
1570
+ session_len_samples = int(
1571
+ (self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr)
1572
+ )
1573
+ array = torch.zeros((session_len_samples, self._params.data_simulator.rir_generation.mic_config.num_channels))
1574
+ is_speech = torch.zeros(session_len_samples)
1575
+
1576
+ while running_len_samples < session_len_samples or enforce:
1577
+ # Step 1: Prepare parameters for sentence generation
1578
+ # Enforce speakers depending on running length
1579
+ if running_len_samples > enforce_time * session_len_samples and enforce:
1580
+ speaker_dominance, enforce = self._increase_speaker_dominance(base_speaker_dominance, enforce_counter)
1581
+ if enforce:
1582
+ enforce_counter += 1
1583
+
1584
+ # Step 2: Select a speaker
1585
+ speaker_turn = self._get_next_speaker(prev_speaker, speaker_dominance)
1586
+
1587
+ # Calculate parameters for building a sentence (only add if remaining length > specific time)
1588
+ max_samples_in_sentence = (
1589
+ session_len_samples - running_len_samples - RIR_pad
1590
+ ) # sentence will be RIR_len - 1 longer than the audio was pre-augmentation
1591
+ if enforce:
1592
+ max_samples_in_sentence = float('inf')
1593
+ elif (
1594
+ max_samples_in_sentence
1595
+ < self._params.data_simulator.session_params.end_buffer * self._params.data_simulator.sr
1596
+ ):
1597
+ break
1598
+
1599
+ # Step 3: Generate a sentence
1600
+ self._build_sentence(speaker_turn, speaker_ids, speaker_wav_align_map, max_samples_in_sentence)
1601
+ augmented_sentence, length = self._convolve_rir(self._sentence, speaker_turn, RIR)
1602
+
1603
+ # Step 4: Generate a time-stamp for either silence or overlap
1604
+ start = self._add_silence_or_overlap(
1605
+ speaker_turn=speaker_turn,
1606
+ prev_speaker=prev_speaker,
1607
+ start=running_len_samples,
1608
+ length=length,
1609
+ session_len_samples=session_len_samples,
1610
+ prev_len_samples=prev_len_samples,
1611
+ enforce=enforce,
1612
+ )
1613
+ # step 5: add sentence to array
1614
+ end = start + length
1615
+ if end > len(array):
1616
+ array = torch.nn.functional.pad(array, (0, 0, 0, end - len(array)))
1617
+ is_speech = torch.nn.functional.pad(is_speech, (0, end - len(is_speech)))
1618
+ is_speech[start:end] = 1
1619
+
1620
+ for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels):
1621
+ len_ch = len(augmented_sentence[channel]) # accounts for how channels are slightly different lengths
1622
+ array[start : start + len_ch, channel] += augmented_sentence[channel]
1623
+
1624
+ # Step 6: Build entries for output files
1625
+ new_rttm_entries = self.annotator.create_new_rttm_entry(
1626
+ self._words,
1627
+ self._alignments,
1628
+ start / self._params.data_simulator.sr,
1629
+ end / self._params.data_simulator.sr,
1630
+ speaker_ids[speaker_turn],
1631
+ )
1632
+
1633
+ self.annotator.annote_lists['rttm'].extend(new_rttm_entries)
1634
+
1635
+ new_json_entry = self.annotator.create_new_json_entry(
1636
+ self._text,
1637
+ os.path.join(basepath, filename + '.wav'),
1638
+ start / self._params.data_simulator.sr,
1639
+ length / self._params.data_simulator.sr,
1640
+ speaker_ids[speaker_turn],
1641
+ os.path.join(basepath, filename + '.rttm'),
1642
+ os.path.join(basepath, filename + '.ctm'),
1643
+ )
1644
+ self.annotator.annote_lists['json'].append(new_json_entry)
1645
+
1646
+ new_ctm_entries = self.annotator.create_new_ctm_entry(
1647
+ filename, speaker_ids[speaker_turn], start / self._params.data_simulator.sr
1648
+ )
1649
+ self.annotator.annote_lists['ctm'].extend(new_ctm_entries)
1650
+
1651
+ running_len_samples = np.maximum(running_len_samples, end)
1652
+ self._furthest_sample[speaker_turn] = running_len_samples
1653
+ prev_speaker = speaker_turn
1654
+ prev_len_samples = length
1655
+
1656
+ # Step 7-1: Add optional perturbations to the whole session, such as white noise.
1657
+ if self._params.data_simulator.session_augmentor.add_sess_aug:
1658
+ # NOTE: This perturbation is not reflected in the session SNR in meta dictionary.
1659
+ array = perturb_audio(array, self._params.data_simulator.sr, self.session_augmentor)
1660
+
1661
+ # Step 7-2: Additive background noise from noise manifest files
1662
+ if self._params.data_simulator.background_noise.add_bg:
1663
+ if len(self._noise_samples) > 0:
1664
+ avg_power_array = torch.mean(array[is_speech == 1] ** 2)
1665
+ bg, snr = get_background_noise(
1666
+ len_array=len(array),
1667
+ power_array=avg_power_array,
1668
+ noise_samples=self._noise_samples,
1669
+ audio_read_buffer_dict=self._audio_read_buffer_dict,
1670
+ snr_min=self._params.data_simulator.background_noise.snr_min,
1671
+ snr_max=self._params.data_simulator.background_noise.snr_max,
1672
+ background_noise_snr=self._params.data_simulator.background_noise.snr,
1673
+ seed=(random_seed + idx),
1674
+ device=self._device,
1675
+ )
1676
+ array += bg
1677
+ length = array.shape[0]
1678
+ bg, snr = self._get_background(length, avg_power_array)
1679
+ augmented_bg, _ = self._convolve_rir(bg, -1, RIR)
1680
+ for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels):
1681
+ array[:, channel] += augmented_bg[channel][:length]
1682
+ else:
1683
+ snr = "N/A"
1684
+
1685
+ # Step 7: Normalize and write to disk
1686
+ array = normalize_audio(array)
1687
+
1688
+ if torch.is_tensor(array):
1689
+ array = array.cpu().numpy()
1690
+ sf.write(os.path.join(basepath, filename + '.wav'), array, self._params.data_simulator.sr)
1691
+
1692
+ self.annotator.write_annotation_files(
1693
+ basepath=basepath,
1694
+ filename=filename,
1695
+ meta_data=self._get_session_meta_data(array=array, snr=snr),
1696
+ )
1697
+
1698
+ del array
1699
+ self.clean_up()
1700
+ return basepath, filename
nemo/collections/asr/data/feature_to_label.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Dict, List, Optional
15
+
16
+ import torch
17
+
18
+ from nemo.collections.asr.parts.preprocessing.feature_loader import ExternalFeatureLoader
19
+ from nemo.collections.common.parts.preprocessing import collections
20
+ from nemo.core.classes import Dataset
21
+ from nemo.core.neural_types import AcousticEncodedRepresentation, LabelsType, LengthsType, NeuralType
22
+ from nemo.utils import logging
23
+
24
+
25
+ def _feature_collate_fn(batch):
26
+ """collate batch of feat sig, feat len, labels, labels len, assuming all features have the same shape.
27
+ Args:
28
+ batch (FloatTensor, LongTensor, LongTensor, LongTensor): A tuple of tuples of feature, feature lengths,
29
+ encoded labels, and encoded labels length.
30
+ """
31
+ packed_batch = list(zip(*batch))
32
+ if len(packed_batch) == 5:
33
+ _, feat_lengths, _, labels_lengths, sample_ids = packed_batch
34
+ elif len(packed_batch) == 4:
35
+ sample_ids = None
36
+ _, feat_lengths, _, labels_lengths = packed_batch
37
+ else:
38
+ raise ValueError("Expects 4 or 5 tensors in the batch!")
39
+
40
+ features, labels = [], []
41
+ for b in batch:
42
+ feat_i, labels_i = b[0], b[2]
43
+ features.append(feat_i)
44
+ labels.append(labels_i)
45
+
46
+ features = torch.stack(features)
47
+ feat_lengths = torch.stack(feat_lengths)
48
+
49
+ labels = torch.stack(labels)
50
+ labels_lengths = torch.stack(labels_lengths)
51
+
52
+ if sample_ids is None:
53
+ return features, feat_lengths, labels, labels_lengths
54
+ else:
55
+ sample_ids = torch.tensor(sample_ids, dtype=torch.int32)
56
+ return features, feat_lengths, labels, labels_lengths, sample_ids
57
+
58
+
59
+ def _audio_feature_collate_fn(batch, feat_pad_val, label_pad_id):
60
+ """collate batch of audio feature, audio len, labels, labels len
61
+ Args:
62
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
63
+ LongTensor): A tuple of tuples of feature, feature lengths,
64
+ labels, and label lengths. This collate func assumes the
65
+ features are torch tensors of Log-Melspectrogram (i.e. [N_MEL, T]).
66
+ """
67
+ packed_batch = list(zip(*batch))
68
+ if len(packed_batch) == 5:
69
+ _, feat_lengths, _, labels_lengths, sample_ids = packed_batch
70
+ elif len(packed_batch) == 4:
71
+ sample_ids = None
72
+ _, feat_lengths, _, labels_lengths = packed_batch
73
+ else:
74
+ raise ValueError("Expects 4 or 5 tensors in the batch!")
75
+ max_feat_len = 0
76
+ has_feat = feat_lengths[0] is not None
77
+ if has_feat:
78
+ max_feat_len = max(feat_lengths).item()
79
+ max_labels_len = max(labels_lengths).item()
80
+
81
+ features, labels = [], []
82
+ for b in batch:
83
+ feat_i, feat_i_len, label_i, label_i_len = b[0], b[1], b[2], b[3]
84
+
85
+ if has_feat:
86
+ feat_i_len = feat_i_len.item()
87
+ if feat_i_len < max_feat_len:
88
+ pad = (0, max_feat_len - feat_i_len)
89
+ feat_i = torch.nn.functional.pad(feat_i, pad, value=feat_pad_val)
90
+ features.append(feat_i)
91
+
92
+ label_i_len = label_i_len.item()
93
+ if label_i_len < max_labels_len:
94
+ pad = (0, max_labels_len - label_i_len)
95
+ label_i = torch.nn.functional.pad(label_i, pad, value=label_pad_id)
96
+ labels.append(label_i)
97
+
98
+ if has_feat:
99
+ features = torch.stack(features)
100
+ feature_lengths = torch.stack(feat_lengths)
101
+ else:
102
+ features, feat_lengths = None, None
103
+ labels = torch.stack(labels)
104
+ labels_lengths = torch.stack(labels_lengths)
105
+
106
+ if sample_ids is None:
107
+ return features, feature_lengths, labels, labels_lengths
108
+ else:
109
+ sample_ids = torch.tensor(sample_ids, dtype=torch.int32)
110
+ return features, feature_lengths, labels, labels_lengths, sample_ids
111
+
112
+
113
+ def _vad_feature_segment_collate_fn(batch, window_length_in_sec, shift_length_in_sec, frame_unit_in_sec):
114
+ """collate batch of audio features, features len, tokens, tokens len
115
+ Args:
116
+ batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,
117
+ LongTensor): A tuple of tuples of signal, signal lengths,
118
+ encoded tokens, and encoded tokens length. This collate func
119
+ assumes the signals are 1d torch tensors (i.e. mono audio).
120
+ batch size equals to 1.
121
+ """
122
+ slice_length = int(window_length_in_sec / frame_unit_in_sec)
123
+ audio_features, feat_lengths, _, tokens_lengths = zip(*batch)
124
+
125
+ slice_length = int(min(slice_length, max(feat_lengths)))
126
+ shift = int(shift_length_in_sec / frame_unit_in_sec)
127
+ has_audio = feat_lengths[0] is not None
128
+
129
+ f_dim = audio_features[0].shape[0]
130
+ audio_features, num_slices, tokens, feat_lengths = [], [], [], []
131
+ append_len_start = torch.div(slice_length, 2, rounding_mode='trunc')
132
+ append_len_end = slice_length - torch.div(slice_length, 2, rounding_mode='trunc')
133
+ for feat_i, feat_i_len, tokens_i, _ in batch:
134
+ start = torch.zeros(f_dim, append_len_start)
135
+ end = torch.zeros(f_dim, append_len_end)
136
+ feat_i = torch.cat((start, feat_i, end), dim=1)
137
+ feat_i_len += slice_length
138
+
139
+ if has_audio:
140
+ slices = max(1, torch.div(feat_i_len - slice_length, shift, rounding_mode='trunc'))
141
+
142
+ for slice_id in range(slices):
143
+ start_idx = slice_id * shift
144
+ end_idx = start_idx + slice_length
145
+ feat_slice = feat_i[:, start_idx:end_idx]
146
+ audio_features.append(feat_slice)
147
+
148
+ num_slices.append(slices)
149
+ tokens.extend([tokens_i] * slices)
150
+ feat_lengths.extend([slice_length] * slices)
151
+
152
+ if has_audio:
153
+ audio_features = torch.stack(audio_features)
154
+ feat_lengths = torch.tensor(feat_lengths)
155
+ else:
156
+ audio_features, feat_lengths = None, None
157
+
158
+ tokens = torch.stack(tokens)
159
+ tokens_lengths = torch.tensor(num_slices)
160
+ return audio_features, feat_lengths, tokens, tokens_lengths
161
+
162
+
163
+ class _FeatureSeqSpeakerLabelDataset(Dataset):
164
+ """
165
+ Dataset that loads tensors via a json file containing paths to feature files, sequences of labels.
166
+ Each new line is a different sample. Example below:
167
+ and their target labels. JSON files should be of the following format:
168
+ {"feature_filepath": "/path/to/feature_0.p", "seq_label": speakerA speakerB SpeakerA ....} \
169
+ ...
170
+ {"feature_filepath": "/path/to/feature_n.p", "seq_label": target_seq_label_n}
171
+ target_seq_label_n is the string of sequence of speaker label, separated by space.
172
+
173
+ Args:
174
+ manifest_filepath (str): Dataset parameter. Path to JSON containing data.
175
+ labels (Optional[list]): Dataset parameter. List of unique labels collected from all samples.
176
+ feature_loader : Dataset parameter. Feature loader to load (external) feature.
177
+ """
178
+
179
+ @property
180
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
181
+ """Returns definitions of module output ports.
182
+ """
183
+ # TODO output type for external features
184
+ output_types = {
185
+ 'external_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),
186
+ 'feat_length': NeuralType(tuple('B'), LengthsType()),
187
+ }
188
+
189
+ if self.is_speaker_emb:
190
+ output_types.update(
191
+ {
192
+ 'embs': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),
193
+ 'embs_length': NeuralType(tuple('B'), LengthsType()),
194
+ 'label': NeuralType(('B', 'T'), LabelsType()),
195
+ 'label_length': NeuralType(tuple('B'), LengthsType()),
196
+ }
197
+ )
198
+ else:
199
+ output_types.update(
200
+ {'label': NeuralType(('B', 'T'), LabelsType()), 'label_length': NeuralType(tuple('B'), LengthsType()),}
201
+ )
202
+
203
+ return output_types
204
+
205
+ def __init__(
206
+ self, *, manifest_filepath: str, labels: List[str], feature_loader, is_speaker_emb: bool = False,
207
+ ):
208
+ super().__init__()
209
+ self.collection = collections.ASRFeatureSequenceLabel(manifests_files=manifest_filepath.split(','),)
210
+
211
+ self.feature_loader = feature_loader
212
+ self.labels = labels if labels else self.collection.uniq_labels
213
+ self.is_speaker_emb = is_speaker_emb
214
+
215
+ self.label2id, self.id2label = {}, {}
216
+ for label_id, label in enumerate(self.labels):
217
+ self.label2id[label] = label_id
218
+ self.id2label[label_id] = label
219
+
220
+ for idx in range(len(self.labels[:5])):
221
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
222
+
223
+ def __len__(self):
224
+ return len(self.collection)
225
+
226
+ def __getitem__(self, index):
227
+ sample = self.collection[index]
228
+
229
+ features = self.feature_loader.process(sample.feature_file)
230
+ f, fl = features, torch.tensor(features.shape[0]).long()
231
+
232
+ t = torch.tensor(sample.seq_label).float()
233
+ tl = torch.tensor(len(sample.seq_label)).long()
234
+
235
+ return f, fl, t, tl
236
+
237
+
238
+ class FeatureToSeqSpeakerLabelDataset(_FeatureSeqSpeakerLabelDataset):
239
+ """
240
+ Dataset that loads tensors via a json file containing paths to feature
241
+ files and sequence of speakers. Each new line is a
242
+ different sample. Example below:
243
+ {"feature_filepath": "/path/to/feature_0.p", "seq_label": speakerA speakerB SpeakerA ....} \
244
+ ...
245
+ {"feature_filepath": "/path/to/feature_n.p", "seq_label": target_seq_label_n}
246
+ target_seq_label_n is the string of sequence of speaker label, separated by space.
247
+
248
+ Args:
249
+ manifest_filepath (str): Path to manifest json as described above. Canbe comma-separated paths.
250
+ labels (Optional[list]): String containing all the possible labels to map to
251
+ if None then automatically picks from ASRFeatureSequenceLabel collection.
252
+ feature_loader, Feature load to loader (external) feature.
253
+
254
+ """
255
+
256
+ def _collate_fn(self, batch):
257
+ return _feature_collate_fn(batch)
258
+
259
+
260
+ class FeatureToLabelDataset(Dataset):
261
+ """
262
+ Dataset that loads tensors via a json file containing paths to feature files and their labels.
263
+ Each new line is a different sample. Example below:
264
+ and their target labels. JSON files should be of the following format:
265
+ {"feature_filepath": "/path/to/audio_feature.pt", "label": "1"}
266
+ ...
267
+ {"feature_filepath": "/path/to/audio_feature.pt", "label": "0"}
268
+ Args:
269
+ manifest_filepath (str): Path to JSON containing data.
270
+ labels (Optional[list]): List of unique labels collected from all samples.
271
+ augmentor (Optional): feature augmentation
272
+ window_length_in_sec (float): Window length in seconds.
273
+ shift_length_in_sec (float): Shift length in seconds.
274
+ is_regression_task (bool): if True, the labels are treated as for a regression task.
275
+ cal_labels_occurrence (bool): if True, the labels occurrence will be calculated.
276
+ zero_spec_db_val (float): Value to replace non-speech signals in log-melspectrogram.
277
+ min_duration (float): Minimum duration of the audio file in seconds.
278
+ max_duration (float): Maximum duration of the audio file in seconds.
279
+ """
280
+
281
+ ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal
282
+ FRAME_UNIT_TIME_SECS = 0.01
283
+
284
+ @property
285
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
286
+ """Returns definitions of module output ports.
287
+ """
288
+ output_types = {
289
+ 'audio_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),
290
+ 'feat_length': NeuralType(tuple('B'), LengthsType()),
291
+ 'labels': NeuralType(('B'), LabelsType()),
292
+ 'labels_length': NeuralType(tuple('B'), LengthsType()),
293
+ }
294
+
295
+ return output_types
296
+
297
+ def __init__(
298
+ self,
299
+ *,
300
+ manifest_filepath: str,
301
+ labels: List[str] = None,
302
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
303
+ window_length_in_sec: float = 0.63,
304
+ shift_length_in_sec: float = 0.01,
305
+ is_regression_task: bool = False,
306
+ cal_labels_occurrence: Optional[bool] = False,
307
+ zero_spec_db_val: float = -16.635,
308
+ min_duration: Optional[float] = None,
309
+ max_duration: Optional[float] = None,
310
+ ):
311
+ super().__init__()
312
+ self.window_length_in_sec = window_length_in_sec
313
+ self.shift_length_in_sec = shift_length_in_sec
314
+ self.zero_spec_db_val = zero_spec_db_val
315
+
316
+ if isinstance(manifest_filepath, str):
317
+ manifest_filepath = manifest_filepath.split(',')
318
+
319
+ self.collection = collections.ASRFeatureLabel(
320
+ manifests_files=manifest_filepath,
321
+ is_regression_task=is_regression_task,
322
+ cal_labels_occurrence=cal_labels_occurrence,
323
+ min_duration=min_duration,
324
+ max_duration=max_duration,
325
+ )
326
+
327
+ self.feature_loader = ExternalFeatureLoader(augmentor=augmentor)
328
+ self.labels = labels if labels else self.collection.uniq_labels
329
+
330
+ self.is_regression_task = is_regression_task
331
+
332
+ if not is_regression_task:
333
+ self.labels = labels if labels else self.collection.uniq_labels
334
+ self.num_classes = len(self.labels) if self.labels is not None else 1
335
+ self.label2id, self.id2label = {}, {}
336
+ self.id2occurrence, self.labels_occurrence = {}, []
337
+
338
+ for label_id, label in enumerate(self.labels):
339
+ self.label2id[label] = label_id
340
+ self.id2label[label_id] = label
341
+ if cal_labels_occurrence:
342
+ self.id2occurrence[label_id] = self.collection.labels_occurrence[label]
343
+
344
+ if cal_labels_occurrence:
345
+ self.labels_occurrence = [self.id2occurrence[k] for k in sorted(self.id2occurrence)]
346
+
347
+ for idx in range(len(self.labels[:5])):
348
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
349
+ else:
350
+ self.labels = []
351
+ self.num_classes = 1
352
+
353
+ def __len__(self):
354
+ return len(self.collection)
355
+
356
+ def __getitem__(self, index):
357
+ sample = self.collection[index]
358
+
359
+ features = self.feature_loader.process(sample.feature_file)
360
+ f, fl = features, torch.tensor(features.shape[1]).long()
361
+
362
+ t = torch.tensor(self.label2id[sample.label])
363
+ tl = torch.tensor(1).long()
364
+
365
+ return f, fl, t, tl
366
+
367
+ def _collate_fn(self, batch):
368
+ return _audio_feature_collate_fn(batch, self.zero_spec_db_val, 0)
369
+
370
+ def _vad_segment_collate_fn(self, batch):
371
+ return _vad_feature_segment_collate_fn(
372
+ batch, self.window_length_in_sec, self.shift_length_in_sec, self.FRAME_UNIT_TIME_SECS
373
+ )
374
+
375
+
376
+ class FeatureToMultiLabelDataset(Dataset):
377
+ """
378
+ Dataset that loads tensors via a json file containing paths to feature files and their labels.
379
+ Each new line is a different sample. Example below:
380
+ and their target labels. JSON files should be of the following format:
381
+ {"feature_filepath": "/path/to/audio_feature.pt", "label": "1 1 0 0 1"}
382
+ ...
383
+ {"feature_filepath": "/path/to/audio_feature.pt", "label": "0 1 0 0"}
384
+ Args:
385
+ manifest_filepath (str): Path to JSON containing data.
386
+ labels (Optional[list]): List of unique labels collected from all samples.
387
+ augmentor (Optional): feature augmentation
388
+ delimiter (str): delimiter to split the labels.
389
+ is_regression_task (bool): if True, the labels are treated as for a regression task.
390
+ cal_labels_occurrence (bool): if True, the labels occurrence will be calculated.
391
+ zero_spec_db_val (float): Value to replace non-speech signals in log-melspectrogram.
392
+ min_duration (float): Minimum duration of the audio file in seconds.
393
+ max_duration (float): Maximum duration of the audio file in seconds.
394
+ """
395
+
396
+ ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal
397
+
398
+ @property
399
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
400
+ """Returns definitions of module output ports.
401
+ """
402
+ output_types = {
403
+ 'audio_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),
404
+ 'feat_length': NeuralType(tuple('B'), LengthsType()),
405
+ 'labels': NeuralType(('B', 'T'), LabelsType()),
406
+ 'labels_length': NeuralType(tuple('B'), LengthsType()),
407
+ }
408
+
409
+ return output_types
410
+
411
+ def __init__(
412
+ self,
413
+ *,
414
+ manifest_filepath: str,
415
+ labels: List[str] = None,
416
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
417
+ delimiter: Optional[str] = None,
418
+ is_regression_task: bool = False,
419
+ cal_labels_occurrence: Optional[bool] = False,
420
+ zero_spec_db_val: float = -16.635,
421
+ min_duration: Optional[float] = None,
422
+ max_duration: Optional[float] = None,
423
+ ):
424
+ super().__init__()
425
+ self.delimiter = delimiter
426
+ self.zero_spec_db_val = zero_spec_db_val
427
+
428
+ if isinstance(manifest_filepath, str):
429
+ manifest_filepath = manifest_filepath.split(',')
430
+
431
+ self.collection = collections.ASRFeatureLabel(
432
+ manifests_files=manifest_filepath,
433
+ is_regression_task=is_regression_task,
434
+ cal_labels_occurrence=cal_labels_occurrence,
435
+ delimiter=delimiter,
436
+ min_duration=min_duration,
437
+ max_duration=max_duration,
438
+ )
439
+
440
+ self.is_regression_task = is_regression_task
441
+ self.feature_loader = ExternalFeatureLoader(augmentor=augmentor)
442
+ self.labels = labels if labels else self.collection.uniq_labels
443
+
444
+ self.label2id, self.id2label = {}, {}
445
+ if not is_regression_task:
446
+ self.labels = labels if labels else self._get_label_set()
447
+ self.num_classes = len(self.labels) if self.labels is not None else 1
448
+ self.label2id, self.id2label = {}, {}
449
+ for label_id, label in enumerate(self.labels):
450
+ self.label2id[label] = label_id
451
+ self.id2label[label_id] = label
452
+ if cal_labels_occurrence:
453
+ self.id2occurrence[label_id] = self.collection.labels_occurrence[label]
454
+ self.labels_occurrence.append(self.id2occurrence[label_id])
455
+
456
+ for idx in range(len(self.labels[:5])):
457
+ logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx]))
458
+ else:
459
+ self.labels = []
460
+ self.num_classes = 1
461
+
462
+ def _get_label_set(self):
463
+ labels = []
464
+ for sample in self.collection:
465
+ label_str = sample.label
466
+ if label_str:
467
+ label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split()
468
+ labels.extend(label_str_list)
469
+ return sorted(set(labels))
470
+
471
+ def _label_str_to_tensor(self, label_str: str):
472
+ labels = label_str.split(self.delimiter) if self.delimiter else label_str.split()
473
+
474
+ if self.is_regression_task:
475
+ labels = [float(s) for s in labels]
476
+ labels = torch.tensor(labels).float()
477
+ else:
478
+ labels = [self.label2id[s] for s in labels]
479
+ labels = torch.tensor(labels).long()
480
+ return labels
481
+
482
+ def __len__(self):
483
+ return len(self.collection)
484
+
485
+ def __getitem__(self, index):
486
+ sample = self.collection[index]
487
+
488
+ features = self.feature_loader.process(sample.feature_file)
489
+ f, fl = features, torch.tensor(features.shape[1]).long()
490
+
491
+ t = self._label_str_to_tensor(sample.label)
492
+ tl = torch.tensor(t.size(0)).long()
493
+
494
+ return f, fl, t, tl
495
+
496
+ def _collate_fn(self, batch):
497
+ return _audio_feature_collate_fn(batch, self.zero_spec_db_val, 0)
nemo/collections/asr/data/feature_to_label_dataset.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional
15
+
16
+ from nemo.collections.asr.data import feature_to_label
17
+
18
+
19
+ def get_feature_seq_speakerlabel_dataset(
20
+ feature_loader, config: dict
21
+ ) -> feature_to_label.FeatureToSeqSpeakerLabelDataset:
22
+ """
23
+ Instantiates a FeatureSeqSpeakerLabelDataset.
24
+ Args:
25
+ config: Config of the FeatureToSeqSpeakerLabelDataset.
26
+
27
+ Returns:
28
+ An instance of FeatureToSeqSpeakerLabelDataset.
29
+ """
30
+ dataset = feature_to_label.FeatureToSeqSpeakerLabelDataset(
31
+ manifest_filepath=config['manifest_filepath'], labels=config['labels'], feature_loader=feature_loader,
32
+ )
33
+ return dataset
34
+
35
+
36
+ def get_feature_label_dataset(
37
+ config: dict, augmentor: Optional['FeatureAugmentor'] = None
38
+ ) -> feature_to_label.FeatureToLabelDataset:
39
+ dataset = feature_to_label.FeatureToLabelDataset(
40
+ manifest_filepath=config['manifest_filepath'],
41
+ labels=config['labels'],
42
+ augmentor=augmentor,
43
+ window_length_in_sec=config.get("window_length_in_sec", 0.63),
44
+ shift_length_in_sec=config.get("shift_length_in_sec", 0.08),
45
+ is_regression_task=config.get("is_regression_task", False),
46
+ cal_labels_occurrence=config.get("cal_labels_occurrence", False),
47
+ zero_spec_db_val=config.get("zero_spec_db_val", -16.635),
48
+ max_duration=config.get('max_duration', None),
49
+ min_duration=config.get('min_duration', None),
50
+ )
51
+ return dataset
52
+
53
+
54
+ def get_feature_multi_label_dataset(
55
+ config: dict, augmentor: Optional['FeatureAugmentor'] = None
56
+ ) -> feature_to_label.FeatureToMultiLabelDataset:
57
+ dataset = feature_to_label.FeatureToMultiLabelDataset(
58
+ manifest_filepath=config['manifest_filepath'],
59
+ labels=config['labels'],
60
+ augmentor=augmentor,
61
+ delimiter=config.get('delimiter', None),
62
+ is_regression_task=config.get("is_regression_task", False),
63
+ cal_labels_occurrence=config.get("cal_labels_occurrence", False),
64
+ zero_spec_db_val=config.get("zero_spec_db_val", -16.635),
65
+ max_duration=config.get('max_duration', None),
66
+ min_duration=config.get('min_duration', None),
67
+ )
68
+ return dataset
nemo/collections/asr/data/feature_to_text.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+
19
+ from nemo.collections.asr.data.feature_to_label import _audio_feature_collate_fn
20
+ from nemo.collections.asr.parts.preprocessing.feature_loader import ExternalFeatureLoader
21
+ from nemo.collections.asr.parts.preprocessing.features import normalize_batch
22
+ from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType
23
+ from nemo.collections.asr.parts.utils.vad_utils import load_speech_segments_from_rttm
24
+ from nemo.collections.common import tokenizers
25
+ from nemo.collections.common.parts.preprocessing import collections, parsers
26
+ from nemo.core.classes import Dataset
27
+ from nemo.core.neural_types import AcousticEncodedRepresentation, LabelsType, LengthsType, NeuralType
28
+
29
+
30
+ class ASRFeatureManifestProcessor:
31
+ def __init__(
32
+ self,
33
+ manifest_filepath: str,
34
+ parser: Union[str, Callable],
35
+ max_duration: Optional[float] = None,
36
+ min_duration: Optional[float] = None,
37
+ max_utts: int = 0,
38
+ bos_id: Optional[int] = None,
39
+ eos_id: Optional[int] = None,
40
+ pad_id: int = 0,
41
+ index_by_file_id: bool = False,
42
+ ):
43
+ self.parser = parser
44
+ self.collection = collections.ASRFeatureText(
45
+ manifests_files=manifest_filepath,
46
+ parser=parser,
47
+ min_duration=min_duration,
48
+ max_duration=max_duration,
49
+ max_number=max_utts,
50
+ index_by_file_id=index_by_file_id,
51
+ )
52
+
53
+ self.eos_id = eos_id
54
+ self.bos_id = bos_id
55
+ self.pad_id = pad_id
56
+
57
+ def process_text_by_id(self, index: int) -> Tuple[List[int], int]:
58
+ sample = self.collection[index]
59
+ return self.process_text_by_sample(sample)
60
+
61
+ def process_text_by_file_id(self, file_id: str) -> Tuple[List[int], int]:
62
+ manifest_idx = self.collection.mapping[file_id][0]
63
+ sample = self.collection[manifest_idx]
64
+ return self.process_text_by_sample(sample)
65
+
66
+ def process_text_by_sample(self, sample: collections.ASRAudioText.OUTPUT_TYPE) -> Tuple[List[int], int]:
67
+ t, tl = sample.text_tokens, len(sample.text_tokens)
68
+
69
+ if self.bos_id is not None:
70
+ t = [self.bos_id] + t
71
+ tl += 1
72
+ if self.eos_id is not None:
73
+ t = t + [self.eos_id]
74
+ tl += 1
75
+
76
+ return t, tl
77
+
78
+
79
+ class _FeatureTextDataset(Dataset):
80
+ """
81
+ Dataset that loads tensors via a json file containing paths to audio feature files, transcripts,
82
+ durations (in seconds) and optional RTTM files. Each new line is a different sample. Example below:
83
+ {"feature_filepath": "/path/to/audio_feature.pt", "text_filepath": "/path/to/audio.txt",
84
+ "rttm_filepath": "/path/to/audio_rttm.rttm", "duration": 23.147}
85
+ ...
86
+ {"feature_filepath": "/path/to/audio_feature.pt", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt":
87
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
88
+ Args:
89
+ manifest_filepath (str): Path to manifest json as described above. Can be comma-separated paths.
90
+ parser: Str for a language specific preprocessor or a callable.
91
+ normalize (bool): whether and where to normalize feature, must be one of [None, "post_norm", "pre_norm"]
92
+ normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch`
93
+ use_rttm (bool): whether to use RTTM files if there is any, default to False
94
+ rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask'
95
+ feat_min_len (int): minimum length of feature when rttm_mode=deop, default to 4.
96
+ feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram
97
+ frame_unit_time_secs (float): time in seconds for each frame
98
+ sample_rate (int): Sample rate to resample loaded audio to
99
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
100
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor object used to augment loaded audio
101
+ max_duration (float): If audio exceeds this length, do not include in dataset
102
+ min_duration (float): If audio is less than this length, do not include in dataset
103
+ max_utts (int): Limit number of utterances
104
+ trim (bool): whether or not to trim silence. Defaults to False
105
+ bos_id (int): Id of beginning of sequence symbol to append if not None
106
+ eos_id (int): Id of end of sequence symbol to append if not None
107
+ pad_id (int): Id of pad symbol. Defaults to 0
108
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
109
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
110
+ """
111
+
112
+ ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal
113
+ NORM_MODES = ["pre_norm", "post_norm"]
114
+ RTTM_MODES = ["mask", "drop"]
115
+
116
+ @property
117
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
118
+ """Returns definitions of module output ports."""
119
+ return {
120
+ 'features': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()),
121
+ 'feature_length': NeuralType(tuple('B'), LengthsType()),
122
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
123
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
124
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
125
+ }
126
+
127
+ def __init__(
128
+ self,
129
+ manifest_filepath: str,
130
+ parser: Union[str, Callable],
131
+ normalize: Optional[str] = "post_norm",
132
+ normalize_type: Union[str, dict] = "per_feature",
133
+ use_rttm: bool = False,
134
+ rttm_mode: str = "mask",
135
+ feat_min_len: int = 4,
136
+ feat_mask_val: Optional[float] = None,
137
+ frame_unit_time_secs: float = 0.01,
138
+ sample_rate: Optional[int] = 16000,
139
+ augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None,
140
+ max_duration: Optional[int] = None,
141
+ min_duration: Optional[int] = None,
142
+ max_utts: int = 0,
143
+ trim: bool = False,
144
+ bos_id: Optional[int] = None,
145
+ eos_id: Optional[int] = None,
146
+ pad_id: int = 0,
147
+ return_sample_id: bool = False,
148
+ channel_selector: Optional[ChannelSelectorType] = None,
149
+ ):
150
+ if type(manifest_filepath) == str:
151
+ manifest_filepath = manifest_filepath.split(",")
152
+
153
+ self.sample_rate = sample_rate
154
+ self.normalize = normalize
155
+ self.normalize_type = normalize_type
156
+ self.use_rttm = use_rttm
157
+ self.rttm_mode = rttm_mode
158
+ if self.use_rttm and self.rttm_mode not in self.RTTM_MODES:
159
+ raise ValueError(f"`rttm_mode` must be one of {self.RTTM_MODES}, got `{rttm_mode}` instead")
160
+
161
+ self.feat_min_len = feat_min_len
162
+ if feat_mask_val is not None:
163
+ self.feat_mask_val = feat_mask_val
164
+ elif normalize == "pre_norm":
165
+ self.feat_mask_val = 0.0 # similar to SpectralAugmentation
166
+ else:
167
+ self.feat_mask_val = self.ZERO_LEVEL_SPEC_DB_VAL
168
+
169
+ if normalize is not None and normalize not in self.NORM_MODES:
170
+ raise ValueError(f"`normalize` must be one of {self.NORM_MODES}, got `{normalize}` instead")
171
+
172
+ self.frame_unit_time_secs = frame_unit_time_secs
173
+
174
+ self.manifest_processor = ASRFeatureManifestProcessor(
175
+ manifest_filepath=manifest_filepath,
176
+ parser=parser,
177
+ max_duration=max_duration,
178
+ min_duration=min_duration,
179
+ max_utts=max_utts,
180
+ bos_id=bos_id,
181
+ eos_id=eos_id,
182
+ pad_id=pad_id,
183
+ )
184
+ self.featurizer = ExternalFeatureLoader(augmentor=augmentor)
185
+ self.trim = trim
186
+ self.return_sample_id = return_sample_id
187
+ self.channel_selector = channel_selector
188
+
189
+ def get_manifest_sample(self, sample_id):
190
+ return self.manifest_processor.collection[sample_id]
191
+
192
+ def __getitem__(self, index):
193
+ sample = self.manifest_processor.collection[index]
194
+ offset = sample.offset
195
+
196
+ if offset is None:
197
+ offset = 0
198
+
199
+ features = self.featurizer.process(sample.feature_file)
200
+
201
+ f, fl = features, torch.tensor(features.shape[1]).long()
202
+
203
+ t, tl = self.manifest_processor.process_text_by_sample(sample=sample)
204
+
205
+ # Feature normalization
206
+ if self.normalize is None:
207
+ if self.use_rttm and sample.rttm_file:
208
+ f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val)
209
+ elif self.normalize == "post_norm":
210
+ # (Optional) Masking based on RTTM file
211
+ if self.use_rttm and sample.rttm_file:
212
+ f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val)
213
+
214
+ f = self.normalize_feature(f)
215
+ else: # pre-norm
216
+ f = self.normalize_feature(f)
217
+ # (Optional) Masking based on RTTM file
218
+ if self.use_rttm and sample.rttm_file:
219
+ f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val)
220
+
221
+ if self.return_sample_id:
222
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index
223
+ else:
224
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long()
225
+
226
+ return output
227
+
228
+ def process_features_with_rttm(self, features, offset, rttm_file, mask_val):
229
+ segments = load_speech_segments_from_rttm(rttm_file)
230
+ new_features = features.clone()
231
+ sid, fid = 0, 0
232
+ for i in range(features.size(1)):
233
+ t = offset + i * self.frame_unit_time_secs
234
+ while sid < len(segments) - 1 and segments[sid][1] < t:
235
+ sid += 1
236
+ if segments[sid][1] == 0 or t < segments[sid][0] or t > segments[sid][1]:
237
+ # not in speech segment
238
+ if self.rttm_mode == "drop":
239
+ # drop the frame
240
+ continue
241
+ else:
242
+ # mask the frame with specified value
243
+ new_features[:, i] = mask_val
244
+ fid += 1
245
+ else:
246
+ # in speech segment
247
+ new_features[:, fid] = features[:, i]
248
+ fid += 1
249
+
250
+ if fid < self.feat_min_len and self.rttm_mode == "drop":
251
+ new_features[:, : self.feat_min_len] = mask_val
252
+ return new_features[:, : self.feat_min_len]
253
+ return new_features[:, :fid]
254
+
255
+ def __len__(self):
256
+ return len(self.manifest_processor.collection)
257
+
258
+ def _collate_fn(self, batch):
259
+ return _audio_feature_collate_fn(
260
+ batch, feat_pad_val=self.feat_mask_val, label_pad_id=self.manifest_processor.pad_id
261
+ )
262
+
263
+ def normalize_feature(self, feat):
264
+ """
265
+ Args:
266
+ feat: feature tensor of shape [M, T]
267
+ """
268
+ feat = feat.unsqueeze(0) # add batch dim
269
+ feat, _, _ = normalize_batch(feat, torch.tensor([feat.size(-1)]), self.normalize_type)
270
+ return feat.squeeze(0) # delete batch dim
271
+
272
+
273
+ class FeatureToCharDataset(_FeatureTextDataset):
274
+ """
275
+ Dataset that loads tensors via a json file containing paths to audio feature
276
+ files, transcripts, durations (in seconds) and optional RTTM files. Each new line is a
277
+ different sample. Example below:
278
+ {"feature_filepath": "/path/to/audio_feature.pt", "text_filepath":
279
+ "/path/to/audio.txt", "duration": 23.147, "rttm_filepath": "/path/to/audio_rttm.rttm",}
280
+ ...
281
+ {"feature_filepath": "/path/to/audio_feature.pt", "text": "the
282
+ transcription", "offset": 301.75, "duration": 0.82, "utt":
283
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
284
+
285
+ Args:
286
+ manifest_filepath (str): Path to manifest json as described above. Can
287
+ be comma-separated paths.
288
+ labels (str): String containing all the possible characters to map to
289
+ normalize (str): how to normalize feature, must be one of [None, "post_norm", "pre_norm"]
290
+ normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch`
291
+ use_rttm (bool): whether to use RTTM files if there is any, default to False
292
+ rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask'
293
+ feat_min_len (int): minimum length of feature, default to 4
294
+ feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram
295
+ frame_unit_time_secs: time in seconds for each frame
296
+ sample_rate (int): Sample rate to resample loaded audio to
297
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
298
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
299
+ object used to augment loaded audio
300
+ max_duration: If audio exceeds this length, do not include in dataset
301
+ min_duration: If audio is less than this length, do not include
302
+ in dataset
303
+ max_utts: Limit number of utterances
304
+ blank_index: blank character index, default = -1
305
+ unk_index: unk_character index, default = -1
306
+ bos_id: Id of beginning of sequence symbol to append if not None
307
+ eos_id: Id of end of sequence symbol to append if not None
308
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
309
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
310
+ """
311
+
312
+ def __init__(
313
+ self,
314
+ manifest_filepath: str,
315
+ labels: Union[str, List[str]],
316
+ normalize: Optional[str] = "post_norm",
317
+ normalize_type: Union[str, dict] = "per_feature",
318
+ use_rttm: bool = False,
319
+ rttm_mode: str = "mask",
320
+ feat_min_len: int = 4,
321
+ feat_mask_val: Optional[float] = None,
322
+ frame_unit_time_secs: float = 0.01,
323
+ sample_rate: Optional[int] = 16000,
324
+ augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None,
325
+ max_duration: Optional[int] = None,
326
+ min_duration: Optional[int] = None,
327
+ max_utts: int = 0,
328
+ blank_index: int = -1,
329
+ unk_index: int = -1,
330
+ trim: bool = False,
331
+ bos_id: Optional[int] = None,
332
+ eos_id: Optional[int] = None,
333
+ pad_id: int = 0,
334
+ parser: Union[str, Callable] = 'en',
335
+ return_sample_id: bool = False,
336
+ channel_selector: Optional[ChannelSelectorType] = None,
337
+ ):
338
+ self.labels = labels
339
+
340
+ parser = parsers.make_parser(
341
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
342
+ )
343
+
344
+ super().__init__(
345
+ manifest_filepath=manifest_filepath,
346
+ parser=parser,
347
+ normalize=normalize,
348
+ normalize_type=normalize_type,
349
+ use_rttm=use_rttm,
350
+ rttm_mode=rttm_mode,
351
+ feat_min_len=feat_min_len,
352
+ feat_mask_val=feat_mask_val,
353
+ frame_unit_time_secs=frame_unit_time_secs,
354
+ sample_rate=sample_rate,
355
+ augmentor=augmentor,
356
+ max_duration=max_duration,
357
+ min_duration=min_duration,
358
+ max_utts=max_utts,
359
+ trim=trim,
360
+ bos_id=bos_id,
361
+ eos_id=eos_id,
362
+ pad_id=pad_id,
363
+ return_sample_id=return_sample_id,
364
+ channel_selector=channel_selector,
365
+ )
366
+
367
+
368
+ class FeatureToBPEDataset(_FeatureTextDataset):
369
+ """
370
+ Dataset that loads tensors via a json file containing paths to audio feature
371
+ files, transcripts, durations (in seconds) and optional RTTM files. Each new line is a different sample.
372
+ Example below:
373
+ {"audio_filepath": "/path/to/audio.wav", "text_filepath":
374
+ "/path/to/audio.txt", "duration": 23.147, "rttm_filepath": "/path/to/audio_rttm.rttm",}
375
+ ...
376
+ {"audio_filepath": "/path/to/audio.wav", "text": "the
377
+ transcription", "offset": 301.75, "duration": 0.82, "utt":
378
+ "utterance_id", "ctm_utt": "en_4156", "side": "A"}
379
+
380
+ In practice, the dataset and manifest used for character encoding and byte pair encoding
381
+ are exactly the same. The only difference lies in how the dataset tokenizes the text in
382
+ the manifest.
383
+
384
+ Args:
385
+ manifest_filepath (str): Path to manifest json as described above. Can
386
+ be comma-separated paths.
387
+ tokenizer: A subclass of the Tokenizer wrapper found in the common collection,
388
+ nemo.collections.common.tokenizers.TokenizerSpec. ASR Models support a subset of
389
+ all available tokenizers.
390
+ normalize (str): how to normalize feature, must be one of [None, "post_norm", "pre_norm"]
391
+ normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch`
392
+ use_rttm (bool): whether to use RTTM files if there is any, default to False
393
+ rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask'
394
+ feat_min_len (int): minimum length of feature, default to 4
395
+ feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram
396
+ frame_unit_time_secs: time in seconds for each frame
397
+ sample_rate (int): Sample rate to resample loaded audio to
398
+ int_values (bool): If true, load samples as 32-bit integers. Defauts to False.
399
+ augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor
400
+ object used to augment loaded audio
401
+ max_duration: If audio exceeds this length, do not include in dataset
402
+ min_duration: If audio is less than this length, do not include
403
+ in dataset
404
+ max_utts: Limit number of utterances
405
+ trim: Whether to trim silence segments
406
+ use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS]
407
+ tokens to beginning and ending of speech respectively.
408
+ return_sample_id (bool): whether to return the sample_id as a part of each sample
409
+ channel_selector (int | Iterable[int] | str): select a single channel or a subset of channels from multi-channel audio. If set to `'average'`, it performs averaging across channels. Disabled if set to `None`. Defaults to `None`. Uses zero-based indexing.
410
+ """
411
+
412
+ def __init__(
413
+ self,
414
+ manifest_filepath: str,
415
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
416
+ normalize: Optional[str] = "post_norm",
417
+ normalize_type: Union[str, dict] = "per_feature",
418
+ use_rttm: bool = False,
419
+ rttm_mode: str = "mask",
420
+ feat_min_len: int = 4,
421
+ feat_mask_val: Optional[float] = None,
422
+ frame_unit_time_secs: float = 0.01,
423
+ sample_rate: Optional[int] = 16000,
424
+ augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None,
425
+ max_duration: Optional[int] = None,
426
+ min_duration: Optional[int] = None,
427
+ max_utts: int = 0,
428
+ use_start_end_token: bool = True,
429
+ trim: bool = False,
430
+ return_sample_id: bool = False,
431
+ channel_selector: Optional[ChannelSelectorType] = None,
432
+ ):
433
+ if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0:
434
+ bos_id = tokenizer.bos_id
435
+ else:
436
+ bos_id = None
437
+
438
+ if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0:
439
+ eos_id = tokenizer.eos_id
440
+ else:
441
+ eos_id = None
442
+
443
+ if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0:
444
+ pad_id = tokenizer.pad_id
445
+ else:
446
+ pad_id = 0
447
+
448
+ class TokenizerWrapper:
449
+ def __init__(self, tokenizer):
450
+ if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer):
451
+ self.is_aggregate = True
452
+ else:
453
+ self.is_aggregate = False
454
+ self._tokenizer = tokenizer
455
+
456
+ def __call__(self, *args):
457
+ if isinstance(args[0], List) and self.is_aggregate:
458
+ t = []
459
+ for span in args[0]:
460
+ t.extend(self._tokenizer.text_to_ids(span['str'], span['lang']))
461
+ return t
462
+
463
+ t = self._tokenizer.text_to_ids(*args)
464
+ return t
465
+
466
+ super().__init__(
467
+ manifest_filepath=manifest_filepath,
468
+ parser=TokenizerWrapper(tokenizer),
469
+ normalize=normalize,
470
+ normalize_type=normalize_type,
471
+ use_rttm=use_rttm,
472
+ rttm_mode=rttm_mode,
473
+ feat_min_len=feat_min_len,
474
+ feat_mask_val=feat_mask_val,
475
+ frame_unit_time_secs=frame_unit_time_secs,
476
+ sample_rate=sample_rate,
477
+ augmentor=augmentor,
478
+ max_duration=max_duration,
479
+ min_duration=min_duration,
480
+ max_utts=max_utts,
481
+ trim=trim,
482
+ bos_id=bos_id,
483
+ eos_id=eos_id,
484
+ pad_id=pad_id,
485
+ return_sample_id=return_sample_id,
486
+ channel_selector=channel_selector,
487
+ )
nemo/collections/asr/data/feature_to_text_dataset.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ from nemo.collections.asr.data.feature_to_text import FeatureToBPEDataset, FeatureToCharDataset
18
+ from nemo.utils import logging
19
+
20
+
21
+ def get_char_dataset(config: dict, augmentor: Optional['FeatureAugmentor'] = None) -> FeatureToCharDataset:
22
+ """
23
+ Instantiates a Character Encoding based FeatureToCharDataset.
24
+
25
+ Args:
26
+ config: Config of the FeatureToCharDataset.
27
+ augmentor: Optional AudioAugmentor object for augmentations on audio data.
28
+
29
+ Returns:
30
+ An instance of FeatureToCharDataset.
31
+ """
32
+ if 'labels' not in config:
33
+ logging.warning(f"dataset does not have explicitly defined labels")
34
+
35
+ dataset = FeatureToCharDataset(
36
+ manifest_filepath=config['manifest_filepath'],
37
+ labels=config.get('labels', None),
38
+ normalize=config.get('normalize', 'post_norm'),
39
+ normalize_type=config.get('normalize_type', 'per_feature'),
40
+ use_rttm=config.get('use_rttm', False),
41
+ rttm_mode=config.get('rttm_mode', 'mask'),
42
+ feat_min_len=config.get('feat_min_len', 4),
43
+ feat_mask_val=config.get('feat_mask_val', None),
44
+ frame_unit_time_secs=config.get('frame_unit_time_secs', 0.01),
45
+ sample_rate=config.get('sample_rate', 16000),
46
+ augmentor=augmentor,
47
+ max_duration=config.get('max_duration', None),
48
+ min_duration=config.get('min_duration', None),
49
+ max_utts=config.get('max_utts', 0),
50
+ blank_index=config.get('blank_index', -1),
51
+ unk_index=config.get('unk_index', -1),
52
+ trim=config.get('trim_silence', False),
53
+ parser=config.get('parser', 'en'),
54
+ return_sample_id=config.get('return_sample_id', False),
55
+ channel_selector=config.get('channel_selector', None),
56
+ )
57
+ return dataset
58
+
59
+
60
+ def get_bpe_dataset(
61
+ config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['FeatureAugmentor'] = None
62
+ ) -> FeatureToBPEDataset:
63
+ """
64
+ Instantiates a Byte Pair Encoding / Word Piece Encoding based FeatureoToBPEDataset.
65
+
66
+ Args:
67
+ config: Config of the FeatureToBPEDataset.
68
+ tokenizer: An instance of a TokenizerSpec object.
69
+ augmentor: Optional FeatureAugmentor object for augmentations on audio features.
70
+
71
+ Returns:
72
+ An instance of FeatureToBPEDataset.
73
+ """
74
+ dataset = FeatureToBPEDataset(
75
+ manifest_filepath=config['manifest_filepath'],
76
+ tokenizer=tokenizer,
77
+ normalize=config.get('normalize', 'post_norm'),
78
+ normalize_type=config.get('normalize_type', 'per_feature'),
79
+ use_rttm=config.get('use_rttm', False),
80
+ rttm_mode=config.get('rttm_mode', 'mask'),
81
+ feat_min_len=config.get('feat_min_len', 4),
82
+ feat_mask_val=config.get('feat_mask_val', None),
83
+ frame_unit_time_secs=config.get('frame_unit_time_secs', 0.01),
84
+ sample_rate=config.get('sample_rate', 16000),
85
+ augmentor=augmentor,
86
+ max_duration=config.get('max_duration', None),
87
+ min_duration=config.get('min_duration', None),
88
+ max_utts=config.get('max_utts', 0),
89
+ trim=config.get('trim_silence', False),
90
+ use_start_end_token=config.get('use_start_end_token', True),
91
+ return_sample_id=config.get('return_sample_id', False),
92
+ channel_selector=config.get('channel_selector', None),
93
+ )
94
+ return dataset
nemo/collections/asr/data/huggingface/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
nemo/collections/asr/data/huggingface/hf_audio_to_text.py ADDED
@@ -0,0 +1,694 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import datasets as hf_datasets
18
+ import torch
19
+ from datasets import concatenate_datasets
20
+ from datasets.distributed import split_dataset_by_node
21
+ from omegaconf import DictConfig, ListConfig, open_dict
22
+
23
+ from nemo.collections.asr.data.audio_to_text import _speech_collate_fn
24
+ from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor
25
+ from nemo.collections.asr.parts.preprocessing.segment import AudioSegment, ChannelSelectorType
26
+ from nemo.collections.common import tokenizers
27
+ from nemo.collections.common.parts.preprocessing import parsers
28
+ from nemo.core.classes import Dataset, IterableDataset
29
+ from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType
30
+ from nemo.utils import logging
31
+
32
+
33
+ class HFTextProcessor:
34
+ """
35
+ Text processor for huggingface datasets, mimicing the behavior of
36
+ `nemo.collections.asr.data.audio_to_text.ASRManifestProcessor`.
37
+ Basic text cleaning is also supported.
38
+ Args:
39
+ parser: Str for a language specific preprocessor or a callable.
40
+ bos_id: BOS token id to add to the beginning of the transcript.
41
+ eos_id: EOS token id to add to the end of the transcript.
42
+ pad_id: PAD token id to pad transcripts to the same length.
43
+ normalize_text: If true, normalizes text in HFTextProcessor
44
+ symbols_to_keep: If not None, only keeps symbols in this list when normalizing text
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ parser: Union[str, Callable],
50
+ bos_id: Optional[int] = None,
51
+ eos_id: Optional[int] = None,
52
+ pad_id: int = 0,
53
+ normalize_text: bool = False,
54
+ symbols_to_keep: Optional[str | List[str]] = None,
55
+ ):
56
+ self.parser = parser
57
+ self.eos_id = eos_id
58
+ self.bos_id = bos_id
59
+ self.pad_id = pad_id
60
+ self.normalize_text = normalize_text
61
+ self.symbols_to_keep = [x for x in symbols_to_keep] if symbols_to_keep is not None else []
62
+
63
+ def process_text(self, text: str, lang: Optional[str] = None) -> List[int]:
64
+
65
+ if self.normalize_text:
66
+ text = text.lower()
67
+ # only keep alphanumeric characters, spaces and symbols defined in self.symbols_to_keep
68
+ text = ''.join([c for c in text if c.isalnum() or c.isspace() or c in self.symbols_to_keep])
69
+
70
+ if hasattr(self.parser, "is_aggregate") and self.parser.is_aggregate and isinstance(text, str):
71
+ if lang is not None:
72
+ text_tokens = self.parser(text, lang)
73
+ # for future use if want to add language bypass to audio_to_text classes
74
+ # elif hasattr(parser, "lang") and parser.lang is not None:
75
+ # text_tokens = parser(text, parser.lang)
76
+ else:
77
+ raise ValueError("lang required in manifest when using aggregate tokenizers")
78
+ else:
79
+ text_tokens = self.parser(text)
80
+ text_tokens_length = len(text_tokens)
81
+ if self.bos_id is not None:
82
+ text_tokens = [self.bos_id] + text_tokens
83
+ text_tokens_length += 1
84
+ if self.eos_id is not None:
85
+ text_tokens = text_tokens + [self.eos_id]
86
+ text_tokens_length += 1
87
+ return text_tokens, text_tokens_length
88
+
89
+
90
+ def get_nested_dict_value(dictionary: dict, key: str):
91
+ """
92
+ the key should be a string of nested keys separated by `.`, e.g. `key1.key2.key3`,
93
+ then the returned value will be `dictionary[key1][key2][key3]`
94
+ """
95
+ nested_keys = key.split(".")
96
+ result = dictionary
97
+ for k in nested_keys:
98
+ if k not in result:
99
+ raise KeyError(
100
+ f"Key `{key}` not found in [{result.keys()}], target is {nested_keys}, input is {dictionary}"
101
+ )
102
+ result = result[k]
103
+ return result
104
+
105
+
106
+ class _HFAudioTextDataset(Dataset):
107
+ """
108
+ A Dataset wrapper that loads from HuggingFace datasets and converts to NeMo compatible format.
109
+ Args:
110
+ audio_key: key to access audio data from the dataset
111
+ text_key: key to access text data from the dataset
112
+ sample_rate_key: key to access sample rate data from the dataset
113
+ hf_data_cfg: HuggingFace dataset config, all params in this config will be passed to `hf_datasets.load_dataset`
114
+ parser: Str for a language specific preprocessor or a callable.
115
+ augmentor: An instance of `nemo.collections.asr.parts.perturb.AudioAugmentor` to apply on audio.
116
+ trim: If true, trims silence using `nemo.collections.asr.parts.preprocessing.segment.AudioSegment`
117
+ bos_id: BOS token id to add to the beginning of the transcript.
118
+ eos_id: EOS token id to add to the end of the transcript.
119
+ pad_id: PAD token id to pad transcripts to the same length.
120
+ return_sample_id: If true, returns sample id from the dataset.
121
+ channel_selector: ChannelSelectorType, which channel(s) to use for audio.
122
+ normalize_db: Target RMS value for audio normalization.
123
+ ref_channel: Reference channel for normalization.
124
+ id_key: key to access sample id from the dataset
125
+ normalize_text: If true, normalizes text in HFTextProcessor
126
+ symbols_to_keep: If not None, only keeps symbols in this list when normalizing text
127
+ """
128
+
129
+ def __init__(
130
+ self,
131
+ audio_key: str,
132
+ text_key: str,
133
+ sample_rate_key: str,
134
+ hf_data_cfg: Union[DictConfig, ListConfig],
135
+ parser: Union[str, Callable],
136
+ sample_rate: int,
137
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
138
+ trim: bool = False,
139
+ bos_id: Optional[int] = None,
140
+ eos_id: Optional[int] = None,
141
+ pad_id: int = 0,
142
+ return_sample_id: bool = False,
143
+ channel_selector: Optional[ChannelSelectorType] = None,
144
+ normalize_db: Optional[float] = None,
145
+ ref_channel: Optional[int] = None,
146
+ id_key: Optional[str] = None,
147
+ normalize_text: bool = False,
148
+ symbols_to_keep: Optional[str] = None,
149
+ ) -> None:
150
+ super().__init__()
151
+ self.audio_key = audio_key
152
+ self.text_key = text_key
153
+ self.sample_rate_key = sample_rate_key
154
+ self.id_key = id_key
155
+ self.sample_rate = sample_rate
156
+ self.augmentor = augmentor if augmentor is not None else AudioAugmentor()
157
+ self.trim = trim
158
+ self.return_sample_id = return_sample_id
159
+ self.channel_selector = channel_selector
160
+ self.normalize_db = normalize_db
161
+ self.ref_channel = ref_channel
162
+
163
+ self.text_processor = HFTextProcessor(parser, bos_id, eos_id, pad_id, normalize_text, symbols_to_keep)
164
+
165
+ data_config_list = [hf_data_cfg] if isinstance(hf_data_cfg, DictConfig) else hf_data_cfg
166
+ dataset_list = []
167
+ for data_cfg in data_config_list:
168
+ with open_dict(data_cfg):
169
+ if "streaming" in data_cfg and data_cfg.streaming:
170
+ logging.warning(
171
+ "streaming must be False for random access dataset, but you use streaming=True. Forcing streaming=False"
172
+ )
173
+ data_cfg.streaming = False
174
+ logging.info(f"Loading HuggingFace Dataset with cfg: {data_cfg}")
175
+ dataset_list.append(hf_datasets.load_dataset(**data_cfg))
176
+ logging.info(f"Dataset loaded with {len(dataset_list[-1])} samples")
177
+ self.dataset = concatenate_datasets(dataset_list)
178
+
179
+ logging.info(f"Total number of samples loaded: {len(self.dataset)}")
180
+
181
+ def __len__(self):
182
+ return len(self.dataset)
183
+
184
+ def __getitem__(self, index) -> Tuple:
185
+ item = self.dataset[index]
186
+
187
+ audio_array = get_nested_dict_value(item, self.audio_key)
188
+ origin_sr = get_nested_dict_value(item, self.sample_rate_key)
189
+ audio_segment = AudioSegment(
190
+ samples=audio_array,
191
+ sample_rate=origin_sr,
192
+ target_sr=self.sample_rate,
193
+ trim=self.trim,
194
+ channel_selector=self.channel_selector,
195
+ normalize_db=self.normalize_db,
196
+ ref_channel=self.ref_channel,
197
+ )
198
+ self.augmentor.perturb(audio_segment)
199
+ f = torch.tensor(audio_segment.samples, dtype=torch.float)
200
+ fl = torch.tensor(f.shape[0], dtype=torch.long)
201
+
202
+ text = get_nested_dict_value(item, self.text_key)
203
+ t, tl = self.text_processor.process_text(text)
204
+
205
+ index = get_nested_dict_value(item, self.id_key) if self.id_key else index
206
+ if self.return_sample_id:
207
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index
208
+ else:
209
+ output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long()
210
+
211
+ return output
212
+
213
+ def _collate_fn(self, batch):
214
+ return _speech_collate_fn(batch, pad_id=self.text_processor.pad_id)
215
+
216
+
217
+ class HFAudioToCharDataset(_HFAudioTextDataset):
218
+ """
219
+ Wrapper class for loading HuggingFace dataset for a char-based ASR model
220
+ """
221
+
222
+ @property
223
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
224
+ """Returns definitions of module output ports."""
225
+ return {
226
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
227
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
228
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
229
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
230
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
231
+ }
232
+
233
+ def __init__(
234
+ self,
235
+ audio_key: str,
236
+ text_key: str,
237
+ sample_rate_key: str,
238
+ hf_data_cfg: DictConfig,
239
+ labels: List[str],
240
+ sample_rate: int,
241
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
242
+ trim: bool = False,
243
+ bos_id: Optional[int] = None,
244
+ eos_id: Optional[int] = None,
245
+ pad_id: int = 0,
246
+ return_sample_id: bool = False,
247
+ channel_selector: Optional[ChannelSelectorType] = None,
248
+ normalize_db: Optional[float] = None,
249
+ ref_channel: Optional[int] = None,
250
+ parser: Union[str, Callable] = 'en',
251
+ blank_index: int = -1,
252
+ unk_index: int = -1,
253
+ normalize: bool = True,
254
+ id_key: Optional[str] = None,
255
+ normalize_text: bool = False,
256
+ symbols_to_keep: Optional[str] = None,
257
+ ):
258
+ self.labels = labels
259
+
260
+ parser = parsers.make_parser(
261
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
262
+ )
263
+
264
+ super().__init__(
265
+ audio_key=audio_key,
266
+ text_key=text_key,
267
+ sample_rate_key=sample_rate_key,
268
+ hf_data_cfg=hf_data_cfg,
269
+ parser=parser,
270
+ sample_rate=sample_rate,
271
+ augmentor=augmentor,
272
+ trim=trim,
273
+ bos_id=bos_id,
274
+ eos_id=eos_id,
275
+ pad_id=pad_id,
276
+ return_sample_id=return_sample_id,
277
+ channel_selector=channel_selector,
278
+ normalize_db=normalize_db,
279
+ ref_channel=ref_channel,
280
+ id_key=id_key,
281
+ normalize_text=normalize_text,
282
+ symbols_to_keep=symbols_to_keep,
283
+ )
284
+
285
+
286
+ class HFAudioToBPEDataset(_HFAudioTextDataset):
287
+ """
288
+ Wrapper class for loading a HuggingFace dataset for a BPE-based ASR model
289
+ """
290
+
291
+ @property
292
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
293
+ """Returns definitions of module output ports."""
294
+ return {
295
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
296
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
297
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
298
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
299
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
300
+ }
301
+
302
+ def __init__(
303
+ self,
304
+ audio_key: str,
305
+ text_key: str,
306
+ sample_rate_key: str,
307
+ hf_data_cfg: DictConfig,
308
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
309
+ sample_rate: int,
310
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
311
+ trim: bool = False,
312
+ return_sample_id: bool = False,
313
+ channel_selector: Optional[ChannelSelectorType] = None,
314
+ normalize_db: Optional[float] = None,
315
+ ref_channel: Optional[int] = None,
316
+ use_start_end_token: bool = True,
317
+ id_key: Optional[str] = None,
318
+ normalize_text: bool = False,
319
+ symbols_to_keep: Optional[str] = None,
320
+ ):
321
+ if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0:
322
+ bos_id = tokenizer.bos_id
323
+ else:
324
+ bos_id = None
325
+
326
+ if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0:
327
+ eos_id = tokenizer.eos_id
328
+ else:
329
+ eos_id = None
330
+
331
+ if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0:
332
+ pad_id = tokenizer.pad_id
333
+ else:
334
+ pad_id = 0
335
+
336
+ class TokenizerWrapper:
337
+ def __init__(self, tokenizer):
338
+ if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer):
339
+ self.is_aggregate = True
340
+ else:
341
+ self.is_aggregate = False
342
+ self._tokenizer = tokenizer
343
+
344
+ def __call__(self, *args):
345
+ if isinstance(args[0], List) and self.is_aggregate:
346
+ t = []
347
+ for span in args[0]:
348
+ t.extend(self._tokenizer.text_to_ids(span['str'], span['lang']))
349
+ return t
350
+
351
+ t = self._tokenizer.text_to_ids(*args)
352
+ return t
353
+
354
+ super().__init__(
355
+ audio_key=audio_key,
356
+ text_key=text_key,
357
+ sample_rate_key=sample_rate_key,
358
+ hf_data_cfg=hf_data_cfg,
359
+ parser=TokenizerWrapper(tokenizer),
360
+ sample_rate=sample_rate,
361
+ augmentor=augmentor,
362
+ trim=trim,
363
+ bos_id=bos_id,
364
+ eos_id=eos_id,
365
+ pad_id=pad_id,
366
+ return_sample_id=return_sample_id,
367
+ channel_selector=channel_selector,
368
+ normalize_db=normalize_db,
369
+ ref_channel=ref_channel,
370
+ id_key=id_key,
371
+ normalize_text=normalize_text,
372
+ symbols_to_keep=symbols_to_keep,
373
+ )
374
+
375
+
376
+ class _HFIterableAudioTextDataset(IterableDataset):
377
+ """
378
+ Wrapper class for loading HuggingFace IterableDataset and converts to NeMo compatible format.
379
+ Args:
380
+ audio_key: key to access audio data from the dataset
381
+ text_key: key to access text data from the dataset
382
+ sample_rate_key: key to access sample rate data from the dataset
383
+ hf_data_cfg: HuggingFace dataset config, all params in this config will be passed to `hf_datasets.load_dataset`
384
+ parser: Str for a language specific preprocessor or a callable.
385
+ augmentor: An instance of `nemo.collections.asr.parts.perturb.AudioAugmentor` to apply on audio.
386
+ trim: If true, trims silence using `nemo.collections.asr.parts.preprocessing.segment.AudioSegment`
387
+ bos_id: BOS token id to add to the beginning of the transcript.
388
+ eos_id: EOS token id to add to the end of the transcript.
389
+ pad_id: PAD token id to pad transcripts to the same length.
390
+ return_sample_id: If true, returns sample id from the dataset.
391
+ channel_selector: ChannelSelectorType, which channel(s) to use for audio.
392
+ normalize_db: Target RMS value for audio normalization.
393
+ ref_channel: Reference channel for normalization.
394
+ id_key: key to access sample id from the dataset
395
+ global_rank: global rank of the current worker
396
+ world_size: total number of workers
397
+ shuffle_n: buffer size for shuffling
398
+ shuffle_seed: seed for shuffling
399
+ normalize_text: If true, normalizes text in HFTextProcessor
400
+ symbols_to_keep: If not None, only keeps symbols in this list when normalizing text
401
+ """
402
+
403
+ def __init__(
404
+ self,
405
+ audio_key: str,
406
+ text_key: str,
407
+ sample_rate_key: str,
408
+ hf_data_cfg: Union[DictConfig, ListConfig],
409
+ parser: Union[str, Callable],
410
+ sample_rate: int,
411
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
412
+ trim: bool = False,
413
+ bos_id: Optional[int] = None,
414
+ eos_id: Optional[int] = None,
415
+ pad_id: int = 0,
416
+ return_sample_id: bool = False,
417
+ channel_selector: Optional[ChannelSelectorType] = None,
418
+ normalize_db: Optional[float] = None,
419
+ ref_channel: Optional[int] = None,
420
+ id_key: Optional[str] = None,
421
+ global_rank: int = 0,
422
+ world_size: int = 0,
423
+ shuffle_n: int = 0,
424
+ shuffle_seed: Optional[int] = None,
425
+ normalize_text: bool = False,
426
+ symbols_to_keep: Optional[str] = None,
427
+ ) -> None:
428
+ super().__init__()
429
+
430
+ if return_sample_id and id_key is None:
431
+ raise ValueError("return_sample_id is True, but id_key is None")
432
+
433
+ self.audio_key = audio_key
434
+ self.text_key = text_key
435
+ self.sample_rate_key = sample_rate_key
436
+ self.id_key = id_key
437
+ self.sample_rate = sample_rate
438
+ self.augmentor = augmentor if augmentor is not None else AudioAugmentor()
439
+ self.trim = trim
440
+ self.return_sample_id = return_sample_id
441
+ self.channel_selector = channel_selector
442
+ self.normalize_db = normalize_db
443
+ self.ref_channel = ref_channel
444
+
445
+ self.text_processor = HFTextProcessor(parser, bos_id, eos_id, pad_id, normalize_text, symbols_to_keep)
446
+
447
+ data_config_list = [hf_data_cfg] if isinstance(hf_data_cfg, DictConfig) else hf_data_cfg
448
+ dataset_list = []
449
+ for data_cfg in data_config_list:
450
+ with open_dict(data_cfg):
451
+ if "streaming" in data_cfg and not data_cfg.streaming:
452
+ logging.warning(
453
+ "streaming must be True for streaming dataset, but you use streaming=False. Forcing streaming=True"
454
+ )
455
+ # streaming must be True for iterable dataset
456
+ data_cfg.streaming = True
457
+ logging.info(f"Streaming HuggingFace IterableDataset with cfg: {data_cfg}")
458
+ dataset_list.append(hf_datasets.load_dataset(**data_cfg))
459
+
460
+ self.dataset = concatenate_datasets(dataset_list)
461
+ logging.info(f"Total number of samples cannot be extracted from HF streaming dataset")
462
+
463
+ if shuffle_n > 0:
464
+ self.dataset = self.dataset.shuffle(seed=shuffle_seed, buffer_size=shuffle_n)
465
+
466
+ self.dataset = split_dataset_by_node(self.dataset, global_rank, world_size)
467
+ self.dataset = self.dataset.map(self._build_sample)
468
+
469
+ def __len__(self):
470
+ raise NotImplementedError(
471
+ f"len() is not supported for {self.__class__.__name__}. Please set `trainer.max_steps` to explicitly set the number of steps to train for."
472
+ )
473
+
474
+ def __iter__(self):
475
+ return self.dataset.__iter__()
476
+
477
+ def _collate_fn(self, batch):
478
+ a_signal = [b['audio_signal'] for b in batch]
479
+ a_sig_length = [b['a_sig_length'] for b in batch]
480
+ transcripts = [b['transcripts'] for b in batch]
481
+ transcript_length = [b['transcript_length'] for b in batch]
482
+ if self.return_sample_id:
483
+ sample_id = [b['sample_id'] for b in batch]
484
+ batch_list = list(zip(a_signal, a_sig_length, transcripts, transcript_length, sample_id))
485
+ else:
486
+ batch_list = list(zip(a_signal, a_sig_length, transcripts, transcript_length))
487
+
488
+ return _speech_collate_fn(batch_list, pad_id=self.text_processor.pad_id)
489
+
490
+ def _build_sample(self, sample):
491
+ audio_array = get_nested_dict_value(sample, self.audio_key)
492
+ origin_sr = get_nested_dict_value(sample, self.sample_rate_key)
493
+ audio_segment = AudioSegment(
494
+ samples=audio_array,
495
+ sample_rate=origin_sr,
496
+ target_sr=self.sample_rate,
497
+ trim=self.trim,
498
+ channel_selector=self.channel_selector,
499
+ normalize_db=self.normalize_db,
500
+ ref_channel=self.ref_channel,
501
+ )
502
+ self.augmentor.perturb(audio_segment)
503
+ f = torch.tensor(audio_segment.samples, dtype=torch.float)
504
+ fl = torch.tensor(f.shape[0], dtype=torch.long)
505
+
506
+ text = get_nested_dict_value(sample, self.text_key)
507
+ t, tl = self.text_processor.process_text(text)
508
+
509
+ output = {
510
+ 'audio_signal': f,
511
+ 'a_sig_length': fl,
512
+ 'transcripts': torch.tensor(t).long(),
513
+ 'transcript_length': torch.tensor(tl).long(),
514
+ }
515
+
516
+ if self.return_sample_id:
517
+ output['sample_id'] = get_nested_dict_value(sample, self.id_key)
518
+ return output
519
+
520
+
521
+ class HFIterableAudioToCharDataset(_HFIterableAudioTextDataset):
522
+ """
523
+ Wrapper class for loading HuggingFace IterableDataset for a char-based ASR model
524
+ """
525
+
526
+ @property
527
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
528
+ """Returns definitions of module output ports."""
529
+ return {
530
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
531
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
532
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
533
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
534
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
535
+ }
536
+
537
+ def __init__(
538
+ self,
539
+ labels: List[str],
540
+ audio_key: str,
541
+ text_key: str,
542
+ sample_rate_key: str,
543
+ hf_data_cfg: DictConfig,
544
+ sample_rate: int,
545
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
546
+ trim: bool = False,
547
+ bos_id: int | None = None,
548
+ eos_id: int | None = None,
549
+ pad_id: int = 0,
550
+ return_sample_id: bool = False,
551
+ id_key: str | None = None,
552
+ channel_selector: ChannelSelectorType | None = None,
553
+ normalize_db: float | None = None,
554
+ ref_channel: int | None = None,
555
+ global_rank: int = 0,
556
+ world_size: int = 0,
557
+ shuffle_n: int = 0,
558
+ shuffle_seed: Optional[int] = None,
559
+ parser: Union[str, Callable] = 'en',
560
+ blank_index: int = -1,
561
+ unk_index: int = -1,
562
+ normalize: bool = True,
563
+ normalize_text: bool = False,
564
+ symbols_to_keep: Optional[str] = None,
565
+ ) -> None:
566
+ self.labels = labels
567
+
568
+ parser = parsers.make_parser(
569
+ labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize
570
+ )
571
+
572
+ super().__init__(
573
+ audio_key=audio_key,
574
+ text_key=text_key,
575
+ sample_rate_key=sample_rate_key,
576
+ hf_data_cfg=hf_data_cfg,
577
+ parser=parser,
578
+ sample_rate=sample_rate,
579
+ augmentor=augmentor,
580
+ trim=trim,
581
+ bos_id=bos_id,
582
+ eos_id=eos_id,
583
+ pad_id=pad_id,
584
+ return_sample_id=return_sample_id,
585
+ id_key=id_key,
586
+ channel_selector=channel_selector,
587
+ normalize_db=normalize_db,
588
+ ref_channel=ref_channel,
589
+ global_rank=global_rank,
590
+ world_size=world_size,
591
+ shuffle_n=shuffle_n,
592
+ shuffle_seed=shuffle_seed,
593
+ normalize_text=normalize_text,
594
+ symbols_to_keep=symbols_to_keep,
595
+ )
596
+
597
+
598
+ class HFIterableAudioToBPEDataset(_HFIterableAudioTextDataset):
599
+ """
600
+ Wrapper class for loading HuggingFace IterableDataset for a BPE-based ASR model
601
+ """
602
+
603
+ @property
604
+ def output_types(self) -> Optional[Dict[str, NeuralType]]:
605
+ """Returns definitions of module output ports."""
606
+ return {
607
+ 'audio_signal': NeuralType(('B', 'T'), AudioSignal()),
608
+ 'a_sig_length': NeuralType(tuple('B'), LengthsType()),
609
+ 'transcripts': NeuralType(('B', 'T'), LabelsType()),
610
+ 'transcript_length': NeuralType(tuple('B'), LengthsType()),
611
+ 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True),
612
+ }
613
+
614
+ def __init__(
615
+ self,
616
+ audio_key: str,
617
+ text_key: str,
618
+ sample_rate_key: str,
619
+ hf_data_cfg: DictConfig,
620
+ tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',
621
+ sample_rate: int,
622
+ augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,
623
+ trim: bool = False,
624
+ return_sample_id: bool = False,
625
+ id_key: str | None = None,
626
+ channel_selector: ChannelSelectorType | None = None,
627
+ normalize_db: float | None = None,
628
+ ref_channel: int | None = None,
629
+ global_rank: int = 0,
630
+ world_size: int = 0,
631
+ shuffle_n: int = 0,
632
+ shuffle_seed: Optional[int] = None,
633
+ use_start_end_token: bool = True,
634
+ normalize_text: bool = False,
635
+ symbols_to_keep: Optional[str] = None,
636
+ ) -> None:
637
+
638
+ if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0:
639
+ bos_id = tokenizer.bos_id
640
+ else:
641
+ bos_id = None
642
+
643
+ if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0:
644
+ eos_id = tokenizer.eos_id
645
+ else:
646
+ eos_id = None
647
+
648
+ if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0:
649
+ pad_id = tokenizer.pad_id
650
+ else:
651
+ pad_id = 0
652
+
653
+ class TokenizerWrapper:
654
+ def __init__(self, tokenizer):
655
+ if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer):
656
+ self.is_aggregate = True
657
+ else:
658
+ self.is_aggregate = False
659
+ self._tokenizer = tokenizer
660
+
661
+ def __call__(self, *args):
662
+ if isinstance(args[0], List) and self.is_aggregate:
663
+ t = []
664
+ for span in args[0]:
665
+ t.extend(self._tokenizer.text_to_ids(span['str'], span['lang']))
666
+ return t
667
+
668
+ t = self._tokenizer.text_to_ids(*args)
669
+ return t
670
+
671
+ super().__init__(
672
+ audio_key=audio_key,
673
+ text_key=text_key,
674
+ sample_rate_key=sample_rate_key,
675
+ hf_data_cfg=hf_data_cfg,
676
+ parser=TokenizerWrapper(tokenizer),
677
+ sample_rate=sample_rate,
678
+ augmentor=augmentor,
679
+ trim=trim,
680
+ bos_id=bos_id,
681
+ eos_id=eos_id,
682
+ pad_id=pad_id,
683
+ return_sample_id=return_sample_id,
684
+ id_key=id_key,
685
+ channel_selector=channel_selector,
686
+ normalize_db=normalize_db,
687
+ ref_channel=ref_channel,
688
+ global_rank=global_rank,
689
+ world_size=world_size,
690
+ shuffle_n=shuffle_n,
691
+ shuffle_seed=shuffle_seed,
692
+ normalize_text=normalize_text,
693
+ symbols_to_keep=symbols_to_keep,
694
+ )
nemo/collections/asr/data/huggingface/hf_audio_to_text_dataset.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from omegaconf import DictConfig
16
+
17
+ from nemo.collections.asr.data.huggingface.hf_audio_to_text import (
18
+ HFAudioToBPEDataset,
19
+ HFAudioToCharDataset,
20
+ HFIterableAudioToBPEDataset,
21
+ HFIterableAudioToCharDataset,
22
+ )
23
+
24
+
25
+ def get_hf_audio_to_text_bpe_dataset(
26
+ config: DictConfig, global_rank: int, world_size: int, tokenizer, augmentor=None,
27
+ ):
28
+ if "streaming" in config and config["streaming"]:
29
+ dataset = HFIterableAudioToBPEDataset(
30
+ audio_key=config.get('audio_key', 'audio.array'),
31
+ text_key=config["text_key"],
32
+ sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'),
33
+ tokenizer=tokenizer,
34
+ hf_data_cfg=config["hf_data_cfg"],
35
+ sample_rate=config["sample_rate"],
36
+ augmentor=augmentor,
37
+ trim=config.get('trim_silence', False),
38
+ return_sample_id=config.get('return_sample_id', False),
39
+ id_key=config.get("id_key", None),
40
+ channel_selector=config.get('channel_selector', None),
41
+ normalize_db=config.get('normalize_db', None),
42
+ ref_channel=config.get('ref_channel', None),
43
+ global_rank=global_rank,
44
+ world_size=world_size,
45
+ shuffle_n=config.get("shuffle_n", 2048),
46
+ shuffle_seed=config.get("shuffle_seed", None),
47
+ use_start_end_token=config.get('use_start_end_token', True),
48
+ normalize_text=config.get('normalize_text', False),
49
+ symbols_to_keep=config.get('symbols_to_keep', None),
50
+ )
51
+ else:
52
+ dataset = HFAudioToBPEDataset(
53
+ audio_key=config.get('audio_key', 'audio.array'),
54
+ text_key=config["text_key"],
55
+ sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'),
56
+ tokenizer=tokenizer,
57
+ hf_data_cfg=config["hf_data_cfg"],
58
+ sample_rate=config["sample_rate"],
59
+ augmentor=augmentor,
60
+ trim=config.get('trim_silence', False),
61
+ return_sample_id=config.get('return_sample_id', False),
62
+ id_key=config.get("id_key", None),
63
+ channel_selector=config.get('channel_selector', None),
64
+ normalize_db=config.get('normalize_db', None),
65
+ ref_channel=config.get('ref_channel', None),
66
+ use_start_end_token=config.get('use_start_end_token', True),
67
+ normalize_text=config.get('normalize_text', False),
68
+ symbols_to_keep=config.get('symbols_to_keep', None),
69
+ )
70
+
71
+ return dataset
72
+
73
+
74
+ def get_hf_audio_to_text_char_dataset(
75
+ config: DictConfig, global_rank: int, world_size: int, augmentor=None,
76
+ ):
77
+ if "streaming" in config and config["streaming"]:
78
+ dataset = HFIterableAudioToCharDataset(
79
+ labels=config["labels"],
80
+ audio_key=config.get('audio_key', 'audio.array'),
81
+ text_key=config["text_key"],
82
+ sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'),
83
+ hf_data_cfg=config["hf_data_cfg"],
84
+ sample_rate=config["sample_rate"],
85
+ augmentor=augmentor,
86
+ trim=config.get('trim_silence', False),
87
+ return_sample_id=config.get('return_sample_id', False),
88
+ id_key=config.get("id_key", None),
89
+ channel_selector=config.get('channel_selector', None),
90
+ normalize_db=config.get('normalize_db', None),
91
+ ref_channel=config.get('ref_channel', None),
92
+ global_rank=global_rank,
93
+ world_size=world_size,
94
+ shuffle_n=config.get("shuffle_n", 2048),
95
+ shuffle_seed=config.get("shuffle_seed", None),
96
+ parser=config.get("parser", "en"),
97
+ blank_index=config.get("blank_index", -1),
98
+ unk_index=config.get("unk_index", -1),
99
+ normalize=config.get("normalize", False),
100
+ normalize_text=config.get('normalize_text', False),
101
+ symbols_to_keep=config.get('symbols_to_keep', None),
102
+ pad_id=config.get('pad_id', 0),
103
+ bos_id=config.get('bos_id', None),
104
+ eos_id=config.get('eos_id', None),
105
+ )
106
+ else:
107
+ dataset = HFAudioToCharDataset(
108
+ labels=config["labels"],
109
+ audio_key=config.get('audio_key', 'audio.array'),
110
+ text_key=config["text_key"],
111
+ sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'),
112
+ hf_data_cfg=config["hf_data_cfg"],
113
+ sample_rate=config["sample_rate"],
114
+ augmentor=augmentor,
115
+ trim=config.get('trim_silence', False),
116
+ bos_id=config.get('bos_id', None),
117
+ eos_id=config.get('eos_id', None),
118
+ pad_id=config.get('pad_id', 0),
119
+ return_sample_id=config.get('return_sample_id', False),
120
+ id_key=config.get("id_key", None),
121
+ channel_selector=config.get('channel_selector', None),
122
+ normalize_db=config.get('normalize_db', None),
123
+ ref_channel=config.get('ref_channel', None),
124
+ parser=config.get("parser", "en"),
125
+ blank_index=config.get("blank_index", -1),
126
+ unk_index=config.get("unk_index", -1),
127
+ normalize=config.get("normalize", False),
128
+ normalize_text=config.get('normalize_text', False),
129
+ symbols_to_keep=config.get('symbols_to_keep', None),
130
+ )
131
+
132
+ return dataset
nemo/collections/asr/data/ssl_dataset.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import copy
16
+ import io
17
+ import json
18
+ import os
19
+ from dataclasses import dataclass
20
+ from math import isclose
21
+ from typing import Any, Dict, List, Optional, Union
22
+
23
+ import numpy as np
24
+ import torch
25
+ from lhotse.dataset import AudioSamples
26
+ from omegaconf import DictConfig, ListConfig, open_dict
27
+ from torch import Tensor
28
+
29
+ from nemo.collections.asr.data import audio_to_text, audio_to_text_dataset
30
+ from nemo.collections.asr.parts.preprocessing.perturb import WhiteNoisePerturbation, process_augmentations
31
+ from nemo.collections.asr.parts.preprocessing.segment import AudioSegment
32
+ from nemo.collections.asr.parts.utils.manifest_utils import read_manifest
33
+ from nemo.collections.common.data.dataset import ConcatDataset
34
+ from nemo.collections.common.parts.preprocessing.manifest import get_full_path
35
+ from nemo.core.classes import Serialization
36
+ from nemo.utils import logging
37
+
38
+
39
+ @dataclass
40
+ class AudioNoiseItem:
41
+ sample_id: str | None = None
42
+ audio: Union[Tensor, None] = None
43
+ audio_len: Union[Tensor, None] = None
44
+ noise: Union[Tensor, None] = None
45
+ noise_len: Union[Tensor, None] = None
46
+ noisy_audio: Union[Tensor, None] = None
47
+ noisy_audio_len: Union[Tensor, None] = None
48
+
49
+
50
+ @dataclass
51
+ class AudioNoiseBatch:
52
+ sample_id: list | None = None
53
+ audio: Union[Tensor, None] = None
54
+ audio_len: Union[Tensor, None] = None
55
+ noise: Union[Tensor, None] = None
56
+ noise_len: Union[Tensor, None] = None
57
+ noisy_audio: Union[Tensor, None] = None
58
+ noisy_audio_len: Union[Tensor, None] = None
59
+
60
+
61
+ def _parse_manifest_item(line: str, manifest_file: str) -> Dict[str, Any]:
62
+ """
63
+ Specialized function to parse the manifest file by ignoring text,
64
+ such that nemo dataset can save time on tokenizing text.
65
+ """
66
+ item = json.loads(line)
67
+
68
+ # Audio file
69
+ if 'audio_filename' in item:
70
+ item['audio_file'] = item.pop('audio_filename')
71
+ elif 'audio_filepath' in item:
72
+ item['audio_file'] = item.pop('audio_filepath')
73
+ else:
74
+ raise KeyError(f"No 'audio_filename' or 'audio_filepath' in manifest item: {item}")
75
+
76
+ item['audio_file'] = get_full_path(audio_file=item['audio_file'], manifest_file=manifest_file)
77
+
78
+ # Duration.
79
+ if 'duration' not in item:
80
+ item['duration'] = None
81
+
82
+ # dummy text
83
+ item['text'] = ""
84
+
85
+ item = dict(
86
+ audio_file=item['audio_file'],
87
+ duration=item['duration'],
88
+ text=item['text'],
89
+ offset=item.get('offset', None),
90
+ speaker=item.get('speaker', None),
91
+ orig_sr=item.get('orig_sample_rate', None),
92
+ token_labels=item.get('token_labels', None),
93
+ lang=item.get('lang', None),
94
+ )
95
+ return item
96
+
97
+
98
+ def _audio_noise_collate_fn(batch: List[AudioNoiseItem], batch_augmentor: Any = None) -> AudioNoiseBatch:
99
+ audios = [x.audio for x in batch]
100
+ audio_lengths = [x.audio_len for x in batch]
101
+ max_audio_len = max(audio_lengths).item()
102
+
103
+ noises = [x.noise for x in batch]
104
+ noise_lengths = [x.noise_len for x in batch]
105
+
106
+ noisy_audios = [x.noisy_audio for x in batch]
107
+ noisy_audio_lengths = [x.noisy_audio_len for x in batch]
108
+
109
+ audio_signal_list = []
110
+ noise_signal_list = []
111
+ noisy_audio_signal_list = []
112
+ for i, audio in enumerate(audios):
113
+ audio_len = audio.size(0)
114
+ if audio_len < max_audio_len:
115
+ pad = (0, max_audio_len - audio_len)
116
+ audio = torch.nn.functional.pad(audio, pad)
117
+ audio_signal_list.append(audio)
118
+
119
+ noise = noises[i]
120
+ noise_len = noise.size(0)
121
+ if noise_len < max_audio_len:
122
+ pad = (0, max_audio_len - noise_len)
123
+ noise = torch.nn.functional.pad(noise, pad)
124
+ noise_signal_list.append(noise[:max_audio_len])
125
+
126
+ noisy_audio = noisy_audios[i]
127
+ noisy_audio_len = noisy_audio.size(0)
128
+ if noisy_audio_len < max_audio_len:
129
+ pad = (0, max_audio_len - noisy_audio_len)
130
+ noisy_audio = torch.nn.functional.pad(noisy_audio, pad)
131
+ noisy_audio_signal_list.append(noisy_audio[:max_audio_len])
132
+
133
+ audio_signal = torch.stack(audio_signal_list).float()
134
+ audio_lengths = torch.stack(audio_lengths).long()
135
+ noise_signal = torch.stack(noise_signal_list).float()
136
+ noise_lengths = torch.stack(noise_lengths).long()
137
+ noisy_audio_signal = torch.stack(noisy_audio_signal_list).float()
138
+ noisy_audio_lengths = torch.stack(noisy_audio_lengths).long()
139
+
140
+ output = AudioNoiseBatch(
141
+ audio=audio_signal,
142
+ audio_len=audio_lengths,
143
+ noise=noise_signal,
144
+ noise_len=noise_lengths,
145
+ noisy_audio=noisy_audio_signal,
146
+ noisy_audio_len=noisy_audio_lengths,
147
+ )
148
+
149
+ if batch_augmentor is not None:
150
+ output = batch_augmentor(output)
151
+
152
+ return output
153
+
154
+
155
+ def load_noise_manifest(noise_manifest: Union[str, ListConfig, None]):
156
+ """
157
+ load noise manifest from a single or a list of manifest files
158
+ """
159
+ if noise_manifest is None:
160
+ return []
161
+
162
+ if isinstance(noise_manifest, str):
163
+ noise_manifest = noise_manifest.split(',')
164
+
165
+ noise_data = []
166
+ for manifest in noise_manifest:
167
+ curr_data = read_manifest(manifest)
168
+ for i in range(len(curr_data)):
169
+ curr_data[i]['audio_filepath'] = get_full_path(curr_data[i]['audio_filepath'], manifest)
170
+ noise_data.extend(curr_data)
171
+ return noise_data
172
+
173
+
174
+ def load_noise_audio(
175
+ sample: Dict[str, Any],
176
+ sample_rate: int,
177
+ max_audio_len: Optional[int] = None,
178
+ pad_to_max: bool = True,
179
+ min_white_noise_db: int = -90,
180
+ max_white_noise_db: int = -46,
181
+ max_trial: int = 100,
182
+ ):
183
+ """
184
+ Load noise audio from the manifest item, and apply white noise if the loaded noise audio is empty.
185
+ Args:
186
+ sample: a sample from the noise manifest
187
+ sample_rate: target sample rate to resample the noise audio
188
+ max_audio_len: the maximum audio length to load
189
+ pad_to_max: whether to pad the audio to max_audio_len
190
+ min_white_noise_db: the minimum white noise level in dB
191
+ max_white_noise_db: the maximum white noise level in dB
192
+ max_trial: the maximum number of trials to load noise audio before giving up
193
+ Returns:
194
+ noise: the loaded noise audio
195
+ noise_len: the length of the loaded noise audio
196
+ """
197
+ max_dur = None if max_audio_len is None else max_audio_len / sample_rate
198
+ duration = sample.get('duration', None)
199
+ offset = sample.get('offset', 0.0)
200
+
201
+ if max_dur is not None and duration is not None and duration > max_dur:
202
+ cnt = 0
203
+ while cnt < max_trial:
204
+ # randomly sample a segment of the noise
205
+ offset = np.random.uniform(0, duration - max_dur)
206
+
207
+ audio_segment = AudioSegment.from_file(
208
+ audio_file=sample['audio_filepath'],
209
+ offset=offset,
210
+ duration=max_dur,
211
+ target_sr=sample_rate,
212
+ )
213
+
214
+ if sum(audio_segment.samples) > 0:
215
+ # break if the segment is not empty
216
+ break
217
+ cnt += 1
218
+ else:
219
+ audio_segment = AudioSegment.from_file(
220
+ audio_file=sample['audio_filepath'],
221
+ offset=offset,
222
+ duration=duration,
223
+ target_sr=sample_rate,
224
+ )
225
+
226
+ if sum(audio_segment.samples) == 0:
227
+ logging.warning(
228
+ f"Loaded noise audio is empty: {sample}, with sampled offset={offset}, duration={max_dur}. Adding white noise."
229
+ )
230
+ WhiteNoisePerturbation(min_level=min_white_noise_db, max_level=max_white_noise_db).perturb(audio_segment)
231
+
232
+ noise = torch.tensor(audio_segment.samples, dtype=torch.float)
233
+ noise_len = torch.tensor(noise.size(0)).long()
234
+ # pad to max_audio_len if necessary
235
+ if max_audio_len is not None and pad_to_max:
236
+ if noise.size(0) < max_audio_len:
237
+ pad = (0, max_audio_len - noise.size(0))
238
+ noise = torch.nn.functional.pad(noise, pad)
239
+ else:
240
+ noise = noise[:max_audio_len]
241
+ noise_len = torch.tensor(max_audio_len).long()
242
+ return noise, noise_len
243
+
244
+
245
+ def sample_noise(noise_data: List[Dict], sample_rate: int, max_audio_len: int | None = None, max_trial: int = 20):
246
+ """
247
+ Randomly sample noise audio from the noise manifest.
248
+ Args:
249
+ noise_data: the noise manifest data
250
+ sample_rate: target sample rate to resample the noise audio
251
+ max_audio_len: the maximum audio length to load
252
+ max_trial: the maximum number of trials to load noise audio before giving up
253
+ Returns:
254
+ noise_audio: the sampled noise audio
255
+ noise_len: the length of the sampled noise audio
256
+ """
257
+ cnt = 0
258
+ noise_audio = torch.zeros(max_audio_len).float()
259
+ noise_len = torch.tensor(max_audio_len).long()
260
+ while cnt < max_trial and len(noise_data) > 0:
261
+ try:
262
+ noise_sample = noise_data[np.random.randint(len(noise_data))]
263
+ noise_audio, noise_len = load_noise_audio(noise_sample, sample_rate, max_audio_len)
264
+ break
265
+ except Exception as e:
266
+ logging.warning(f"Error loading noise audio with config {noise_sample} and exception: {e}, retrying.")
267
+ cnt += 1
268
+ if cnt == max_trial:
269
+ logging.warning(f"Failed to load noise audio after {max_trial} attempts, returning zero noise.")
270
+ return torch.zeros(max_audio_len).float(), torch.tensor(max_audio_len).long()
271
+ return noise_audio, noise_len
272
+
273
+
274
+ def pad_audio(audio: Tensor, min_len: int, pad_audio_mode) -> Tensor:
275
+ """
276
+ Pad audio to min_len with the specified mode
277
+ Args:
278
+ audio: the input audio tensor
279
+ min_len: the minimum length to pad to
280
+ pad_audio_mode: the padding mode, either 'repeat' or 'zero'
281
+ Returns:
282
+ audio: the padded audio tensor
283
+ """
284
+ allowed_mode = ['repeat', 'zero']
285
+ if audio.size(0) < min_len:
286
+ if pad_audio_mode == 'repeat' and audio.size(0) > 0:
287
+ num_repeats = int(np.ceil(min_len / audio.size(0)))
288
+ audio = audio.repeat(num_repeats)[:min_len]
289
+ elif pad_audio_mode == 'zero' or audio.size(0) == 0:
290
+ audio = torch.nn.functional.pad(audio, (0, min_len - audio.size(0)))
291
+ else:
292
+ raise ValueError(f"Unsupported pad_audio_mode: {pad_audio_mode}, must be one of {allowed_mode}")
293
+ return audio
294
+
295
+
296
+ class AudioNoiseDataset(audio_to_text.AudioToCharDataset):
297
+ @property
298
+ def output_types(self):
299
+ # disable type checking for since it doesn't support dataclass
300
+ return None
301
+
302
+ def __init__(
303
+ self,
304
+ noise_manifest: str | None = None,
305
+ batch_augmentor: Any | None = None,
306
+ min_audio_len_secs: float = 1.0,
307
+ pad_audio_mode: str = 'repeat',
308
+ **kwargs,
309
+ ):
310
+ # add bos_id=0 to avoid empty text token
311
+ super().__init__(bos_id=0, manifest_parse_func=_parse_manifest_item, **kwargs)
312
+ self.noise_manifest = noise_manifest
313
+ self.batch_augmentor = batch_augmentor
314
+ self.noise_data = load_noise_manifest(noise_manifest)
315
+ self.min_audio_len_secs = min_audio_len_secs
316
+ self.pad_audio_mode = pad_audio_mode
317
+
318
+ def __getitem__(self, index) -> AudioNoiseItem:
319
+ sample = self.manifest_processor.collection[index]
320
+ offset = sample.offset
321
+
322
+ if offset is None:
323
+ offset = 0
324
+
325
+ audio = self.featurizer.process(
326
+ sample.audio_file,
327
+ offset=offset,
328
+ duration=sample.duration,
329
+ trim=self.trim,
330
+ orig_sr=sample.orig_sr,
331
+ channel_selector=self.channel_selector,
332
+ )
333
+ if audio.size(0) == 0:
334
+ logging.warning(f"Loaded audio has zero length: {sample}.")
335
+
336
+ min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate)
337
+ audio = pad_audio(audio, min_len, self.pad_audio_mode)
338
+ audio_len = torch.tensor(audio.shape[0]).long()
339
+ noise, noise_len = sample_noise(self.noise_data, self.featurizer.sample_rate, audio_len.item())
340
+
341
+ item = AudioNoiseItem(
342
+ sample_id=str(index),
343
+ audio=audio,
344
+ audio_len=audio_len,
345
+ noise=noise,
346
+ noise_len=noise_len,
347
+ noisy_audio=audio + noise,
348
+ noisy_audio_len=audio_len,
349
+ )
350
+ return item
351
+
352
+ def _collate_fn(self, batch: List[AudioNoiseItem]) -> AudioNoiseBatch:
353
+ return _audio_noise_collate_fn(batch, self.batch_augmentor)
354
+
355
+
356
+ class TarredAudioNoiseDataset(audio_to_text.TarredAudioToCharDataset):
357
+ @property
358
+ def output_types(self):
359
+ # disable type checking for since it doesn't support dataclass
360
+ return None
361
+
362
+ def __init__(
363
+ self,
364
+ noise_manifest: str | None = None,
365
+ batch_augmentor: Any | None = None,
366
+ min_audio_len_secs: float = 1.0,
367
+ pad_audio_mode: str = 'repeat',
368
+ **kwargs,
369
+ ):
370
+ """
371
+ Args:
372
+ noise_manifest: the noise manifest file
373
+ batch_augmentor: the batch augmentor
374
+ min_audio_len_secs: the minimum audio length in seconds, audios shorter than this will be padded
375
+ pad_audio_mode: the padding mode for audios shorter than min_audio_len_secs, either 'repeat' or 'zero'
376
+ **kwargs: other arguments for TarredAudioToCharDataset
377
+
378
+ """
379
+ super().__init__(bos_id=0, manifest_parse_func=_parse_manifest_item, **kwargs)
380
+ self.noise_manifest = noise_manifest
381
+ self.batch_augmentor = batch_augmentor
382
+ self.noise_data = load_noise_manifest(noise_manifest)
383
+ self.min_audio_len_secs = min_audio_len_secs
384
+ self.pad_audio_mode = pad_audio_mode
385
+
386
+ def _build_sample(self, tup):
387
+ """Builds the training sample by combining the data from the WebDataset with the manifest info."""
388
+ audio_bytes, audio_filename, offset_id = tup
389
+
390
+ # Grab manifest entry from self.manifest_preprocessor.collection
391
+ file_id, _ = os.path.splitext(os.path.basename(audio_filename))
392
+ manifest_idx = self.manifest_processor.collection.mapping[file_id][offset_id]
393
+ manifest_entry = self.manifest_processor.collection[manifest_idx]
394
+
395
+ offset = manifest_entry.offset
396
+ if offset is None:
397
+ offset = 0
398
+
399
+ try:
400
+ # Convert audio bytes to IO stream for processing (for SoundFile to read)
401
+ audio_filestream = io.BytesIO(audio_bytes)
402
+ audio = self.featurizer.process(
403
+ audio_filestream,
404
+ offset=offset,
405
+ duration=manifest_entry.duration,
406
+ trim=self.trim,
407
+ orig_sr=manifest_entry.orig_sr,
408
+ )
409
+ audio_filestream.close()
410
+ except Exception as e:
411
+ raise RuntimeError(f"Error reading audio sample: {manifest_entry}, with exception: {e}.")
412
+
413
+ min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate)
414
+ audio = pad_audio(audio, min_len, self.pad_audio_mode)
415
+ audio_len = torch.tensor(audio.shape[0]).long()
416
+ noise, noise_len = sample_noise(self.noise_data, self.featurizer.sample_rate, audio_len.item())
417
+
418
+ item = AudioNoiseItem(
419
+ sample_id=str(manifest_idx),
420
+ audio=audio,
421
+ audio_len=audio_len,
422
+ noise=noise,
423
+ noise_len=noise_len,
424
+ noisy_audio=audio + noise,
425
+ noisy_audio_len=audio_len,
426
+ )
427
+ return item
428
+
429
+ def _pad_audio(self, audio: Tensor) -> Tensor:
430
+ min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate)
431
+ if audio.size(0) < min_len:
432
+ if self.pad_audio_mode == 'repeat':
433
+ num_repeats = int(np.ceil(min_len / audio.size(0)))
434
+ audio = audio.repeat(num_repeats)[:min_len]
435
+ elif self.pad_audio_mode == 'zero':
436
+ audio = torch.nn.functional.pad(audio, (0, min_len - audio.size(0)))
437
+ else:
438
+ raise ValueError(
439
+ f"Unsupported pad_audio_mode: {self.pad_audio_mode}, must be one of ['repeat', 'zero']"
440
+ )
441
+ return audio
442
+
443
+ def _collate_fn(self, batch: List[AudioNoiseItem]) -> AudioNoiseBatch:
444
+ return _audio_noise_collate_fn(batch, self.batch_augmentor)
445
+
446
+
447
+ class LhotseAudioNoiseDataset(torch.utils.data.Dataset):
448
+ def __init__(self, noise_manifest: str | None = None, batch_augmentor_cfg: DictConfig = None):
449
+ super().__init__()
450
+
451
+ if batch_augmentor_cfg:
452
+ batch_augmentor = Serialization.from_config_dict(batch_augmentor_cfg)
453
+ else:
454
+ batch_augmentor = None
455
+
456
+ self.batch_augmentor = batch_augmentor
457
+ self.noise_data = load_noise_manifest(noise_manifest)
458
+ self.load_audio = AudioSamples(fault_tolerant=True)
459
+
460
+ def __getitem__(self, cuts):
461
+
462
+ audios, audio_lens, cuts = self.load_audio(cuts)
463
+ sampled_noises = [sample_noise(self.noise_data, cut.sampling_rate, cut.num_samples) for cut in cuts]
464
+
465
+ items = [
466
+ AudioNoiseItem(
467
+ sample_id=str(cuts[i].id),
468
+ audio=audios[i],
469
+ audio_len=audio_lens[i],
470
+ noise=sampled_noises[i][0],
471
+ noise_len=sampled_noises[i][1],
472
+ noisy_audio=audios[i] + sampled_noises[i][0],
473
+ noisy_audio_len=audio_lens[i],
474
+ )
475
+ for i in range(len(cuts))
476
+ ]
477
+ return _audio_noise_collate_fn(items, self.batch_augmentor)
478
+
479
+
480
+ def get_audio_noise_dataset(
481
+ config: Dict[str, Any], augmentor: Any = None, batch_augmentor: Any = None
482
+ ) -> AudioNoiseDataset:
483
+ dataset = AudioNoiseDataset(
484
+ noise_manifest=config.get('noise_manifest', None),
485
+ batch_augmentor=batch_augmentor,
486
+ manifest_filepath=config['manifest_filepath'],
487
+ labels=config.get('labels', None),
488
+ sample_rate=config['sample_rate'],
489
+ int_values=config.get('int_values', False),
490
+ augmentor=augmentor,
491
+ max_duration=config.get('max_duration', None),
492
+ min_duration=config.get('min_duration', None),
493
+ trim=config.get('trim_silence', False),
494
+ channel_selector=config.get('channel_selector', None),
495
+ )
496
+ return dataset
497
+
498
+
499
+ def get_concat_audio_noise_dataset(
500
+ config: Dict[str, Any], global_rank: int, world_size: int, augmentor: Any = None, batch_augmentor: Any = None
501
+ ) -> ConcatDataset:
502
+ manifest_filepaths = config['manifest_filepath']
503
+ datasets = []
504
+
505
+ # needed to support validation Concat Datasets that arrive here as
506
+ # [[dataset1,dataset2]] otherwise ModelPT would interfere
507
+ if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str):
508
+ logging.info(f"removing an extra nesting level from {manifest_filepaths}")
509
+ manifest_filepaths = config['manifest_filepath'][0]
510
+
511
+ for manifest_filepath in manifest_filepaths:
512
+ conf = copy.deepcopy(config)
513
+ conf['manifest_filepath'] = manifest_filepath
514
+
515
+ dataset = get_audio_noise_dataset(config=conf, augmentor=augmentor)
516
+ datasets.append(dataset)
517
+
518
+ dataset = ConcatDataset(
519
+ datasets,
520
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
521
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
522
+ sampling_scale=config.get('concat_sampling_scale', 1),
523
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
524
+ shuffle=config.get('concat_shuffle', True),
525
+ seed=config.get('concat_sampling_seed', None),
526
+ global_rank=global_rank,
527
+ world_size=world_size,
528
+ )
529
+ return dataset
530
+
531
+
532
+ def get_tarred_audio_noise_dataset(config, shuffle_n, global_rank, world_size, augmentor, batch_augmentor: Any = None):
533
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
534
+ manifest_filepaths = config['manifest_filepath']
535
+ datasets = []
536
+ tarred_audio_filepaths = audio_to_text_dataset.convert_to_config_list(tarred_audio_filepaths)
537
+ manifest_filepaths = audio_to_text_dataset.convert_to_config_list(manifest_filepaths)
538
+
539
+ bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets
540
+ if bucketing_weights:
541
+ for idx, weight in enumerate(bucketing_weights):
542
+ if not isinstance(weight, int) or weight <= 0:
543
+ raise ValueError("bucket weights must be positive integers")
544
+
545
+ if len(manifest_filepaths) != len(tarred_audio_filepaths):
546
+ raise ValueError(
547
+ f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets."
548
+ )
549
+
550
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
551
+ zip(tarred_audio_filepaths, manifest_filepaths)
552
+ ):
553
+ if len(tarred_audio_filepath) == 1:
554
+ tarred_audio_filepath = tarred_audio_filepath[0]
555
+ if len(manifest_filepath) == 1:
556
+ manifest_filepath = manifest_filepath[0]
557
+
558
+ is_sharded_manifest = True if "_OP_" in manifest_filepath and "_CL_" in manifest_filepath else False
559
+ logging.info(
560
+ f"Loading TarredAudioNoiseDataset from {tarred_audio_filepath} and {manifest_filepath}, shard={is_sharded_manifest}"
561
+ )
562
+ dataset = TarredAudioNoiseDataset(
563
+ noise_manifest=config.get('noise_manifest', None),
564
+ batch_augmentor=batch_augmentor,
565
+ audio_tar_filepaths=tarred_audio_filepath,
566
+ manifest_filepath=manifest_filepath,
567
+ labels=config.get('labels', None),
568
+ sample_rate=config['sample_rate'],
569
+ int_values=config.get('int_values', False),
570
+ augmentor=augmentor,
571
+ shuffle_n=shuffle_n,
572
+ max_duration=config.get('max_duration', None),
573
+ min_duration=config.get('min_duration', None),
574
+ trim=config.get('trim_silence', False),
575
+ shard_strategy=config.get('tarred_shard_strategy', 'scatter'),
576
+ shard_manifests=is_sharded_manifest,
577
+ global_rank=global_rank,
578
+ world_size=world_size,
579
+ )
580
+ if bucketing_weights:
581
+ [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])]
582
+ else:
583
+ datasets.append(dataset)
584
+
585
+ return audio_to_text_dataset.get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank)
586
+
587
+
588
+ def get_concat_tarred_audio_noise_dataset(
589
+ config, shuffle_n, global_rank, world_size, augmentor, batch_augmentor: Any = None
590
+ ):
591
+ tarred_audio_filepaths = config['tarred_audio_filepaths']
592
+ manifest_filepaths = config['manifest_filepath']
593
+ datasets = []
594
+ for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate(
595
+ zip(tarred_audio_filepaths, manifest_filepaths)
596
+ ):
597
+ conf = copy.deepcopy(config)
598
+ conf['manifest_filepath'] = manifest_filepath
599
+ conf['tarred_audio_filepaths'] = tarred_audio_filepath
600
+ dataset = get_tarred_audio_noise_dataset(
601
+ config=conf,
602
+ shuffle_n=shuffle_n,
603
+ global_rank=global_rank,
604
+ world_size=world_size,
605
+ augmentor=augmentor,
606
+ batch_augmentor=batch_augmentor,
607
+ )
608
+ datasets.append(dataset)
609
+
610
+ dataset = ConcatDataset(
611
+ datasets,
612
+ sampling_technique=config.get('concat_sampling_technique', 'temperature'),
613
+ sampling_temperature=config.get('concat_sampling_temperature', 5),
614
+ sampling_scale=config.get('concat_sampling_scale', 1),
615
+ sampling_probabilities=config.get('concat_sampling_probabilities', None),
616
+ shuffle=config.get('concat_shuffle', True),
617
+ seed=config.get('concat_sampling_seed', None),
618
+ global_rank=global_rank,
619
+ world_size=world_size,
620
+ )
621
+ return dataset
622
+
623
+
624
+ def get_audio_noise_dataset_from_config(
625
+ config,
626
+ global_rank: int,
627
+ world_size: int,
628
+ ):
629
+ if 'augmentor' in config:
630
+ augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size)
631
+ else:
632
+ augmentor = None
633
+
634
+ if 'batch_augmentor' in config:
635
+ batch_augmentor = Serialization.from_config_dict(config['batch_augmentor'])
636
+ else:
637
+ batch_augmentor = None
638
+
639
+ is_concat = config.get('is_concat', False)
640
+ if is_concat:
641
+ if config.get('concat_sampling_technique', None) is None:
642
+ logging.warning(
643
+ f"Concat dataset requires `concat_sampling_technique` but it was not provided, using round-robin. Config: {config}"
644
+ )
645
+ config['concat_sampling_technique'] = 'round-robin'
646
+
647
+ if config['concat_sampling_technique'] == 'random':
648
+ if not 'concat_sampling_probabilities' in config:
649
+ logging.warning(
650
+ f"Concat dataset requires `concat_sampling_probabilities` list, using uniform weights. Config: {config}"
651
+ )
652
+ with open_dict(config):
653
+ config['concat_sampling_probabilities'] = [1 / len(config['manifest_filepath'])] * len(
654
+ config['manifest_filepath']
655
+ )
656
+ elif not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6):
657
+ raise ValueError(
658
+ f"`concat_sampling_probabilities` need to sum to 1 with 1e-6 tolerance. Config: {config}"
659
+ )
660
+
661
+ shuffle = config['shuffle']
662
+ if config.get('is_tarred', False):
663
+ if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or (
664
+ 'manifest_filepath' in config and config['manifest_filepath'] is None
665
+ ):
666
+ logging.warning(
667
+ "Could not load dataset as `manifest_filepath` was None or "
668
+ f"`tarred_audio_filepaths` is None. Provided config : {config}"
669
+ )
670
+ return None
671
+
672
+ shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0
673
+ if is_concat:
674
+ dataset = get_concat_tarred_audio_noise_dataset(
675
+ config=config,
676
+ shuffle_n=shuffle_n,
677
+ global_rank=global_rank,
678
+ world_size=world_size,
679
+ augmentor=augmentor,
680
+ batch_augmentor=batch_augmentor,
681
+ )
682
+ else:
683
+ dataset = get_tarred_audio_noise_dataset(
684
+ config=config,
685
+ shuffle_n=shuffle_n,
686
+ global_rank=global_rank,
687
+ world_size=world_size,
688
+ augmentor=augmentor,
689
+ batch_augmentor=batch_augmentor,
690
+ )
691
+ else:
692
+ if 'manifest_filepath' in config and config['manifest_filepath'] is None:
693
+ logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}")
694
+ return None
695
+ if is_concat:
696
+ dataset = get_concat_audio_noise_dataset(
697
+ config=config,
698
+ global_rank=global_rank,
699
+ world_size=world_size,
700
+ augmentor=augmentor,
701
+ batch_augmentor=batch_augmentor,
702
+ )
703
+ else:
704
+ dataset = get_audio_noise_dataset(config=config, augmentor=augmentor, batch_augmentor=batch_augmentor)
705
+ return dataset
nemo/collections/asr/data/text_to_text.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import concurrent.futures
18
+ import copy
19
+ import gc
20
+ import json
21
+ import math
22
+ import random
23
+ from pathlib import Path
24
+ from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.utils.data
29
+ from torch.nn.utils.rnn import pad_sequence
30
+ from tqdm.auto import tqdm
31
+
32
+ from nemo.collections.asr.data.audio_to_text import _speech_collate_fn
33
+ from nemo.collections.common.tokenizers import TokenizerSpec
34
+ from nemo.core.classes import Dataset, IterableDataset
35
+ from nemo.utils import logging
36
+
37
+ try:
38
+ from nemo_text_processing.text_normalization.normalize import Normalizer
39
+ except Exception as e:
40
+ pass # Normalizer imported only for annotation purposes, error can be ignored
41
+
42
+ AnyPath = Union[Path, str]
43
+
44
+
45
+ class TextToTextItem(NamedTuple):
46
+ tts_text: torch.Tensor # normalized and tokenized text for TTS
47
+ transcript: torch.Tensor # tokenized text for ASR
48
+ speaker: int # speaker id for multi-speaker TTS
49
+
50
+
51
+ class TextToTextBatch(NamedTuple):
52
+ tts_texts: torch.Tensor # tokenized texts for tts
53
+ tts_text_lengths: torch.Tensor
54
+ transcripts: torch.Tensor # tokenized texts for ASR
55
+ transcript_lengths: torch.Tensor
56
+ speakers: torch.Tensor # speaker ids for multi-speaker TTS
57
+
58
+ @staticmethod
59
+ def collate_fn(batch: List[TextToTextItem], asr_pad_id: int, tts_text_pad_id: int) -> TextToTextBatch:
60
+ return TextToTextBatch(
61
+ tts_texts=pad_sequence([item.tts_text for item in batch], batch_first=True, padding_value=tts_text_pad_id),
62
+ tts_text_lengths=torch.tensor([item.tts_text.shape[0] for item in batch]).long(),
63
+ transcripts=pad_sequence([item.transcript for item in batch], batch_first=True, padding_value=asr_pad_id),
64
+ transcript_lengths=torch.tensor([item.transcript.shape[0] for item in batch]).long(),
65
+ speakers=torch.tensor([item.speaker for item in batch]).long(),
66
+ )
67
+
68
+
69
+ class TextOrAudioToTextBatch(NamedTuple):
70
+ audio_signals: torch.Tensor
71
+ audio_signal_lengths: torch.Tensor
72
+ tts_texts: torch.Tensor
73
+ tts_text_lengths: torch.Tensor
74
+ speakers: torch.Tensor
75
+ transcripts: torch.Tensor
76
+ transcript_lengths: torch.Tensor
77
+
78
+ @staticmethod
79
+ def collate_fn(
80
+ batch: List[Union[TextToTextItem, tuple]], tts_text_pad_id: int, asr_pad_id: int
81
+ ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]:
82
+ """
83
+ Collate function for dataloader
84
+ Can accept mixed batch of text-to-text items and audio-text items (typical for ASR)
85
+ """
86
+ text_items: List[TextToTextItem] = [item for item in batch if isinstance(item, TextToTextItem)]
87
+ if not text_items:
88
+ # pure audio-text batch
89
+ return _speech_collate_fn(batch=batch, pad_id=asr_pad_id)
90
+
91
+ asr_items = [item for item in batch if not isinstance(item, TextToTextItem)]
92
+
93
+ if not asr_items:
94
+ # pure text-to-text batch
95
+ return TextToTextBatch.collate_fn(batch=text_items, asr_pad_id=asr_pad_id, tts_text_pad_id=tts_text_pad_id)
96
+
97
+ # mixed batch
98
+
99
+ # each asr item is a tuple:
100
+ # audio_signal (0), audio_length (1), transcript (2), transcript_length (3), sample_id (4, optional)
101
+ audio_signals = pad_sequence([item[0] for item in asr_items], batch_first=True, padding_value=0.0)
102
+ audio_signal_lengths = torch.tensor([item[1] for item in asr_items]).long()
103
+
104
+ tts_texts = pad_sequence(
105
+ [item.tts_text for item in text_items], batch_first=True, padding_value=tts_text_pad_id
106
+ )
107
+ tts_text_lengths = torch.tensor([item.tts_text.shape[0] for item in text_items]).long()
108
+ speakers = torch.tensor([item.speaker for item in text_items]).long()
109
+
110
+ transcripts = pad_sequence(
111
+ [item.transcript for item in text_items] + [item[2] for item in asr_items],
112
+ batch_first=True,
113
+ padding_value=asr_pad_id,
114
+ )
115
+ transcript_lengths = torch.tensor(
116
+ [item.transcript.shape[0] for item in text_items] + [item[3] for item in asr_items]
117
+ ).long()
118
+
119
+ return TextOrAudioToTextBatch(
120
+ audio_signals=audio_signals,
121
+ audio_signal_lengths=audio_signal_lengths,
122
+ tts_texts=tts_texts,
123
+ tts_text_lengths=tts_text_lengths,
124
+ speakers=speakers,
125
+ transcripts=transcripts,
126
+ transcript_lengths=transcript_lengths,
127
+ )
128
+
129
+
130
+ def _asr_text_to_tokens(text: str) -> np.ndarray:
131
+ """
132
+ Helper function for asr tokenization with multiprocessing pool only.
133
+ Must be defined on the top level.
134
+ Expects asr_tokenizer_global, asr_bos_id_global, asr_eos_id_global to exist in the current pool process
135
+ """
136
+ ids = asr_tokenizer_global.text_to_ids(text)
137
+ if asr_bos_id_global is not None:
138
+ ids = [asr_bos_id_global] + ids
139
+ if asr_eos_id_global is not None:
140
+ ids.append(asr_eos_id_global)
141
+ return np.asarray(ids)
142
+
143
+
144
+ def _tts_text_to_tokens(text: str) -> np.ndarray:
145
+ """
146
+ Helper function for asr tokenization with multiprocessing pool only.
147
+ Must be defined on the top level.
148
+ Expects tts_tokenizer_global to exist in the current pool process
149
+ """
150
+ return np.asarray(tts_tokenizer_global(text))
151
+
152
+
153
+ def _iterate_manifest(filepath: AnyPath) -> Iterable[Dict[str, Any]]:
154
+ """
155
+ Helper function to iterate manifest
156
+ """
157
+ with open(filepath, "r", encoding="utf-8") as f:
158
+ for line in f:
159
+ record = json.loads(line)
160
+ yield record
161
+
162
+
163
+ class TextToTextDatasetBase:
164
+ """
165
+ Base class for loading text-to-text manifests
166
+ Map-style and Iterable datasets should inherit this class
167
+ """
168
+
169
+ asr_pad_id: int
170
+ tts_text_pad_id: int
171
+ asr_bos_id: Optional[int] = None
172
+ asr_eos_id: Optional[int] = None
173
+ data: List[Dict[str, Any]]
174
+
175
+ def __init__(
176
+ self,
177
+ manifest_filepath: Union[AnyPath, List[AnyPath]],
178
+ speakers_filepath: Union[AnyPath, List[AnyPath]],
179
+ asr_tokenizer: TokenizerSpec,
180
+ asr_use_start_end_token: bool,
181
+ tts_parser: Callable,
182
+ tts_text_pad_id: int,
183
+ tts_text_normalizer: "Normalizer",
184
+ tts_text_normalizer_call_kwargs: Dict,
185
+ min_words: int = 1,
186
+ max_words: int = 1_000_000,
187
+ tokenizer_workers: int = 1,
188
+ num_parts: int = 1,
189
+ current_part_index: int = 0,
190
+ ):
191
+ super().__init__()
192
+ # ASR tokenizer setup
193
+ if asr_use_start_end_token and hasattr(asr_tokenizer, 'bos_token'):
194
+ self.asr_bos_id = asr_tokenizer.bos_id
195
+
196
+ if asr_use_start_end_token and hasattr(asr_tokenizer, 'eos_token'):
197
+ self.asr_eos_id = asr_tokenizer.eos_id
198
+
199
+ if hasattr(asr_tokenizer, 'pad_token'):
200
+ self.asr_pad_id = asr_tokenizer.pad_id
201
+ else:
202
+ self.asr_pad_id = 0
203
+
204
+ self.asr_tokenizer = asr_tokenizer
205
+
206
+ # TTS tokenizer setup
207
+ self.tts_parser = tts_parser
208
+ self.tts_normalizer = tts_text_normalizer
209
+ self.tts_normalizer_kwargs = tts_text_normalizer_call_kwargs
210
+ self.tts_text_pad_id = tts_text_pad_id
211
+
212
+ # Load speakers
213
+ if isinstance(speakers_filepath, str):
214
+ speakers_filepath = speakers_filepath.split(",")
215
+ elif isinstance(speakers_filepath, Path):
216
+ speakers_filepath = [speakers_filepath]
217
+ speakers: Set[int] = set()
218
+ for filepath in speakers_filepath:
219
+ with open(Path(filepath).expanduser(), "r") as f:
220
+ speakers.update(map(int, f.read().split()))
221
+ self.speakers = np.asarray(sorted(speakers))
222
+ logging.info(f"Loaded {len(self.speakers)} speakers")
223
+
224
+ # Load manifest
225
+ if isinstance(manifest_filepath, str):
226
+ manifest_filepath = manifest_filepath.split(",")
227
+ elif isinstance(manifest_filepath, Path):
228
+ manifest_filepath = [manifest_filepath]
229
+ self.manifest_paths = [Path(filepath) for filepath in manifest_filepath]
230
+
231
+ num_skipped_words = 0
232
+ num_skipped_utterances = 0
233
+ asr_texts = []
234
+ tts_texts = []
235
+ need_normalization = False
236
+
237
+ for manifest_path in self.manifest_paths:
238
+ for tmp_item in tqdm(_iterate_manifest(manifest_path)):
239
+ text = tmp_item["text"]
240
+ num_words = len(text.split())
241
+ # skip if number of works not in desired range
242
+ # TODO: maybe it would be valuable to sample sub-utterances from long utterances
243
+ if not (min_words <= num_words <= max_words):
244
+ num_skipped_words += num_words
245
+ num_skipped_utterances += 1
246
+ continue
247
+ asr_texts.append(tmp_item["text"])
248
+ if "tts_text_normalized" in tmp_item:
249
+ tts_texts.append(tmp_item["tts_text_normalized"])
250
+ else:
251
+ tts_texts.append(tmp_item["tts_text"])
252
+ need_normalization = True
253
+
254
+ if need_normalization:
255
+ logging.warning("TTS normalization is extremely slow! It is recommended to normalize TTS text")
256
+
257
+ if num_skipped_utterances:
258
+ logging.warning(f"Skipped {num_skipped_utterances} utterances " f"with {num_skipped_words}")
259
+
260
+ num_utterances = len(asr_texts)
261
+ # preprocessing is very costly, if we need only part - remove unnecessary utterances
262
+ if num_parts > 1:
263
+ # NB: floor division, full dataset can contain fewer utterances than original, like in tarred dataset
264
+ num_utterances_part = num_utterances // num_parts
265
+ start = num_utterances_part * current_part_index
266
+ end = start + num_utterances_part
267
+ logging.info(
268
+ f"Taking part of the dataset: {current_part_index} index, total {num_parts} from {start} to {end}"
269
+ )
270
+ asr_texts = asr_texts[start:end]
271
+ tts_texts = tts_texts[start:end]
272
+ num_utterances = num_utterances_part
273
+
274
+ self.data = [dict() for _ in range(num_utterances)]
275
+
276
+ if len(asr_texts) == 0:
277
+ # no data was loaded
278
+ logging.warning("Text-to-text dataset is empty")
279
+ return
280
+
281
+ if tokenizer_workers == 1:
282
+ logging.warning(
283
+ "Preprocessing large text with tokenizer_workers=1 may be slow with TTS tokenizer. "
284
+ "Prefer tokenizer_workers=(num_cpu_cores/num_gpus_per_node)"
285
+ )
286
+ for i, tokenized_text in enumerate(
287
+ tqdm((self._asr_text_to_tokens(text) for text in asr_texts), total=len(asr_texts))
288
+ ):
289
+ self.data[i]["asr_text_tokens"] = tokenized_text
290
+ else:
291
+ # Multiprocessing hack: use global variables for every process (not really global in program context)
292
+ def _init_asr_tokenize_process(tokenizer, bos_id, eos_id):
293
+ global asr_tokenizer_global, asr_bos_id_global, asr_eos_id_global # process-global
294
+ # deepcopy to avoid serialization of parent models
295
+ asr_tokenizer_global = copy.deepcopy(tokenizer)
296
+ asr_bos_id_global = copy.deepcopy(bos_id)
297
+ asr_eos_id_global = copy.deepcopy(eos_id)
298
+
299
+ with concurrent.futures.ProcessPoolExecutor(
300
+ initializer=_init_asr_tokenize_process,
301
+ initargs=(asr_tokenizer, self.asr_bos_id, self.asr_eos_id),
302
+ max_workers=tokenizer_workers,
303
+ ) as pool:
304
+ # chunk size for pool map is empirically chosen as a trade-off between speed and responsiveness
305
+ for i, tokenized_text in enumerate(
306
+ tqdm(pool.map(_asr_text_to_tokens, asr_texts, chunksize=1000), total=len(asr_texts))
307
+ ):
308
+ self.data[i]["asr_text_tokens"] = tokenized_text
309
+ # force free memory
310
+ del asr_texts
311
+ gc.collect()
312
+
313
+ if tokenizer_workers == 1:
314
+ logging.warning(
315
+ "Preprocessing large text with tokenizer_workers=1 may be slow with TTS tokenizer. "
316
+ "Prefer tokenizer_workers=(num_cpu_cores/num_gpus_per_node)"
317
+ )
318
+ for i, tokenized_text in enumerate(
319
+ tqdm(
320
+ (self._tts_text_to_tokens(text, normalize=need_normalization) for text in tts_texts),
321
+ total=len(tts_texts),
322
+ )
323
+ ):
324
+ self.data[i]["tts_text_tokens"] = tokenized_text
325
+ else:
326
+ if need_normalization:
327
+ # TODO: implement, if we really need normalization inplace
328
+ raise NotImplementedError(
329
+ "Normalization with tokenizer_workers > 1 is not implemented. "
330
+ "It is not recommended to use normalization on the fly at all, since it's extremely slow"
331
+ )
332
+
333
+ def _init_tts_tokenize_process(tokenizer):
334
+ global tts_tokenizer_global # process-global
335
+ tts_tokenizer_global = copy.deepcopy(tokenizer)
336
+
337
+ with concurrent.futures.ProcessPoolExecutor(
338
+ initializer=_init_tts_tokenize_process, initargs=(tts_parser,), max_workers=tokenizer_workers,
339
+ ) as pool:
340
+ # chunk size for pool map is empirically chosen as a trade-off between speed and responsiveness
341
+ for i, tokenized_text in enumerate(
342
+ tqdm(pool.map(_tts_text_to_tokens, tts_texts, chunksize=1000), total=len(tts_texts))
343
+ ):
344
+ self.data[i]["tts_text_tokens"] = tokenized_text
345
+ # force free memory
346
+ del tts_texts
347
+ gc.collect()
348
+
349
+ def _asr_text_to_tokens(self, text: str) -> np.ndarray:
350
+ ids = self.asr_tokenizer.text_to_ids(text)
351
+ if self.asr_bos_id is not None:
352
+ ids = [self.asr_bos_id] + ids
353
+ if self.asr_eos_id is not None:
354
+ ids.append(self.asr_eos_id)
355
+ return np.asarray(ids)
356
+
357
+ def _tts_text_to_tokens(self, text: str, normalize=True) -> np.ndarray:
358
+ if normalize:
359
+ text = self.tts_normalizer.normalize(text, **self.tts_normalizer_kwargs)
360
+ tokens = self.tts_parser(text)
361
+ return np.asarray(tokens)
362
+
363
+ def __getitem__(self, index):
364
+ item = self.data[index]
365
+ return TextToTextItem(
366
+ transcript=torch.from_numpy(item["asr_text_tokens"]).long(),
367
+ tts_text=torch.from_numpy(item["tts_text_tokens"]).long(),
368
+ speaker=random.choice(self.speakers),
369
+ )
370
+
371
+ def __len__(self):
372
+ return len(self.data)
373
+
374
+
375
+ class TextToTextDataset(TextToTextDatasetBase, Dataset):
376
+ """Text-to-Text Map-style Dataset for hybrid ASR-TTS models"""
377
+
378
+ def __init__(
379
+ self,
380
+ manifest_filepath: Union[AnyPath, List[AnyPath]],
381
+ speakers_filepath: Union[AnyPath, List[AnyPath]],
382
+ asr_tokenizer: TokenizerSpec,
383
+ asr_use_start_end_token: bool,
384
+ tts_parser: Callable,
385
+ tts_text_pad_id: int,
386
+ tts_text_normalizer: "Normalizer",
387
+ tts_text_normalizer_call_kwargs: Dict,
388
+ min_words: int = 1,
389
+ max_words: int = 1_000_000,
390
+ tokenizer_workers: int = 1,
391
+ ):
392
+ super().__init__(
393
+ manifest_filepath=manifest_filepath,
394
+ speakers_filepath=speakers_filepath,
395
+ asr_tokenizer=asr_tokenizer,
396
+ asr_use_start_end_token=asr_use_start_end_token,
397
+ tts_parser=tts_parser,
398
+ tts_text_pad_id=tts_text_pad_id,
399
+ tts_text_normalizer=tts_text_normalizer,
400
+ tts_text_normalizer_call_kwargs=tts_text_normalizer_call_kwargs,
401
+ min_words=min_words,
402
+ max_words=max_words,
403
+ tokenizer_workers=tokenizer_workers,
404
+ num_parts=1,
405
+ )
406
+
407
+ def collate_fn(
408
+ self, batch: List[Union[TextToTextItem, tuple]]
409
+ ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]:
410
+ """
411
+ Collate function for dataloader
412
+ Can accept mixed batch of text-to-text items and audio-text items (typical for ASR)
413
+ """
414
+ return TextOrAudioToTextBatch.collate_fn(
415
+ batch=batch, asr_pad_id=self.asr_pad_id, tts_text_pad_id=self.tts_text_pad_id
416
+ )
417
+
418
+
419
+ class TextToTextIterableDataset(TextToTextDatasetBase, IterableDataset):
420
+ """
421
+ Text-to-Text Iterable Dataset for hybrid ASR-TTS models
422
+ Only part necessary for current process should be loaded and stored
423
+ """
424
+
425
+ def __init__(
426
+ self,
427
+ manifest_filepath: Union[AnyPath, List[AnyPath]],
428
+ speakers_filepath: Union[AnyPath, List[AnyPath]],
429
+ asr_tokenizer: TokenizerSpec,
430
+ asr_use_start_end_token: bool,
431
+ tts_parser: Callable,
432
+ tts_text_pad_id: int,
433
+ tts_text_normalizer: "Normalizer",
434
+ tts_text_normalizer_call_kwargs: Dict,
435
+ min_words: int = 1,
436
+ max_words: int = 1_000_000,
437
+ tokenizer_workers: int = 1,
438
+ num_parts: int = 1,
439
+ current_part_index: int = 0,
440
+ ):
441
+ super().__init__(
442
+ manifest_filepath=manifest_filepath,
443
+ speakers_filepath=speakers_filepath,
444
+ asr_tokenizer=asr_tokenizer,
445
+ asr_use_start_end_token=asr_use_start_end_token,
446
+ tts_parser=tts_parser,
447
+ tts_text_pad_id=tts_text_pad_id,
448
+ tts_text_normalizer=tts_text_normalizer,
449
+ tts_text_normalizer_call_kwargs=tts_text_normalizer_call_kwargs,
450
+ min_words=min_words,
451
+ max_words=max_words,
452
+ tokenizer_workers=tokenizer_workers,
453
+ num_parts=num_parts,
454
+ current_part_index=current_part_index,
455
+ )
456
+
457
+ def __iter__(self):
458
+ # Implementation based on docs: https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset
459
+ worker_info = torch.utils.data.get_worker_info()
460
+ if worker_info is None: # single-process data loading, return the full iterator
461
+ start = 0
462
+ end = len(self)
463
+ else: # in a worker process
464
+ # split workload
465
+ per_worker = int(math.ceil(len(self) / float(worker_info.num_workers)))
466
+ worker_id = worker_info.id
467
+ start = worker_id * per_worker
468
+ end = min(start + per_worker, len(self))
469
+ indices = np.arange(start, end)
470
+ np.random.shuffle(indices)
471
+ return map(self.__getitem__, indices)
472
+
473
+ def collate_fn(
474
+ self, batch: List[Union[TextToTextItem, tuple]]
475
+ ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]:
476
+ """
477
+ Collate function for dataloader
478
+ Can accept mixed batch of text-to-text items and audio-text items (typical for ASR)
479
+ """
480
+ return TextOrAudioToTextBatch.collate_fn(
481
+ batch=batch, asr_pad_id=self.asr_pad_id, tts_text_pad_id=self.tts_text_pad_id
482
+ )
nemo/collections/asr/losses/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr.losses.angularloss import AngularSoftmaxLoss
16
+ from nemo.collections.asr.losses.bce_loss import BCELoss
17
+ from nemo.collections.asr.losses.ctc import CTCLoss
18
+ from nemo.collections.asr.losses.lattice_losses import LatticeLoss
19
+ from nemo.collections.asr.losses.ssl_losses.contrastive import ContrastiveLoss
20
+ from nemo.collections.asr.losses.ssl_losses.ctc import CTCLossForSSL
21
+ from nemo.collections.asr.losses.ssl_losses.mlm import MLMLoss, MultiMLMLoss
22
+ from nemo.collections.asr.losses.ssl_losses.rnnt import RNNTLossForSSL
nemo/collections/asr/losses/angularloss.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import torch
17
+
18
+ from nemo.core.classes import Loss, Typing, typecheck
19
+ from nemo.core.neural_types import LabelsType, LogitsType, LossType, NeuralType
20
+
21
+ __all__ = ['AngularSoftmaxLoss']
22
+
23
+
24
+ class AngularSoftmaxLoss(Loss, Typing):
25
+ """
26
+ Computes ArcFace Angular softmax angle loss
27
+ reference: https://openaccess.thecvf.com/content_CVPR_2019/papers/Deng_ArcFace_Additive_Angular_Margin_Loss_for_Deep_Face_Recognition_CVPR_2019_paper.pdf
28
+ args:
29
+ scale: scale value for cosine angle
30
+ margin: margin value added to cosine angle
31
+ """
32
+
33
+ @property
34
+ def input_types(self):
35
+ """Input types definitions for AnguarLoss.
36
+ """
37
+ return {
38
+ "logits": NeuralType(('B', 'D'), LogitsType()),
39
+ "labels": NeuralType(('B',), LabelsType()),
40
+ }
41
+
42
+ @property
43
+ def output_types(self):
44
+ """Output types definitions for AngularLoss.
45
+ loss:
46
+ NeuralType(None)
47
+ """
48
+ return {"loss": NeuralType(elements_type=LossType())}
49
+
50
+ def __init__(self, scale=20.0, margin=1.35):
51
+ super().__init__()
52
+
53
+ self.eps = 1e-7
54
+ self.scale = scale
55
+ self.margin = margin
56
+
57
+ @typecheck()
58
+ def forward(self, logits, labels):
59
+ numerator = self.scale * torch.cos(
60
+ torch.acos(torch.clamp(torch.diagonal(logits.transpose(0, 1)[labels]), -1.0 + self.eps, 1 - self.eps))
61
+ + self.margin
62
+ )
63
+ excl = torch.cat(
64
+ [torch.cat((logits[i, :y], logits[i, y + 1 :])).unsqueeze(0) for i, y in enumerate(labels)], dim=0
65
+ )
66
+ denominator = torch.exp(numerator) + torch.sum(torch.exp(self.scale * excl), dim=1)
67
+ L = numerator - torch.log(denominator)
68
+ return -torch.mean(L)
nemo/collections/asr/losses/bce_loss.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import torch
17
+
18
+ from nemo.core.classes import Loss, Typing, typecheck
19
+ from nemo.core.neural_types import LabelsType, LengthsType, LossType, NeuralType, ProbsType
20
+
21
+ __all__ = ['BCELoss']
22
+
23
+
24
+ class BCELoss(Loss, Typing):
25
+ """
26
+ Computes Binary Cross Entropy (BCE) loss. The BCELoss class expects output from Sigmoid function.
27
+ """
28
+
29
+ @property
30
+ def input_types(self):
31
+ """Input types definitions for AnguarLoss."""
32
+ return {
33
+ "probs": NeuralType(('B', 'T', 'C'), ProbsType()),
34
+ 'labels': NeuralType(('B', 'T', 'C'), LabelsType()),
35
+ "target_lens": NeuralType(('B'), LengthsType()),
36
+ }
37
+
38
+ @property
39
+ def output_types(self):
40
+ """
41
+ Output types definitions for binary cross entropy loss. Weights for labels can be set using weight variables.
42
+ """
43
+ return {"loss": NeuralType(elements_type=LossType())}
44
+
45
+ def __init__(
46
+ self,
47
+ reduction: str = 'mean',
48
+ alpha: float = 1.0,
49
+ weight: torch.Tensor = torch.tensor([0.1, 0.9]),
50
+ sorted_preds: bool = False,
51
+ sorted_loss: bool = False,
52
+ class_normalization: bool = False,
53
+ ):
54
+ """
55
+ A custom loss function that supports class normalization,
56
+ weighted binary cross-entropy, and optional sorting.
57
+
58
+ Args:
59
+ reduction (str): Specifies the reduction to apply to the output,
60
+ options are 'mean', 'sum', or 'none'. Default is 'mean'.
61
+ alpha (float): Scaling factor for loss (unused in this implementation). Default is 1.0.
62
+ weight (torch.Tensor): Class weights for the binary cross-entropy loss. Default is [0.1, 0.9].
63
+ sorted_preds (bool): If True, assumes predictions are sorted. Default is False.
64
+ sorted_loss (bool): If True, sorts the loss before reduction. Default is False.
65
+ class_normalization (bool): If True, uses 'none' reduction for per-class loss. Default is False.
66
+ """
67
+ super().__init__()
68
+ self.class_normalization = class_normalization
69
+ if class_normalization:
70
+ self.reduction = 'none'
71
+ else:
72
+ self.reduction = 'mean'
73
+ self.loss_weight = weight
74
+ self.loss_f = torch.nn.BCELoss(reduction=self.reduction)
75
+ self.sorted_preds = sorted_preds
76
+ self.sorted_loss = sorted_loss
77
+ self.eps = 1e-6
78
+
79
+ @typecheck()
80
+ def forward(self, probs, labels, target_lens):
81
+ """
82
+ Calculate binary cross entropy loss based on probs, labels and target_lens variables.
83
+
84
+ Args:
85
+ probs (torch.tensor)
86
+ Predicted probability value which ranges from 0 to 1. Sigmoid output is expected.
87
+ labels (torch.tensor)
88
+ Groundtruth label for the predicted samples.
89
+ target_lens (torch.tensor):
90
+ The actual length of the sequence without zero-padding.
91
+
92
+ Returns:
93
+ loss (NeuralType)
94
+ Binary cross entropy loss value.
95
+ """
96
+ probs_list = [probs[k, : target_lens[k], :] for k in range(probs.shape[0])]
97
+ targets_list = [labels[k, : target_lens[k], :] for k in range(labels.shape[0])]
98
+ probs = torch.cat(probs_list, dim=0)
99
+ labels = torch.cat(targets_list, dim=0)
100
+ norm_weight = torch.zeros_like(labels).detach().clone()
101
+ loss = torch.tensor(0.0).to(labels.device)
102
+
103
+ if self.class_normalization in ['class', 'class_binary', 'binary']:
104
+ if self.class_normalization in ['class', 'class_binary']:
105
+ # Normalize loss by number of classes
106
+ norm_weight = 1 / (labels.sum(dim=0) + self.eps)
107
+ norm_weight_norm = norm_weight / norm_weight.sum()
108
+ norm_weight_norm = torch.clamp(norm_weight_norm, min=0.05, max=1.0)
109
+ norm_weight_norm = norm_weight_norm / norm_weight_norm.max()
110
+ norm_weight = norm_weight_norm[None, :].expand_as(labels).detach().clone()
111
+ else:
112
+ norm_weight = torch.ones_like(labels).detach().clone()
113
+
114
+ if self.class_normalization in ['binary', 'class_binary']:
115
+ binary_weight = torch.ones_like(labels).detach().clone()
116
+ one_weight = (labels.sum() / (labels.shape[0] * labels.shape[1])).to(labels.device)
117
+ binary_weight[labels == 0] = one_weight
118
+ binary_weight[labels == 1] = 1 - one_weight
119
+ else:
120
+ binary_weight = torch.ones_like(labels).detach().clone()
121
+
122
+ elif self.class_normalization == 'none' or not self.class_normalization:
123
+ binary_weight = torch.ones_like(labels).detach().clone()
124
+ norm_weight = torch.ones_like(labels).detach().clone()
125
+
126
+ if self.reduction == 'sum':
127
+ loss = self.loss_f(probs, labels)
128
+ elif self.reduction == 'mean':
129
+ loss = self.loss_f(probs, labels).mean()
130
+ elif self.reduction == 'none':
131
+ if self.class_normalization in ['class', 'class_binary', 'binary']:
132
+ loss = (binary_weight * norm_weight * self.loss_f(probs, labels)).sum()
133
+ else:
134
+ loss = self.loss_f(probs, labels)
135
+ return loss
nemo/collections/asr/losses/ctc.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from nemo.core.classes import Serialization, Typing, typecheck
20
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType
21
+
22
+ __all__ = ['CTCLoss']
23
+
24
+
25
+ class CTCLoss(nn.CTCLoss, Serialization, Typing):
26
+ @property
27
+ def input_types(self):
28
+ """Input types definitions for CTCLoss.
29
+ """
30
+ return {
31
+ "log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()),
32
+ "targets": NeuralType(('B', 'T'), LabelsType()),
33
+ "input_lengths": NeuralType(tuple('B'), LengthsType()),
34
+ "target_lengths": NeuralType(tuple('B'), LengthsType()),
35
+ }
36
+
37
+ @property
38
+ def output_types(self):
39
+ """Output types definitions for CTCLoss.
40
+ loss:
41
+ NeuralType(None)
42
+ """
43
+ return {"loss": NeuralType(elements_type=LossType())}
44
+
45
+ def __init__(self, num_classes, zero_infinity=False, reduction='mean_batch'):
46
+ self._blank = num_classes
47
+ # Don't forget to properly call base constructor
48
+ if reduction not in ['none', 'mean', 'sum', 'mean_batch', 'mean_volume']:
49
+ raise ValueError('`reduction` must be one of [mean, sum, mean_batch, mean_volume]')
50
+
51
+ self.config_reduction = reduction
52
+ if reduction == 'mean_batch' or reduction == 'mean_volume':
53
+ ctc_reduction = 'none'
54
+ self._apply_reduction = True
55
+ elif reduction in ['sum', 'mean', 'none']:
56
+ ctc_reduction = reduction
57
+ self._apply_reduction = False
58
+ super().__init__(blank=self._blank, reduction=ctc_reduction, zero_infinity=zero_infinity)
59
+
60
+ def reduce(self, losses, target_lengths):
61
+ if self.config_reduction == 'mean_batch':
62
+ losses = losses.mean() # global batch size average
63
+ elif self.config_reduction == 'mean_volume':
64
+ losses = losses.sum() / target_lengths.sum() # same as above but longer samples weigh more
65
+
66
+ return losses
67
+
68
+ @typecheck()
69
+ def forward(self, log_probs, targets, input_lengths, target_lengths):
70
+ # override forward implementation
71
+ # custom logic, if necessary
72
+ input_lengths = input_lengths.long()
73
+ target_lengths = target_lengths.long()
74
+ targets = targets.long()
75
+ # here we transpose because we expect [B, T, D] while PyTorch assumes [T, B, D]
76
+ log_probs = log_probs.transpose(1, 0)
77
+ loss = super().forward(
78
+ log_probs=log_probs, targets=targets, input_lengths=input_lengths, target_lengths=target_lengths
79
+ )
80
+ if self._apply_reduction:
81
+ loss = self.reduce(loss, target_lengths)
82
+ return loss
nemo/collections/asr/losses/lattice_losses.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import torch
19
+ from omegaconf import DictConfig
20
+
21
+ from nemo.core.classes import Loss, typecheck
22
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType
23
+
24
+
25
+ class LatticeLoss(Loss):
26
+ """Family of loss functions based on various lattice scores.
27
+
28
+ Note:
29
+ Requires k2 v1.14 or later to be installed to use this loss function.
30
+
31
+ Losses can be selected via the config, and optionally be passed keyword arguments as follows.
32
+
33
+ Examples:
34
+ .. code-block:: yaml
35
+
36
+ model: # Model config
37
+ ...
38
+ graph_module_cfg: # Config for graph modules, e.g. LatticeLoss
39
+ criterion_type: "map"
40
+ loss_type: "mmi"
41
+ split_batch_size: 0
42
+ backend_cfg:
43
+ topo_type: "default" # other options: "compact", "shared_blank", "minimal"
44
+ topo_with_self_loops: true
45
+ token_lm: <token_lm_path> # must be provided for criterion_type: "map"
46
+
47
+ Args:
48
+ num_classes: Number of target classes for the decoder network to predict.
49
+ (Excluding the blank token).
50
+
51
+ reduction: Type of reduction to perform on loss. Possible values are `mean_batch`, `mean`, `sum`, or None.
52
+ None will return a torch vector comprising the individual loss values of the batch.
53
+
54
+ backend: Which backend to use for loss calculation. Currently only `k2` is supported.
55
+
56
+ criterion_type: Type of criterion to use. Choices: `ml` and `map`,
57
+ with `ml` standing for Maximum Likelihood and `map` for Maximum A Posteriori Probability.
58
+
59
+ loss_type: Type of the loss function to use. Choices: `ctc` and `rnnt` for `ml`, and `mmi` for `map`.
60
+
61
+ split_batch_size: Local batch size. Used for memory consumption reduction at the cost of speed performance.
62
+ Effective if complies 0 < split_batch_size < batch_size.
63
+
64
+ graph_module_cfg: Optional Dict of (str, value) pairs that are passed to the backend loss function.
65
+ """
66
+
67
+ @property
68
+ def input_types(self):
69
+ """Input types definitions for LatticeLoss.
70
+ """
71
+ return {
72
+ "log_probs": NeuralType(("B", "T", "D") if self._3d_input else ("B", "T", "T", "D"), LogprobsType()),
73
+ "targets": NeuralType(("B", "T"), LabelsType()),
74
+ "input_lengths": NeuralType(tuple("B"), LengthsType()),
75
+ "target_lengths": NeuralType(tuple("B"), LengthsType()),
76
+ }
77
+
78
+ @property
79
+ def output_types(self):
80
+ """Output types definitions for LatticeLoss.
81
+ loss:
82
+ NeuralType(None)
83
+ """
84
+ return {"loss": NeuralType(elements_type=LossType())}
85
+
86
+ def __init__(
87
+ self,
88
+ num_classes: int,
89
+ reduction: str = "mean_batch",
90
+ backend: str = "k2",
91
+ criterion_type: str = "ml",
92
+ loss_type: str = "ctc",
93
+ split_batch_size: int = 0,
94
+ graph_module_cfg: Optional[DictConfig] = None,
95
+ ):
96
+ super().__init__()
97
+ self._blank = num_classes
98
+ self.split_batch_size = split_batch_size
99
+ inner_reduction = None
100
+ if reduction == "mean_batch":
101
+ inner_reduction = "none"
102
+ self._apply_batch_mean = True
103
+ elif reduction in ["sum", "mean", "none"]:
104
+ inner_reduction = reduction
105
+ self._apply_batch_mean = False
106
+
107
+ # we assume that self._blank + 1 == num_classes
108
+ if backend == "k2":
109
+ if criterion_type == "ml":
110
+ if loss_type == "ctc":
111
+ from nemo.collections.asr.parts.k2.ml_loss import CtcLoss as K2Loss
112
+ elif loss_type == "rnnt":
113
+ from nemo.collections.asr.parts.k2.ml_loss import RnntLoss as K2Loss
114
+ else:
115
+ raise ValueError(f"Unsupported `loss_type`: {loss_type}.")
116
+ elif criterion_type == "map":
117
+ if loss_type == "ctc":
118
+ from nemo.collections.asr.parts.k2.map_loss import CtcMmiLoss as K2Loss
119
+ else:
120
+ raise ValueError(f"Unsupported `loss_type`: {loss_type}.")
121
+ else:
122
+ raise ValueError(f"Unsupported `criterion_type`: {criterion_type}.")
123
+
124
+ self._loss = K2Loss(
125
+ num_classes=self._blank + 1, blank=self._blank, reduction=inner_reduction, cfg=graph_module_cfg,
126
+ )
127
+ elif backend == "gtn":
128
+ raise NotImplementedError(f"Backend {backend} is not supported.")
129
+ else:
130
+ raise ValueError(f"Invalid value of `backend`: {backend}.")
131
+
132
+ self.criterion_type = criterion_type
133
+ self.loss_type = loss_type
134
+ self._3d_input = self.loss_type != "rnnt"
135
+
136
+ if self.split_batch_size > 0:
137
+ # don't need to guard grad_utils
138
+ from nemo.collections.asr.parts.k2.grad_utils import PartialGrad
139
+
140
+ self._partial_loss = PartialGrad(self._loss)
141
+
142
+ def update_graph(self, graph):
143
+ """Updates graph of the backend loss function.
144
+ """
145
+ if self.criterion_type != "ml":
146
+ self._loss.update_graph(graph)
147
+
148
+ @typecheck()
149
+ def forward(self, log_probs, targets, input_lengths, target_lengths):
150
+ # override forward implementation
151
+ # custom logic, if necessary
152
+
153
+ assert not (torch.isnan(log_probs).any() or torch.isinf(log_probs).any())
154
+
155
+ log_probs = log_probs.float()
156
+ input_lengths = input_lengths.long()
157
+ target_lengths = target_lengths.long()
158
+ targets = targets.long()
159
+ batch_size = log_probs.shape[0]
160
+ if self.split_batch_size > 0 and self.split_batch_size <= batch_size:
161
+ loss_list = []
162
+ for batch_idx in range(0, batch_size, self.split_batch_size):
163
+ begin = batch_idx
164
+ end = min(begin + self.split_batch_size, batch_size)
165
+ input_lengths_part = input_lengths[begin:end]
166
+ log_probs_part = log_probs[begin:end, : input_lengths_part.max()]
167
+ target_lengths_part = target_lengths[begin:end]
168
+ targets_part = targets[begin:end, : target_lengths_part.max()]
169
+ loss_part, _ = (
170
+ self._partial_loss(log_probs_part, targets_part, input_lengths_part, target_lengths_part)
171
+ if log_probs_part.requires_grad
172
+ else self._loss(log_probs_part, targets_part, input_lengths_part, target_lengths_part)
173
+ )
174
+ del log_probs_part, targets_part, input_lengths_part, target_lengths_part
175
+ loss_list.append(loss_part)
176
+ loss = torch.cat(loss_list, 0)
177
+ else:
178
+ loss, _ = self._loss(
179
+ log_probs=log_probs, targets=targets, input_lengths=input_lengths, target_lengths=target_lengths,
180
+ )
181
+ if self._apply_batch_mean:
182
+ # torch.mean gives nan if loss is empty
183
+ loss = torch.mean(loss) if loss.nelement() > 0 else torch.sum(loss)
184
+ return loss
nemo/collections/asr/losses/rnnt.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Copyright 2018-2019, Mingkun Huang
17
+ #
18
+ # Licensed under the Apache License, Version 2.0 (the "License");
19
+ # you may not use this file except in compliance with the License.
20
+ # You may obtain a copy of the License at
21
+ #
22
+ # http://www.apache.org/licenses/LICENSE-2.0
23
+ #
24
+ # Unless required by applicable law or agreed to in writing, software
25
+ # distributed under the License is distributed on an "AS IS" BASIS,
26
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27
+ # See the License for the specific language governing permissions and
28
+ # limitations under the License.
29
+
30
+ import inspect
31
+ import operator
32
+ from dataclasses import dataclass
33
+ from typing import Any, Callable, Dict, List, Optional, Set
34
+
35
+ import torch
36
+ from omegaconf import DictConfig, OmegaConf
37
+
38
+ from nemo.collections.asr.losses.rnnt_pytorch import MultiblankRNNTLossPytorch, RNNTLossPytorch, TDTLossPytorch
39
+ from nemo.core.classes import Loss, typecheck
40
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType
41
+ from nemo.core.utils import numba_utils
42
+ from nemo.core.utils.k2_utils import K2_INSTALLATION_MESSAGE
43
+ from nemo.core.utils.numba_utils import NUMBA_INSTALLATION_MESSAGE
44
+ from nemo.utils import logging, logging_mode, model_utils
45
+
46
+ try:
47
+ import warprnnt_pytorch as warprnnt
48
+
49
+ WARP_RNNT_AVAILABLE = True
50
+ except (ImportError, ModuleNotFoundError):
51
+ WARP_RNNT_AVAILABLE = False
52
+
53
+ try:
54
+ from nemo.collections.asr.parts.numba.rnnt_loss import MultiblankRNNTLossNumba, RNNTLossNumba, TDTLossNumba
55
+
56
+ NUMBA_RNNT_AVAILABLE = True
57
+ except (ImportError, ModuleNotFoundError):
58
+ NUMBA_RNNT_AVAILABLE = False
59
+
60
+ try:
61
+ from nemo.collections.asr.parts.k2.graph_transducer import GraphRnntLoss
62
+ from nemo.collections.asr.parts.k2.w_transducer import GraphWTransducerLoss
63
+
64
+ K2_AVAILABLE = True
65
+ except (ImportError, ModuleNotFoundError):
66
+ K2_AVAILABLE = False
67
+
68
+ WARP_RNNT_INSTALLATION_MESSAGE = (
69
+ "Could not import `warprnnt_pytorch`.\n"
70
+ "Please visit https://github.com/HawkAaron/warp-transducer "
71
+ "and follow the steps in the readme to build and install the "
72
+ "pytorch bindings for RNNT Loss, or use the provided docker "
73
+ "container that supports RNN-T loss."
74
+ )
75
+
76
+
77
+ @dataclass
78
+ class RNNTLossConfig:
79
+ loss_name: str
80
+ lib_name: str
81
+ is_available: bool = False
82
+ installation_msg: str = ""
83
+ min_version: Optional[str] = None
84
+ force_float32: bool = True # default True for now for all losses except graph-based
85
+
86
+
87
+ # Resolved list of available RNNT losses
88
+ RNNT_LOSS_RESOLVER = {
89
+ "warprnnt": RNNTLossConfig(
90
+ loss_name="warprnnt",
91
+ lib_name="warprnnt_pytorch",
92
+ is_available=WARP_RNNT_AVAILABLE,
93
+ installation_msg=WARP_RNNT_INSTALLATION_MESSAGE,
94
+ force_float32=True,
95
+ ),
96
+ "warprnnt_numba": RNNTLossConfig(
97
+ loss_name="warprnnt_numba",
98
+ lib_name="numba",
99
+ min_version='0.53.0',
100
+ is_available=NUMBA_RNNT_AVAILABLE,
101
+ installation_msg=NUMBA_INSTALLATION_MESSAGE,
102
+ force_float32=False, # This is only temporarily false, will be dynamically updated during resolution
103
+ ),
104
+ "pytorch": RNNTLossConfig(
105
+ loss_name="pytorch",
106
+ lib_name="torch",
107
+ min_version='0.0',
108
+ is_available=True,
109
+ installation_msg="Pure Pytorch implementation of RNN-T loss. Slow and for debugging purposes only.",
110
+ force_float32=True,
111
+ ),
112
+ "multiblank_rnnt": RNNTLossConfig(
113
+ loss_name="multiblank_rnnt",
114
+ lib_name="numba",
115
+ min_version='0.53.0',
116
+ is_available=NUMBA_RNNT_AVAILABLE,
117
+ installation_msg=NUMBA_INSTALLATION_MESSAGE,
118
+ force_float32=True,
119
+ ),
120
+ "multiblank_rnnt_pytorch": RNNTLossConfig(
121
+ loss_name="pytorch",
122
+ lib_name="torch",
123
+ min_version='0.0',
124
+ is_available=True,
125
+ installation_msg="Pure Pytorch implementation of Multiblank RNN-T loss. Slow and for debugging purposes only.",
126
+ force_float32=True,
127
+ ),
128
+ "graph_w_transducer": RNNTLossConfig(
129
+ loss_name="graph_w_transducer",
130
+ lib_name="k2",
131
+ is_available=K2_AVAILABLE,
132
+ installation_msg=K2_INSTALLATION_MESSAGE,
133
+ force_float32=False,
134
+ ),
135
+ "graph_rnnt": RNNTLossConfig(
136
+ loss_name="graph_rnnt",
137
+ lib_name="k2",
138
+ is_available=K2_AVAILABLE,
139
+ installation_msg=K2_INSTALLATION_MESSAGE,
140
+ force_float32=False,
141
+ ),
142
+ "tdt": RNNTLossConfig(
143
+ loss_name="tdt",
144
+ lib_name="numba",
145
+ min_version='0.53.0',
146
+ is_available=NUMBA_RNNT_AVAILABLE,
147
+ installation_msg=NUMBA_INSTALLATION_MESSAGE,
148
+ ),
149
+ "tdt_pytorch": RNNTLossConfig(
150
+ loss_name="tdt_pytorch",
151
+ lib_name="torch",
152
+ min_version='0.0',
153
+ is_available=True,
154
+ installation_msg="Pure Pytorch implementation of TDT loss. Slow and for debugging purposes only.",
155
+ ),
156
+ }
157
+
158
+ RNNT_LOSS_RESOLVER['default'] = RNNT_LOSS_RESOLVER['warprnnt_numba']
159
+
160
+
161
+ def _warn_unused_additional_kwargs(loss_name, kwargs):
162
+ if len(kwargs) > 0:
163
+ logging.warning(
164
+ f"Loss function `{loss_name}` was provided with following additional kwargs,\n"
165
+ f"however they were ignored as it is unused.\n"
166
+ f"{kwargs}"
167
+ )
168
+
169
+
170
+ def _clean_kwargs(
171
+ loss_name: str, kwargs: Optional[Dict[str, Any]], init_method: Callable, ignore_params: Optional[Set[str]] = None
172
+ ) -> Dict[str, Any]:
173
+ """
174
+ Cleans kwargs for the given loss function. Warn if there are unused kwargs.
175
+
176
+ Args:
177
+ loss_name: name of the loss function
178
+ kwargs: kwargs to clean
179
+ init_method: LossClass.__init__ method
180
+ ignore_params: set of argument names for init_method to ignore
181
+
182
+ Returns:
183
+ only used kwargs for the given `init_method`
184
+ """
185
+ if not kwargs:
186
+ return {}
187
+ init_params = set(inspect.signature(init_method).parameters.keys()) - {"self"}
188
+ if ignore_params is not None:
189
+ init_params -= ignore_params
190
+ unused_kwargs = dict()
191
+ used_kwargs = dict()
192
+ for key, value in kwargs.items():
193
+ if key not in init_params:
194
+ unused_kwargs[key] = value
195
+ else:
196
+ used_kwargs[key] = value
197
+ if len(unused_kwargs) > 0:
198
+ _warn_unused_additional_kwargs(loss_name, unused_kwargs)
199
+ return used_kwargs
200
+
201
+
202
+ def resolve_rnnt_default_loss_name() -> str:
203
+ return RNNT_LOSS_RESOLVER['default'].loss_name
204
+
205
+
206
+ def resolve_rnnt_loss(loss_name: str, blank_idx: int, loss_kwargs: dict = None) -> torch.nn.Module:
207
+ loss_function_names = list(RNNT_LOSS_RESOLVER.keys())
208
+
209
+ if loss_name not in loss_function_names:
210
+ raise ValueError(
211
+ f"Provided `loss_name` {loss_name} not in list of available RNNT losses \n" f"{loss_function_names}"
212
+ )
213
+
214
+ all_available_losses = {name: config for name, config in RNNT_LOSS_RESOLVER.items() if config.is_available}
215
+
216
+ loss_config = RNNT_LOSS_RESOLVER[loss_name] # type: RNNTLossConfig
217
+
218
+ # Re-raise import error with installation message
219
+ if not loss_config.is_available:
220
+ msg = (
221
+ f"Installed RNNT losses are : {list(all_available_losses.keys())}.\n"
222
+ f"****************************************************************\n"
223
+ f"To install the selected loss function, please follow the steps below:\n"
224
+ f"{loss_config.installation_msg}"
225
+ )
226
+ raise ImportError(msg)
227
+
228
+ # Library version check
229
+ if loss_config.min_version is not None:
230
+ ver_matched, msg = model_utils.check_lib_version(
231
+ loss_config.lib_name, checked_version=loss_config.min_version, operator=operator.ge
232
+ )
233
+
234
+ if ver_matched is False:
235
+ msg = (
236
+ f"{msg}\n"
237
+ f"****************************************************************\n"
238
+ f"To update the selected loss function, please follow the steps below:\n"
239
+ f"{loss_config.installation_msg}"
240
+ )
241
+ raise RuntimeError(msg)
242
+
243
+ # Resolve loss functions sequentially
244
+ loss_kwargs = {} if loss_kwargs is None else loss_kwargs
245
+
246
+ if isinstance(loss_kwargs, DictConfig):
247
+ loss_kwargs = OmegaConf.to_container(loss_kwargs, resolve=True)
248
+
249
+ # Get actual loss name for `default`
250
+ if loss_name == 'default':
251
+ loss_name = loss_config.loss_name
252
+
253
+ """
254
+ Resolve RNNT loss functions
255
+ """
256
+ if loss_name == 'warprnnt':
257
+ loss_func = warprnnt.RNNTLoss(blank=blank_idx, reduction='none')
258
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
259
+
260
+ elif loss_name == 'warprnnt_numba':
261
+ # Update loss config's forced float32 flag if set to None
262
+ loss_config.force_float32 = not numba_utils.is_numba_cuda_fp16_supported()
263
+
264
+ fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0)
265
+ clamp = loss_kwargs.pop('clamp', -1.0)
266
+ loss_func = RNNTLossNumba(blank=blank_idx, reduction='none', fastemit_lambda=fastemit_lambda, clamp=clamp)
267
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
268
+
269
+ elif loss_name == 'pytorch':
270
+ loss_func = RNNTLossPytorch(blank=blank_idx, reduction='none')
271
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
272
+
273
+ elif loss_name == 'multiblank_rnnt':
274
+ fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0)
275
+ clamp = loss_kwargs.pop('clamp', -1.0)
276
+ big_blank_durations = loss_kwargs.pop('big_blank_durations', None)
277
+ sigma = loss_kwargs.pop('sigma', 0.0)
278
+ loss_func = MultiblankRNNTLossNumba(
279
+ blank=blank_idx,
280
+ big_blank_durations=big_blank_durations,
281
+ reduction='none',
282
+ fastemit_lambda=fastemit_lambda,
283
+ clamp=clamp,
284
+ sigma=sigma,
285
+ )
286
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
287
+
288
+ elif loss_name == 'multiblank_rnnt_pytorch':
289
+ big_blank_durations = loss_kwargs.pop('big_blank_durations', None)
290
+ sigma = loss_kwargs.pop('sigma', 0.0)
291
+ loss_func = MultiblankRNNTLossPytorch(
292
+ blank=blank_idx, big_blank_durations=big_blank_durations, reduction='none', sigma=sigma
293
+ )
294
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
295
+
296
+ elif loss_name == 'tdt':
297
+ fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0)
298
+ clamp = loss_kwargs.pop('clamp', -1.0)
299
+ durations = loss_kwargs.pop('durations', None)
300
+ sigma = loss_kwargs.pop('sigma', 0.0)
301
+ omega = loss_kwargs.pop('omega', 0.0)
302
+ loss_func = TDTLossNumba(
303
+ blank=blank_idx,
304
+ durations=durations,
305
+ reduction='none',
306
+ fastemit_lambda=fastemit_lambda,
307
+ clamp=clamp,
308
+ sigma=sigma,
309
+ omega=omega,
310
+ )
311
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
312
+
313
+ elif loss_name == 'tdt_pytorch':
314
+ durations = loss_kwargs.pop('durations', None)
315
+ sigma = loss_kwargs.pop('sigma', 0.0)
316
+ loss_func = TDTLossPytorch(blank=blank_idx, durations=durations, reduction='none', sigma=sigma)
317
+ _warn_unused_additional_kwargs(loss_name, loss_kwargs)
318
+
319
+ elif loss_name == "graph_rnnt":
320
+ loss_kwargs = _clean_kwargs(loss_name, loss_kwargs, GraphRnntLoss.__init__, ignore_params={"blank"})
321
+ loss_func = GraphRnntLoss(blank=blank_idx, **loss_kwargs)
322
+ elif loss_name == "graph_w_transducer":
323
+ loss_kwargs = _clean_kwargs(loss_name, loss_kwargs, GraphWTransducerLoss.__init__, ignore_params={"blank"})
324
+ loss_func = GraphWTransducerLoss(blank=blank_idx, **loss_kwargs)
325
+ else:
326
+ raise ValueError(
327
+ f"Invalid value of `loss_name`: {loss_name}. Allowed loss names are :" f"{loss_function_names}"
328
+ )
329
+
330
+ return loss_func
331
+
332
+
333
+ class RNNTLoss(Loss):
334
+ @property
335
+ def input_types(self):
336
+ """Input types definitions for CTCLoss.
337
+ """
338
+ return {
339
+ "log_probs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()),
340
+ "targets": NeuralType(('B', 'T'), LabelsType()),
341
+ "input_lengths": NeuralType(tuple('B'), LengthsType()),
342
+ "target_lengths": NeuralType(tuple('B'), LengthsType()),
343
+ }
344
+
345
+ @property
346
+ def output_types(self):
347
+ """Output types definitions for CTCLoss.
348
+ loss:
349
+ NeuralType(None)
350
+ """
351
+ return {"loss": NeuralType(elements_type=LossType())}
352
+
353
+ def __init__(self, num_classes, reduction: str = 'mean_batch', loss_name: str = "default", loss_kwargs=None):
354
+ """
355
+ RNN-T Loss function based on https://github.com/HawkAaron/warp-transducer.
356
+ Optionally, can utilize a numba implementation of the same loss without having to compile the loss,
357
+ albiet there is a small speed penalty for JIT numba compile.
358
+
359
+ Note:
360
+ Requires Numba 0.53.0 or later to be installed to use this loss function.
361
+
362
+ Losses can be selected via the config, and optionally be passed keyword arguments as follows.
363
+
364
+ Examples:
365
+ .. code-block:: yaml
366
+
367
+ model: # RNNT Model config
368
+ ...
369
+ loss:
370
+ loss_name: "warprnnt_numba"
371
+ warprnnt_numba_kwargs:
372
+ fastemit_lambda: 0.0
373
+
374
+ Warning:
375
+ In the case that GPU memory is exhausted in order to compute RNNTLoss, it might cause
376
+ a core dump at the cuda level with the following error message.
377
+
378
+ ```
379
+ ...
380
+ costs = costs.to(acts.device)
381
+ RuntimeError: CUDA error: an illegal memory access was encountered
382
+ terminate called after throwing an instance of 'c10::Error'
383
+ ```
384
+
385
+ Please kill all remaining python processes after this point, and use a smaller batch size
386
+ for train, validation and test sets so that CUDA memory is not exhausted.
387
+
388
+ Args:
389
+ num_classes: Number of target classes for the joint network to predict.
390
+ In all cases (conventional RNNT, multi-blank RNNT, and TDT model), this equals the token-id
391
+ for the standard "blank" symbol. In particular, say V is the number of non-blank tokens in
392
+ the vocabulary, then in the case of,
393
+ standard RNNT: num_classes = V
394
+ multiblank RNNT: num_classes = V + number-big-blanks (since we store big-blanks before
395
+ standard blank, and the standard blank is the last symbol in the vocab)
396
+ TDT: num_classes = V. Note, V here does not include any of the "duration outputs".
397
+
398
+ reduction: Type of reduction to perform on loss. Possible values are
399
+ `mean_batch`, 'mean_volume`, `mean`, `sum` or None.
400
+ `None` will return a torch vector comprising the individual loss values of the batch.
401
+ `mean_batch` will average the losses in the batch
402
+ `mean` will divide each loss by the target length and then average
403
+ `mean_volume` will add up all the losses and divide by sum of target lengths
404
+
405
+ loss_name: String that is resolved into an RNNT loss function. Available list of losses
406
+ is ininitialized in `RNNT_LOSS_RESOLVER` dictionary.
407
+
408
+ loss_kwargs: Optional Dict of (str, value) pairs that are passed to the instantiated loss
409
+ function.
410
+ """
411
+ super(RNNTLoss, self).__init__()
412
+
413
+ if reduction not in [None, 'mean', 'sum', 'mean_batch', 'mean_volume']:
414
+ raise ValueError('`reduction` must be one of [mean, sum, mean_batch, mean_volume]')
415
+
416
+ self._blank = num_classes
417
+ self.reduction = reduction
418
+ self._loss = resolve_rnnt_loss(loss_name, blank_idx=self._blank, loss_kwargs=loss_kwargs)
419
+ self._force_float32 = RNNT_LOSS_RESOLVER[loss_name].force_float32
420
+ self._fp16_compat_checked = False
421
+
422
+ def reduce(self, losses, target_lengths):
423
+
424
+ if isinstance(losses, List):
425
+ losses = torch.cat(losses, 0)
426
+ target_lengths = torch.cat(target_lengths, 0)
427
+
428
+ if self.reduction == 'mean_batch':
429
+ losses = losses.mean() # global batch size average
430
+ elif self.reduction == 'mean':
431
+ losses = torch.div(losses, target_lengths).mean()
432
+ elif self.reduction == 'sum':
433
+ losses = losses.sum()
434
+ elif self.reduction == 'mean_volume':
435
+ losses = losses.sum() / target_lengths.sum() # same as above but longer samples weigh more
436
+
437
+ return losses
438
+
439
+ @typecheck()
440
+ def forward(self, log_probs, targets, input_lengths, target_lengths):
441
+ # Cast to int 64
442
+ targets = targets.long()
443
+ input_lengths = input_lengths.long()
444
+ target_lengths = target_lengths.long()
445
+
446
+ max_logit_len = input_lengths.max()
447
+ max_targets_len = target_lengths.max()
448
+
449
+ # Force cast joint to float32
450
+ if not self._force_float32 and numba_utils.is_numba_cuda_fp16_supported():
451
+ # Execute the kernel in fp16
452
+ pass
453
+ elif self._force_float32 and log_probs.dtype != torch.float32:
454
+ # Log just once if fp16 tensor was passed and fp16 Numba CUDA loss could not be used.
455
+ if log_probs.dtype == torch.float16 and not self._fp16_compat_checked:
456
+ _, reason = numba_utils.is_numba_cuda_fp16_supported(return_reason=True)
457
+ logging.warning(
458
+ f"Provided RNNT Joint tensor is of dtype {log_probs.dtype}, but RNNT loss could not be calculated "
459
+ f"in fp16 due to following reason stated below. Loss will be calculated in fp32. \n\n"
460
+ f"{reason}",
461
+ mode=logging_mode.ONCE,
462
+ )
463
+ self._fp16_compat_checked = True
464
+
465
+ # Upcast the activation tensor and compute loss and grads in fp32
466
+ logits_orig = log_probs
467
+ log_probs = log_probs.float()
468
+ del logits_orig # save memory *before* computing the loss
469
+
470
+ # Ensure that shape mismatch does not occur due to padding
471
+ # Due to padding and subsequent downsampling, it may be possible that
472
+ # max sequence length computed does not match the actual max sequence length
473
+ # of the log_probs tensor, therefore we increment the input_lengths by the difference.
474
+ # This difference is generally small.
475
+ if log_probs.shape[1] != max_logit_len:
476
+ log_probs = log_probs.narrow(dim=1, start=0, length=max_logit_len).contiguous()
477
+
478
+ # Reduce transcript length to correct alignment if additional padding was applied.
479
+ # Transcript: [B, L] -> [B, L']; If L' < L
480
+ if not targets.is_contiguous():
481
+ targets = targets.contiguous()
482
+
483
+ if targets.shape[1] != max_targets_len:
484
+ targets = targets.narrow(dim=1, start=0, length=max_targets_len).contiguous()
485
+
486
+ # Temporarily override loss reduction
487
+ loss_reduction = self._loss.reduction
488
+ self._loss.reduction = None
489
+
490
+ # Compute RNNT loss
491
+ loss = self._loss(acts=log_probs, labels=targets, act_lens=input_lengths, label_lens=target_lengths)
492
+
493
+ # Loss reduction can be dynamic, so reset it after call
494
+ self._loss.reduction = loss_reduction
495
+
496
+ # reduce here using our own reduction function
497
+ if self.reduction is not None:
498
+ loss = self.reduce(loss, target_lengths)
499
+
500
+ # del new variables that may have been created
501
+ del (
502
+ log_probs,
503
+ targets,
504
+ input_lengths,
505
+ target_lengths,
506
+ )
507
+
508
+ return loss
nemo/collections/asr/losses/rnnt_pytorch.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ! /usr/bin/python
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import List
17
+
18
+ import torch
19
+
20
+ from nemo.core.classes import Loss
21
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType
22
+
23
+
24
+ class RNNTLossPytorch(Loss):
25
+ @property
26
+ def input_types(self):
27
+ """Input types definitions for CTCLoss.
28
+ """
29
+ return {
30
+ "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()),
31
+ "labels": NeuralType(('B', 'T'), LabelsType()),
32
+ "act_lens": NeuralType(tuple('B'), LengthsType()),
33
+ "label_lens": NeuralType(tuple('B'), LengthsType()),
34
+ }
35
+
36
+ @property
37
+ def output_types(self):
38
+ """Output types definitions for CTCLoss.
39
+ loss:
40
+ NeuralType(None)
41
+ """
42
+ return {"loss": NeuralType(elements_type=LossType())}
43
+
44
+ def __init__(self, blank, reduction):
45
+ super().__init__()
46
+ self.blank = blank
47
+ self.reduction = reduction
48
+
49
+ def forward(self, acts, labels, act_lens, label_lens):
50
+ # CPU patch for FP16
51
+ if not acts.is_cuda and acts.dtype == torch.float16:
52
+ acts = acts.float()
53
+
54
+ acts = torch.log_softmax(acts, -1)
55
+
56
+ forward_logprob = self.compute_forward_prob(acts, labels, act_lens, label_lens)
57
+ losses = -forward_logprob
58
+ if self.reduction == 'mean_batch':
59
+ losses = losses.mean() # global batch size average
60
+ elif self.reduction == 'mean':
61
+ losses = torch.div(losses, label_lens).mean()
62
+ elif self.reduction == 'sum':
63
+ losses = losses.sum()
64
+ elif self.reduction == 'mean_volume':
65
+ losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more
66
+
67
+ return losses
68
+
69
+ def compute_forward_prob(self, acts, labels, act_lens, label_lens):
70
+ B, T, U, _ = acts.shape
71
+
72
+ log_alpha = torch.zeros(B, T, U)
73
+ log_alpha = log_alpha.to(acts.device)
74
+
75
+ for t in range(T):
76
+ for u in range(U):
77
+ if u == 0:
78
+ if t == 0:
79
+ # this is the base case: (t=0, u=0) with log-alpha = 0.
80
+ log_alpha[:, t, u] = 0.0
81
+ else:
82
+ # this is case for (t = 0, u > 0), reached by (t, u - 1)
83
+ # emitting a blank symbol.
84
+ log_alpha[:, t, u] = log_alpha[:, t - 1, u] + acts[:, t - 1, 0, self.blank]
85
+ else:
86
+ if t == 0:
87
+ # in case of (u > 0, t = 0), this is only reached from
88
+ # (t, u - 1) with a label emission.
89
+ gathered = torch.gather(
90
+ acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64)
91
+ ).reshape(-1)
92
+ log_alpha[:, t, u] = log_alpha[:, t, u - 1] + gathered.to(log_alpha.device)
93
+ else:
94
+ # here both t and u are > 0, this state is reachable
95
+ # with two possibilities: (t - 1, u) with a blank emission
96
+ # or (t, u - 1) with a label emission.
97
+ log_alpha[:, t, u] = torch.logsumexp(
98
+ torch.stack(
99
+ [
100
+ log_alpha[:, t - 1, u] + acts[:, t - 1, u, self.blank],
101
+ log_alpha[:, t, u - 1]
102
+ + torch.gather(
103
+ acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64)
104
+ ).reshape(-1),
105
+ ]
106
+ ),
107
+ dim=0,
108
+ )
109
+
110
+ log_probs = []
111
+ for b in range(B):
112
+ # here we need to add the final blank emission weights.
113
+ to_append = (
114
+ log_alpha[b, act_lens[b] - 1, label_lens[b]] + acts[b, act_lens[b] - 1, label_lens[b], self.blank]
115
+ )
116
+ log_probs.append(to_append)
117
+ log_prob = torch.stack(log_probs)
118
+
119
+ return log_prob
120
+
121
+
122
+ class TDTLossPytorch(Loss):
123
+ """
124
+ Pure Python implementation of TDT loss (https://arxiv.org/pdf/2304.06795.pdf)
125
+ """
126
+
127
+ @property
128
+ def input_types(self):
129
+ """Input types definitions for CTCLoss.
130
+ """
131
+ return {
132
+ "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()),
133
+ "labels": NeuralType(('B', 'T'), LabelsType()),
134
+ "act_lens": NeuralType(tuple('B'), LengthsType()),
135
+ "label_lens": NeuralType(tuple('B'), LengthsType()),
136
+ }
137
+
138
+ @property
139
+ def output_types(self):
140
+ """Output types definitions for CTCLoss.
141
+ loss:
142
+ NeuralType(None)
143
+ """
144
+ return {"loss": NeuralType(elements_type=LossType())}
145
+
146
+ def __init__(self, blank: int, durations: List[int] = [], reduction: str = 'sum', sigma: float = 0.0):
147
+ super().__init__()
148
+ self.blank = blank
149
+ self.durations = durations
150
+ self.n_durations = len(durations)
151
+ self.reduction = reduction
152
+ self.sigma = sigma
153
+
154
+ def forward(self, acts, labels, act_lens, label_lens):
155
+ label_acts = acts[:, :, :, : -self.n_durations]
156
+ duration_acts = acts[:, :, :, -self.n_durations :]
157
+
158
+ # the - self.sigma here is for logit-undernormalization. Check the paper for details.
159
+ label_acts = torch.log_softmax(label_acts, -1) - self.sigma
160
+
161
+ duration_acts = torch.log_softmax(duration_acts, -1)
162
+
163
+ forward_logprob, _ = self.compute_forward_prob(label_acts, duration_acts, labels, act_lens, label_lens)
164
+ losses = -forward_logprob
165
+ if self.reduction == 'mean_batch':
166
+ losses = losses.mean() # global batch size average
167
+ elif self.reduction == 'mean':
168
+ losses = torch.div(losses, label_lens).mean()
169
+ elif self.reduction == 'sum':
170
+ losses = losses.sum()
171
+ elif self.reduction == 'mean_volume':
172
+ losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more
173
+
174
+ return losses
175
+
176
+ def logsumexp(self, a, b):
177
+ ret = torch.logsumexp(torch.stack([a, b]), dim=0)
178
+ return ret
179
+
180
+ def compute_forward_prob(self, acts, duration_acts, labels, act_lens, label_lens):
181
+ """This function implements Equation 7 in the TDT paper https://arxiv.org/pdf/2304.06795.pdf,
182
+ Simply put, for each alpha(t, u), it sums over the contribution from all incoming blank arcs and non-blank arcs.
183
+ """
184
+ B, T, U, _ = acts.shape
185
+
186
+ log_alpha = torch.zeros(B, T, U)
187
+ log_alpha = log_alpha.cuda()
188
+ for b in range(B):
189
+ for t in range(T):
190
+ for u in range(U):
191
+ if u == 0:
192
+ if t == 0:
193
+ # both t and u are 0, this is the base case for alphas.
194
+ log_alpha[b, t, u] = 0.0
195
+ else:
196
+ # u = 0 and t != 0: only considers blank emissions.
197
+ log_alpha[b, t, u] = -1000.0
198
+ for n, l in enumerate(self.durations):
199
+ if (
200
+ t - l >= 0 and l > 0
201
+ ): # checking conditions for blank emission, l has to be at least 1
202
+ tmp = (
203
+ log_alpha[b, t - l, u]
204
+ + acts[b, t - l, u, self.blank]
205
+ + duration_acts[b, t - l, u, n]
206
+ )
207
+ log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u])
208
+
209
+ else:
210
+ # u != 0 here, need to consider both blanks and non-blanks.
211
+ log_alpha[b, t, u] = -1000.0
212
+ for n, l in enumerate(self.durations):
213
+ if t - l >= 0:
214
+ if l > 0: # for blank emissions. Need to ensure index is not out-of-bound.
215
+ tmp = (
216
+ log_alpha[b, t - l, u]
217
+ + acts[b, t - l, u, self.blank]
218
+ + duration_acts[b, t - l, u, n]
219
+ )
220
+ log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u])
221
+
222
+ # non-blank emissions.
223
+ tmp = (
224
+ log_alpha[b, t - l, u - 1]
225
+ + acts[b, t - l, u - 1, labels[b, u - 1]]
226
+ + duration_acts[b, t - l, u - 1, n]
227
+ )
228
+ log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u])
229
+
230
+ log_probs = []
231
+ for b in range(B):
232
+ tt = torch.Tensor([-1000.0]).cuda()[0]
233
+
234
+ # need to loop over all possible ways that blank with different durations contributes to the final loss.
235
+ for n, l in enumerate(self.durations):
236
+ if act_lens[b] - l >= 0 and l > 0:
237
+ bb = (
238
+ log_alpha[b, act_lens[b] - l, label_lens[b]]
239
+ + acts[b, act_lens[b] - l, label_lens[b], self.blank]
240
+ + duration_acts[b, act_lens[b] - l, label_lens[b], n]
241
+ )
242
+
243
+ tt = self.logsumexp(bb, 1.0 * tt)
244
+
245
+ log_probs.append(tt)
246
+
247
+ log_prob = torch.stack(log_probs)
248
+
249
+ return log_prob, log_alpha
250
+
251
+
252
+ class MultiblankRNNTLossPytorch(Loss):
253
+ """
254
+ Pure Python implementation of multi-blank transducer loss (https://arxiv.org/pdf/2211.03541.pdf)
255
+ """
256
+
257
+ @property
258
+ def input_types(self):
259
+ """Input types definitions for CTCLoss.
260
+ """
261
+ return {
262
+ "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()),
263
+ "labels": NeuralType(('B', 'T'), LabelsType()),
264
+ "act_lens": NeuralType(tuple('B'), LengthsType()),
265
+ "label_lens": NeuralType(tuple('B'), LengthsType()),
266
+ }
267
+
268
+ @property
269
+ def output_types(self):
270
+ """Output types definitions for CTCLoss.
271
+ loss:
272
+ NeuralType(None)
273
+ """
274
+ return {"loss": NeuralType(elements_type=LossType())}
275
+
276
+ def __init__(self, blank, big_blank_durations, reduction: str = "sum", sigma: float = 0.0):
277
+ super().__init__()
278
+ self.blank = blank
279
+ self.big_blank_durations = big_blank_durations
280
+ self.reduction = reduction
281
+ self.sigma = sigma
282
+
283
+ def forward(self, acts, labels, act_lens, label_lens):
284
+ acts = torch.log_softmax(acts, -1) - self.sigma
285
+ forward_logprob, _ = self.compute_forward_prob(acts, labels, act_lens, label_lens)
286
+
287
+ losses = -forward_logprob
288
+ if self.reduction == 'mean_batch':
289
+ losses = losses.mean() # global batch size average
290
+ elif self.reduction == 'mean':
291
+ losses = torch.div(losses, label_lens).mean()
292
+ elif self.reduction == 'sum':
293
+ losses = losses.sum()
294
+ elif self.reduction == 'mean_volume':
295
+ losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more
296
+
297
+ return losses
298
+
299
+ def compute_forward_prob(self, acts, labels, act_lens, label_lens):
300
+ B, T, U, _ = acts.shape
301
+
302
+ log_alpha = torch.zeros(B, T, U, device=acts.device)
303
+ for t in range(T):
304
+ for u in range(U):
305
+ if u == 0:
306
+ if t == 0:
307
+ # this is the base case: (t=0, u=0) with log-alpha = 0.
308
+ log_alpha[:, t, u] = 0.0
309
+ else:
310
+ # this is case for (t = 0, u > 0), reached by (t, u - d)
311
+ # emitting a blank symbol of duration d.
312
+ log_alpha[:, t, u] = log_alpha[:, t - 1, u] + acts[:, t - 1, 0, self.blank]
313
+ for i, d in enumerate(self.big_blank_durations):
314
+ if t >= d:
315
+ tt = log_alpha[:, t - d, u] + acts[:, t - d, 0, self.blank - 1 - i]
316
+ log_alpha[:, t, u] = torch.logsumexp(
317
+ torch.stack([1.0 * log_alpha[:, t, u], tt]), dim=0
318
+ )
319
+
320
+ else:
321
+ if t == 0:
322
+ # in case of (u > 0, t = 0), this is only reached from
323
+ # (t, u - 1) with a label emission.
324
+ gathered = torch.gather(
325
+ acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64)
326
+ ).reshape(-1)
327
+ log_alpha[:, t, u] = log_alpha[:, t, u - 1] + gathered
328
+ else:
329
+ # here both t and u are > 0, this state is reachable
330
+ # with two possibilities: (t - d, u) with emission of
331
+ # blank with duration d, or (t, u - 1) with a label emission.
332
+
333
+ # first we take care of the standard blank.
334
+ log_alpha[:, t, u] = torch.logsumexp(
335
+ torch.stack(
336
+ [
337
+ log_alpha[:, t - 1, u] + acts[:, t - 1, u, self.blank],
338
+ log_alpha[:, t, u - 1]
339
+ + torch.gather(
340
+ acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64)
341
+ ).reshape(-1),
342
+ ]
343
+ ),
344
+ dim=0,
345
+ )
346
+
347
+ # now we go over all big blanks. They need to be considered if current t >= blank duration d.
348
+ for i, d in enumerate(self.big_blank_durations):
349
+ if t >= d:
350
+ tt = log_alpha[:, t - d, u] + acts[:, t - d, u, self.blank - 1 - i]
351
+ log_alpha[:, t, u] = torch.logsumexp(
352
+ torch.stack([1.0 * log_alpha[:, t, u], tt]), dim=0
353
+ )
354
+
355
+ log_probs = []
356
+ for b in range(B):
357
+ # here we need to add the final blank emission weights, which needs
358
+ # to consider all possible blank durations.
359
+ to_append = (
360
+ log_alpha[b, act_lens[b] - 1, label_lens[b]] + acts[b, act_lens[b] - 1, label_lens[b], self.blank]
361
+ )
362
+
363
+ for i, d in enumerate(self.big_blank_durations):
364
+ if act_lens[b] >= d:
365
+ tt = (
366
+ log_alpha[b, act_lens[b] - d, label_lens[b]]
367
+ + acts[b, act_lens[b] - d, label_lens[b], self.blank - 1 - i]
368
+ )
369
+ to_append = torch.logsumexp(torch.stack([1.0 * to_append, tt]), dim=0)
370
+
371
+ log_probs.append(to_append)
372
+ log_prob = torch.stack(log_probs)
373
+
374
+ return log_prob, log_alpha
nemo/collections/asr/losses/ssl_losses/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr.losses.ssl_losses.contrastive import ContrastiveLoss
nemo/collections/asr/losses/ssl_losses/contrastive.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from math import ceil
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from nemo.core import Loss, typecheck
22
+ from nemo.core.neural_types import AcousticEncodedRepresentation, LengthsType, LossType, NeuralType, SpectrogramType
23
+
24
+ __all__ = ["ContrastiveLoss"]
25
+
26
+
27
+ class ContrastiveLoss(Loss):
28
+ @property
29
+ def input_types(self):
30
+ """Input types definitions for Contrastive."""
31
+ return {
32
+ "spectrograms": NeuralType(("B", "D", "T"), SpectrogramType()),
33
+ "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()),
34
+ "decoder_outputs": NeuralType(("B", "T", "D"), AcousticEncodedRepresentation()),
35
+ "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
36
+ }
37
+
38
+ @property
39
+ def output_types(self):
40
+ """Output types definitions for Contrastive.
41
+ loss:
42
+ NeuralType(None)
43
+ """
44
+ return {"loss": NeuralType(elements_type=LossType())}
45
+
46
+ @property
47
+ def needs_labels(self):
48
+ return False
49
+
50
+ def __init__(
51
+ self,
52
+ in_dim: int,
53
+ proj_dim: int = 128,
54
+ combine_time_steps: int = 1,
55
+ num_negatives: int = 100,
56
+ quantized_targets: bool = False,
57
+ codebook_size: int = 320,
58
+ prob_ppl_weight: float = 0.1,
59
+ logit_temp: float = 0.1,
60
+ reduce: str = "sum",
61
+ sample_from_same_utterance_only: bool = True,
62
+ sample_from_non_masked: bool = False,
63
+ sample_from_codebook: bool = False,
64
+ group_loss: bool = False,
65
+ num_groups: int = 2,
66
+ quantizer_temp_start: float = 2,
67
+ quantizer_temp_min: float = 0.5,
68
+ quantizer_temp_decay: float = 0.999995,
69
+ mask_threshold: float = 0.8,
70
+ store_ids: bool = True,
71
+ reduce_ids: bool = False,
72
+ multiplier: float = 16.0,
73
+ ):
74
+ """
75
+ Loss function representing the contrastive task of identifying the true latent speech representation of
76
+ the masked spectrogram steps from a set of sampled distractors.
77
+
78
+ Args:
79
+ in_dim: Number of spectrogram channels.
80
+ proj_dim: Number of channels in the model outputs.
81
+ combine_time_steps: How many time steps should be combined into a single representation.
82
+ num_negatives: Number of sampled negatives for each target.
83
+ quantized_targets: Bool that determines if the targets should be quantized.
84
+ codebook_size: Number of vectors in the codebook per group.
85
+ prob_ppl_weight: Float multiplier on the perplexity loss for target quantization.
86
+ logit_temp: Float temperature for normalizing logits.
87
+ reduce: String representing the type of reduction used for cross entropy.
88
+ sample_from_same_utterance_only: Bool that determines if negatives should be sampled only from same utterance.
89
+ sample_from_non_masked: Bool that determines if negatives should be sampled from non-masked steps of the spectrogram.
90
+ sample_from_codebook: Bool that determines if negatives should be sampled from entire codebook.
91
+ group_loss: Bool that determines if loss should be computed separately for each group in the quantizer codebook.
92
+ num_groups: Number of groups in the quantizer codebook.
93
+ quantizer_temp_start: Starting temperature in quantizer.
94
+ quantizer_temp_min: Minimum temperature in quantizer.
95
+ quantizer_temp_decay: Decay rate of quantizer temperature per global step.
96
+ mask_threshold: Float threshold for determining if a time step of the spectrogram is masked based on percent of masked channels.
97
+ store_ids: Bool that determines if the quantizer ids will be stored to be potentially used by other losses.
98
+ reduce_ids: Bool that determines if we convert any sequence of consecutive equivalent ids to a single occurence of that id.
99
+ multiplier: Float multipler on final loss
100
+ """
101
+
102
+ super().__init__()
103
+ quantizer_temp = (quantizer_temp_start, quantizer_temp_min, quantizer_temp_decay)
104
+ self.quantized_targets = quantized_targets
105
+ self.num_negatives = num_negatives
106
+ self.prob_ppl_weight = prob_ppl_weight
107
+ if self.quantized_targets:
108
+ quantizer_cfg = {
109
+ "_target_": "nemo.collections.asr.parts.submodules.ssl_quantizers.GumbelVectorQuantizer",
110
+ "dim": in_dim * combine_time_steps,
111
+ "vq_dim": proj_dim,
112
+ "num_vars": codebook_size,
113
+ "groups": num_groups,
114
+ "temp": quantizer_temp,
115
+ "combine_groups": True,
116
+ "time_first": True,
117
+ }
118
+ self.quantizer = ContrastiveLoss.from_config_dict(quantizer_cfg)
119
+ self.prob_ppl_weight = prob_ppl_weight
120
+ self.logit_temp = logit_temp
121
+ self.reduce = reduce
122
+ self.combine_time_steps = combine_time_steps
123
+ self.sample_from_same_utterance_only = sample_from_same_utterance_only
124
+ self.sample_from_non_masked = sample_from_non_masked
125
+ self.sample_from_codebook = sample_from_codebook
126
+ self.group_loss = group_loss
127
+ self.mask_threshold = mask_threshold
128
+ self.multiplier = multiplier
129
+
130
+ self.store_ids = store_ids
131
+ self.reduce_ids = reduce_ids
132
+
133
+ if not self.quantized_targets:
134
+ self.target_proj = nn.Linear(in_dim * combine_time_steps, proj_dim)
135
+
136
+ def sample_negatives(self, y, num):
137
+ # y - T'xBxC or T'xC
138
+
139
+ high = y.shape[0]
140
+ neg_idxs = torch.multinomial(torch.ones((num, high), device=y.device), self.num_negatives)
141
+
142
+ negs = y[neg_idxs.view(-1)]
143
+ negs = negs.view((num, self.num_negatives) + y.shape[1:])
144
+ negs = negs.transpose(0, 1)
145
+ # negs - NxT'xBxC or NxT'xC
146
+
147
+ return negs, neg_idxs
148
+
149
+ @typecheck()
150
+ def forward(self, spectrograms, spec_masks, decoder_outputs, decoder_lengths=None):
151
+ targets = spectrograms.transpose(-2, -1)
152
+ masks = spec_masks.transpose(-2, -1)
153
+ # BxTxC
154
+ diff = int(ceil(targets.shape[1] / decoder_outputs.shape[1]) * decoder_outputs.shape[1]) - targets.shape[1]
155
+
156
+ if diff > 0:
157
+ targets = F.pad(targets, (0, 0, 0, diff))
158
+ masks = F.pad(masks, (0, 0, 0, diff))
159
+
160
+ targets = targets.reshape(targets.shape[0], decoder_outputs.shape[1], -1)
161
+ masks = masks.reshape(targets.shape[0], decoder_outputs.shape[1], -1)
162
+
163
+ if self.quantized_targets:
164
+ if self.store_ids:
165
+ # store ids for use by other losses
166
+ targets, prob_ppl_loss, cur_codebook_temp, self.target_ids = self.quantizer(targets, return_ids=True)
167
+
168
+ if self.reduce_ids:
169
+ # reduce consecutive equivalent ids to a single occurence
170
+ _, indices = torch.unique_consecutive(self.target_ids, return_inverse=True)
171
+ indices -= indices.min(dim=1, keepdims=True)[0]
172
+ reduced_ids = torch.zeros_like(self.target_ids)
173
+ reduced_ids = reduced_ids.scatter_(1, indices, self.target_ids)
174
+ reduced_lens = indices.max(dim=-1)[0] + 1
175
+
176
+ self.target_ids = reduced_ids.narrow(1, 0, reduced_lens.max())
177
+ self.target_lengths = reduced_lens
178
+
179
+ else:
180
+ self.target_lengths = None
181
+
182
+ else:
183
+ targets, prob_ppl_loss, cur_codebook_temp = self.quantizer(targets)
184
+ else:
185
+ targets = self.target_proj(targets)
186
+
187
+ if self.sample_from_same_utterance_only:
188
+ bs = decoder_outputs.shape[0]
189
+ masks = masks.mean(-1) > self.mask_threshold
190
+ out_masked_only = decoder_outputs[masks]
191
+ targets_masked_only = targets[masks]
192
+ out_masked_only = out_masked_only.reshape(bs, -1, out_masked_only.shape[-1])
193
+ targets_masked_only = targets_masked_only.reshape(bs, -1, targets_masked_only.shape[-1])
194
+
195
+ # BxT'xC
196
+ # number of masked time steps to predict (T')
197
+ # -> T'xBxC
198
+
199
+ out_masked_only = out_masked_only.transpose(0, 1)
200
+ targets_masked_only = targets_masked_only.transpose(0, 1)
201
+ # -> T'xBxC
202
+
203
+ if self.sample_from_non_masked:
204
+ # sample from all steps in utterance
205
+ negatives, _ = self.sample_negatives(
206
+ targets.transpose(0, 1),
207
+ targets_masked_only.size(0), # TxBxC # T'
208
+ )
209
+ else:
210
+ # only sample from masked steps in utterance
211
+ negatives, _ = self.sample_negatives(targets_masked_only, targets_masked_only.size(0)) # T'xBxC # T'
212
+ # NxT'xBxC
213
+
214
+ out_masked_only = out_masked_only.reshape(-1, out_masked_only.shape[-1])
215
+ targets_masked_only = targets_masked_only.reshape(-1, targets_masked_only.shape[-1])
216
+ negatives = negatives.reshape(self.num_negatives, -1, negatives.shape[-1])
217
+
218
+ # T'BxC and NxT'BxC
219
+
220
+ else:
221
+ masks = masks.mean(-1) > self.mask_threshold
222
+ out_masked_only = decoder_outputs[masks]
223
+ targets_masked_only = targets[masks]
224
+
225
+ # T'xC
226
+ # number of masked time steps to predict (T')
227
+
228
+ if self.group_loss:
229
+ num_groups = self.quantizer.groups
230
+ negatives = self.quantizer.vars.reshape(num_groups, self.quantizer.num_vars, -1)
231
+ # GxNx(C//G)
232
+ negatives = negatives.transpose(0, 1)
233
+ # NxGx(C//G)
234
+ negatives = negatives.unsqueeze(1).expand(-1, out_masked_only.shape[0], -1, -1)
235
+ # NxT'xGx(C//G)
236
+ negatives = negatives.reshape(negatives.shape[0], -1, negatives.shape[-1])
237
+ # NxT'Gx(C//G)
238
+
239
+ out_masked_only = out_masked_only.reshape(-1, out_masked_only.shape[-1] // num_groups)
240
+ targets_masked_only = targets_masked_only.reshape(-1, targets_masked_only.shape[-1] // num_groups)
241
+ # T'Gx(C//G)
242
+ elif self.sample_from_codebook:
243
+ # sample from the full codebook
244
+ negatives = self.quantizer.sample_from_codebook(self.num_negatives, targets_masked_only.size(0))
245
+ elif self.sample_from_non_masked:
246
+ # sample from all steps in batch
247
+ negatives, _ = self.sample_negatives(
248
+ targets.reshape(targets.shape[0] * targets.shape[1], -1),
249
+ targets_masked_only.size(0), # BTxC
250
+ ) # T'
251
+ else:
252
+ # only sample from masked steps
253
+ negatives, _ = self.sample_negatives(targets_masked_only, targets_masked_only.size(0)) # T'xC # T'
254
+ # NxT'xC
255
+
256
+ # Calculate similarity between outputs and all targets
257
+ similarity_scores = self._calculate_similarity(out_masked_only, negatives, targets_masked_only)
258
+ # (1+N)xT'
259
+ # cosine similarity of outs with targets + N negatives
260
+
261
+ # Create targets of size T
262
+ similarity_targets = decoder_outputs.new_zeros(similarity_scores.size(1), dtype=torch.long)
263
+ # T'
264
+ # targets are 0, since it's the first, followed by N sampled negatives
265
+
266
+ # Transpose similarity scores to TxF for loss
267
+ similarity_scores = similarity_scores.transpose(0, 1)
268
+ # T'x(1+N)
269
+
270
+ loss = F.cross_entropy(similarity_scores, similarity_targets, reduction=self.reduce)
271
+
272
+ sample_size = similarity_targets.numel()
273
+
274
+ if self.prob_ppl_weight != 0 and self.quantized_targets:
275
+ prob_ppl_loss = self.prob_ppl_weight * prob_ppl_loss * sample_size
276
+ loss += prob_ppl_loss
277
+
278
+ if not isinstance(loss, torch.Tensor):
279
+ loss = torch.Tensor([0]).to(device=decoder_outputs.device)
280
+
281
+ batch_size = spectrograms.shape[0]
282
+ loss *= self.multiplier / batch_size
283
+
284
+ return loss
285
+
286
+ def _calculate_similarity(self, logits, negatives, targets):
287
+ neg_is_pos = (targets == negatives).all(-1)
288
+ # NxT' - true where the negative is actually the positive
289
+ targets = targets.unsqueeze(0)
290
+ # 1xT'xC
291
+ targets = torch.cat([targets, negatives], dim=0)
292
+ # (1+N)xT'XC
293
+ logits = torch.cosine_similarity(
294
+ logits.float().unsqueeze(0).expand(targets.shape[0], -1, -1), targets.float(), dim=-1
295
+ ).type_as(logits)
296
+ # (1+N)xT'
297
+ logits /= self.logit_temp
298
+ if neg_is_pos.any():
299
+ logits[1:][neg_is_pos] = float("-inf")
300
+ return logits
301
+
302
+ def set_num_updates(self, num_updates):
303
+ if self.quantized_targets:
304
+ self.quantizer.set_num_updates(num_updates)
nemo/collections/asr/losses/ssl_losses/ctc.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr.losses import CTCLoss
16
+ from nemo.core import Loss, typecheck
17
+ from nemo.core.neural_types import LabelsType, LengthsType, LossType, NeuralType, SpectrogramType, VoidType
18
+
19
+ __all__ = ["CTCLossForSSL"]
20
+
21
+
22
+ class CTCLossForSSL(Loss):
23
+ @property
24
+ def input_types(self):
25
+ """Input types definitions for Contrastive.
26
+ """
27
+ return {
28
+ "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()),
29
+ "decoder_outputs": NeuralType(("B", "T", "D"), VoidType()),
30
+ "targets": NeuralType(('B', 'T'), LabelsType()),
31
+ "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
32
+ "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
33
+ }
34
+
35
+ @property
36
+ def output_types(self):
37
+ """Output types definitions for Contrastive.
38
+ loss:
39
+ NeuralType(None)
40
+ """
41
+ return {"loss": NeuralType(elements_type=LossType())}
42
+
43
+ @property
44
+ def needs_labels(self):
45
+ return True
46
+
47
+ def __init__(self, num_classes, zero_infinity=True, reduction='mean_batch'):
48
+ super().__init__()
49
+ self.loss = CTCLoss(num_classes=num_classes, reduction=reduction, zero_infinity=zero_infinity)
50
+
51
+ @typecheck()
52
+ def forward(self, spec_masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None):
53
+ loss = self.loss(
54
+ log_probs=decoder_outputs, targets=targets, input_lengths=decoder_lengths, target_lengths=target_lengths
55
+ )
56
+
57
+ return loss
nemo/collections/asr/losses/ssl_losses/mlm.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from torch import nn
18
+
19
+ from nemo.core import Loss, typecheck
20
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType, SpectrogramType
21
+
22
+ __all__ = ["MLMLoss"]
23
+
24
+
25
+ class MLMLoss(Loss):
26
+ @property
27
+ def input_types(self):
28
+ """Input types definitions for Contrastive."""
29
+ return {
30
+ "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType(), optional=True),
31
+ "decoder_outputs": NeuralType(("B", "T", "D"), LogprobsType()),
32
+ "targets": NeuralType(('B', 'T'), LabelsType()),
33
+ "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
34
+ "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
35
+ "masks": NeuralType(("B", "D", "T"), SpectrogramType(), optional=True),
36
+ }
37
+
38
+ @property
39
+ def output_types(self):
40
+ """Output types definitions for Contrastive.
41
+ loss:
42
+ NeuralType(None)
43
+ """
44
+ return {"loss": NeuralType(elements_type=LossType())}
45
+
46
+ @property
47
+ def needs_labels(self):
48
+ return True
49
+
50
+ def __init__(
51
+ self,
52
+ combine_time_steps: int = 1,
53
+ mask_threshold: float = 0.8,
54
+ ):
55
+ super().__init__()
56
+ self.nll_loss = nn.NLLLoss()
57
+ self.combine_time_steps = combine_time_steps
58
+ self.mask_threshold = mask_threshold
59
+
60
+ @typecheck()
61
+ def forward(
62
+ self, decoder_outputs, targets, decoder_lengths=None, target_lengths=None, spec_masks=None, masks=None
63
+ ):
64
+
65
+ if masks is None:
66
+ masks = spec_masks
67
+
68
+ # B,D,T -> B,T,D
69
+ masks = masks.transpose(1, 2)
70
+
71
+ masks = masks.reshape(masks.shape[0], masks.shape[1] // self.combine_time_steps, -1)
72
+ masks = masks.mean(-1) > self.mask_threshold
73
+
74
+ out_masked_only = decoder_outputs[masks]
75
+ targets = F.pad(targets, (0, masks.shape[-1] - targets.shape[-1]))
76
+ targets_masked_only = targets[masks]
77
+
78
+ loss = self.nll_loss(out_masked_only, targets_masked_only)
79
+ loss = torch.mean(loss)
80
+
81
+ return loss
82
+
83
+
84
+ class MultiMLMLoss(Loss):
85
+ """
86
+ Masked language model loss for multiple decoders, where cross-entropy loss is applied separately on each decoder.
87
+ This loss can be used with `nemo.collections.asr.modules.ssl_modules.MultiSoftmaxDecoder` to train a model with multiple targets per frame.
88
+ Reference: https://arxiv.org/abs/2202.01855
89
+ """
90
+
91
+ @property
92
+ def input_types(self):
93
+ if self.squeeze_single and self.num_decoders == 1:
94
+ decoder_outputs = NeuralType(("B", "T", "C"), LogprobsType())
95
+ targets = NeuralType(('B', 'T'), LabelsType())
96
+ else:
97
+ decoder_outputs = NeuralType(("B", "T", "C", "H"), LogprobsType())
98
+ targets = NeuralType(("B", "T", "H"), LabelsType())
99
+ return {
100
+ "masks": NeuralType(("B", "D", "T"), SpectrogramType()),
101
+ "decoder_outputs": decoder_outputs,
102
+ "targets": targets,
103
+ "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
104
+ "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
105
+ }
106
+
107
+ def __init__(
108
+ self,
109
+ combine_time_steps: int = 1,
110
+ mask_threshold: float = 0.8,
111
+ num_decoders: int = 1,
112
+ squeeze_single: bool = False,
113
+ ):
114
+ super().__init__()
115
+ self.num_decoders = num_decoders
116
+ self.squeeze_single = squeeze_single
117
+ self.mlm_loss = MLMLoss(combine_time_steps, mask_threshold)
118
+
119
+ @typecheck()
120
+ def forward(self, masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None):
121
+ if self.squeeze_single and self.num_decoders == 1:
122
+ return self.mlm_loss(
123
+ spec_masks=masks,
124
+ decoder_outputs=decoder_outputs,
125
+ targets=targets,
126
+ decoder_lengths=decoder_lengths,
127
+ target_lengths=target_lengths,
128
+ )
129
+ loss = 0.0
130
+ for i in range(self.num_decoders):
131
+ loss += self.mlm_loss(
132
+ spec_masks=masks,
133
+ decoder_outputs=decoder_outputs[:, :, :, i],
134
+ targets=targets[:, :, i],
135
+ decoder_lengths=decoder_lengths,
136
+ target_lengths=target_lengths,
137
+ )
138
+ return loss / self.num_decoders
nemo/collections/asr/losses/ssl_losses/rnnt.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr.losses.rnnt import RNNTLoss
16
+ from nemo.core import Loss, typecheck
17
+ from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType, SpectrogramType
18
+
19
+ __all__ = ["RNNTLossForSSL"]
20
+
21
+
22
+ class RNNTLossForSSL(Loss):
23
+ @property
24
+ def input_types(self):
25
+ """Input types definitions for Contrastive.
26
+ """
27
+ return {
28
+ "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()),
29
+ "decoder_outputs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()),
30
+ "targets": NeuralType(('B', 'T'), LabelsType()),
31
+ "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
32
+ "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True),
33
+ }
34
+
35
+ @property
36
+ def output_types(self):
37
+ """Output types definitions for Contrastive.
38
+ loss:
39
+ NeuralType(None)
40
+ """
41
+ return {"loss": NeuralType(elements_type=LossType())}
42
+
43
+ @property
44
+ def needs_labels(self):
45
+ return True
46
+
47
+ def __init__(self, num_classes):
48
+ super().__init__()
49
+ self.loss = RNNTLoss(num_classes=num_classes)
50
+
51
+ @typecheck()
52
+ def forward(self, spec_masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None):
53
+
54
+ loss = self.loss(
55
+ log_probs=decoder_outputs, targets=targets, input_lengths=decoder_lengths, target_lengths=target_lengths
56
+ )
57
+
58
+ return loss
nemo/collections/asr/metrics/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from nemo.collections.asr.metrics.bleu import BLEU
16
+ from nemo.collections.asr.metrics.wer import WER
nemo/collections/asr/metrics/bleu.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Literal, Optional, Sequence, Union
16
+
17
+ import torch
18
+ from torchmetrics.functional.text.bleu import _bleu_score_compute
19
+ from torchmetrics.text import SacreBLEUScore
20
+
21
+ from nemo.collections.asr.parts.submodules.ctc_decoding import AbstractCTCDecoding
22
+ from nemo.collections.asr.parts.submodules.multitask_decoding import AbstractMultiTaskDecoding
23
+ from nemo.collections.asr.parts.submodules.rnnt_decoding import AbstractRNNTDecoding
24
+ from nemo.utils import logging
25
+
26
+ __all__ = ['BLEU']
27
+
28
+
29
+ def move_dimension_to_the_front(tensor, dim_index):
30
+ all_dims = list(range(tensor.ndim))
31
+ return tensor.permute(*([dim_index] + all_dims[:dim_index] + all_dims[dim_index + 1 :]))
32
+
33
+
34
+ # TODO: Add documentation
35
+ class BLEU(SacreBLEUScore):
36
+ """
37
+ This metric computes numerator, denominator, hypotheses lengths, and target lengths for Overall Bilingual Evaluation Understudy (BLEU)
38
+ between prediction and reference texts. When doing distributed training/evaluation the result of
39
+ ``res=BLEU.(predictions, predictions_lengths, targets, target_lengths)``
40
+ calls will be all-reduced between all workers using SUM operations.
41
+
42
+ If used with PytorchLightning LightningModule, include bleu_num bleur_den, bleu_pred_len, and bleu_target_len values inside
43
+ validation_step results. Then aggregate (sum) then at the end of validation epoch to correctly compute validation BLEUR.
44
+
45
+ Example:
46
+ def validation_step(self, batch, batch_idx):
47
+ ...
48
+ bleu_values = self.bleu(predictions, predictions_len, transcript, transcript_len)
49
+ self.val_outputs = {'val_loss': loss_value, **bleu_values}
50
+ return self.val_outputs
51
+
52
+ def on_validation_epoch_end(self):
53
+ ...
54
+ bleu_num = torch.stack([x['val_wer_num'] for x in self.val_outputs]).sum()
55
+ bleu_denom = torch.stack([x['val_wer_denom'] for x in self.val_outputs]).sum()
56
+ bleu_num = torch.stack([x[f"val_bleu_num"] for x in outputs]).sum(dim=0)
57
+ bleu_denom = torch.stack([x[f"val_bleu_denom"] for x in outputs]).sum(dim=0)
58
+
59
+ val_bleu = {"val_bleu": self.bleu._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom)}
60
+ tensorboard_logs.update(val_bleu)
61
+
62
+ self.val_outputs.clear() # free memory
63
+ return {'val_loss': val_loss_mean, 'log': tensorboard_logs}
64
+
65
+ Args:
66
+ decoding: An instance of CTCDecoding, RNNTDecoding, or MultiTaskDecoding.
67
+ tokenize: Desired tokenizer for BLEU evaluation. (Depending on language, this will drastically affect BLEU score.)
68
+ n_gram: Maximum number of n_grams to compute BLEU values over. Max: 4.
69
+ lowercase: Whether to lowercase all inputs.
70
+ weights: List of float values to weight each n_gram score.
71
+ log_prediction: Whether to log a single decoded sample per call.
72
+ batch_dim_index: Index corresponding to batch dimension. (For RNNT.)
73
+ dist_dync_on_step: Whether to perform reduction on forward pass of metric.
74
+
75
+ Returns:
76
+ res: a tuple of 3 zero dimensional float32 ``torch.Tensor` objects: a WER score, a sum of Levenstein's
77
+ distances for all prediction - reference pairs, total number of words in all references.
78
+ """
79
+
80
+ full_state_update: bool = True
81
+
82
+ def __init__(
83
+ self,
84
+ decoding: Union[AbstractCTCDecoding, AbstractRNNTDecoding, AbstractMultiTaskDecoding],
85
+ tokenize: Literal["none", "13a", "zh", "intl", "char"] = "13a",
86
+ n_gram: int = 4,
87
+ lowercase: bool = False,
88
+ weights: Optional[Sequence[float]] = None,
89
+ smooth: bool = False,
90
+ log_prediction=True,
91
+ batch_dim_index=0,
92
+ dist_sync_on_step=False,
93
+ ):
94
+ super().__init__(
95
+ tokenize=tokenize,
96
+ n_gram=n_gram,
97
+ lowercase=lowercase,
98
+ weights=weights,
99
+ smooth=smooth,
100
+ dist_sync_on_step=dist_sync_on_step,
101
+ )
102
+ self.decoding = decoding
103
+ self.decode = None
104
+ if isinstance(self.decoding, AbstractRNNTDecoding):
105
+ self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids, targets: self.decoding.rnnt_decoder_predictions_tensor(
106
+ encoder_output=predictions, encoded_lengths=predictions_lengths
107
+ )
108
+ elif isinstance(self.decoding, AbstractCTCDecoding):
109
+ self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids, targets: self.decoding.ctc_decoder_predictions_tensor(
110
+ decoder_outputs=predictions,
111
+ decoder_lengths=predictions_lengths,
112
+ fold_consecutive=self.fold_consecutive,
113
+ )
114
+ elif isinstance(self.decoding, AbstractMultiTaskDecoding):
115
+ self.decode = lambda predictions, prediction_lengths, predictions_mask, input_ids, targets: self.decoding.decode_predictions_tensor(
116
+ encoder_hidden_states=predictions,
117
+ encoder_input_mask=predictions_mask,
118
+ decoder_input_ids=input_ids,
119
+ return_hypotheses=False,
120
+ )
121
+ else:
122
+ raise TypeError(f"WER metric does not support decoding of type {type(self.decoding)}")
123
+
124
+ self.tokenize = tokenize
125
+ self.log_prediction = log_prediction
126
+ self.batch_dim_index = batch_dim_index
127
+
128
+ def update(
129
+ self,
130
+ predictions: torch.Tensor,
131
+ predictions_lengths: torch.Tensor,
132
+ targets: torch.Tensor,
133
+ targets_lengths: torch.Tensor,
134
+ predictions_mask: Optional[torch.Tensor] = None,
135
+ input_ids: Optional[torch.Tensor] = None,
136
+ ):
137
+ """
138
+ Updates metric state.
139
+ Args:
140
+ predictions: an integer torch.Tensor of shape ``[Batch, Time, {Vocabulary}]`` (if ``batch_dim_index == 0``) or
141
+ ``[Time, Batch]`` (if ``batch_dim_index == 1``)
142
+ predictions_lengths: an integer torch.Tensor of shape ``[Batch]``
143
+ targets: an integer torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or
144
+ ``[Time, Batch]`` (if ``batch_dim_index == 1``)
145
+ target_lengths: an integer torch.Tensor of shape ``[Batch]``
146
+ predictions_mask: a bool torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or
147
+ ``[Time, Batch]`` (if ``batch_dim_index == 1``). Required for MultiTaskDecoding.
148
+ input_ids: an int torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or
149
+ ``[Time, Batch]`` (if ``batch_dim_index == 1``). Required for MultiTaskDecoding.
150
+ """
151
+ references = []
152
+ with torch.no_grad():
153
+ tgt_lenths_cpu_tensor = targets_lengths.long().cpu()
154
+ targets_cpu_tensor = targets.long().cpu()
155
+ # check batch_dim_index is first dim
156
+ if self.batch_dim_index != 0:
157
+ targets_cpu_tensor = move_dimension_to_the_front(targets_cpu_tensor, self.batch_dim_index)
158
+ # iterate over batch
159
+ for ind in range(targets_cpu_tensor.shape[0]):
160
+ tgt_len = tgt_lenths_cpu_tensor[ind].item()
161
+ target = targets_cpu_tensor[ind][:tgt_len].numpy().tolist()
162
+ reference = self.decoding.decode_tokens_to_str(target)
163
+ references.append(reference)
164
+ hypotheses = self.decode(predictions, predictions_lengths, predictions_mask, input_ids, targets)
165
+
166
+ if self.log_prediction:
167
+ logging.info("\n")
168
+ logging.info(f"reference:{references[0]}")
169
+ logging.info(f"predicted:{hypotheses[0]}")
170
+
171
+ super().update(
172
+ [h.text for h in hypotheses], [references]
173
+ ) # Note: [references] since BLEU allows multiple references.
174
+
175
+ def compute(self, return_all_metrics=True, prefix="", suffix=""):
176
+ """
177
+ Returns BLEU values and component metrics.
178
+
179
+ Args:
180
+ return_all_metrics: bool flag. On True, BLEU and composite metrics returned. If False, returns
181
+ only BLEU. Default: True.
182
+ prefix: str to prepend to metric value keys.
183
+ suffix: str to append to metric value keys.
184
+
185
+ Returns:
186
+ Dict: key-value pairs of BLEU metrics and values. Keys are prepended and appended with prefix
187
+ and suffix flags, respectively.
188
+ """
189
+ bleu = super().compute()
190
+ if return_all_metrics:
191
+ return {
192
+ f"{prefix}bleu{suffix}": bleu,
193
+ f"{prefix}bleu_pred_len{suffix}": self.preds_len.detach().float(),
194
+ f"{prefix}bleu_target_len{suffix}": self.target_len.detach().float(),
195
+ f"{prefix}bleu_num{suffix}": self.numerator.detach().float(),
196
+ f"{prefix}bleu_denom{suffix}": self.denominator.detach().float(),
197
+ }
198
+ return {
199
+ f"{prefix}bleu{suffix}": bleu,
200
+ }
201
+
202
+ # Adding wrapper to avoid imports and extra variables over the namespace
203
+ def _compute_bleu(
204
+ self,
205
+ predictions_lengths,
206
+ targets_lengths,
207
+ numerator,
208
+ denominator,
209
+ ):
210
+ return _bleu_score_compute(
211
+ predictions_lengths, targets_lengths, numerator, denominator, self.n_gram, self.weights, self.smooth
212
+ )